Fix #6141 - super script and subscribe
[roojs1] / roojs-bootstrap-debug.js
1 /**
2  * set the version of bootstrap based on the stylesheet...
3  *
4  */
5
6 Roo.bootstrap.version = (
7         function() {
8                 var ret=3;
9                 Roo.each(document.styleSheets, function(s) {
10                     if ( s.href  && s.href.match(/css-bootstrap4/)) {
11                         ret=4;
12                     }
13                 });
14         return ret;
15 })(); /*
16  * - LGPL
17  *
18  * base class for bootstrap elements.
19  * 
20  */
21
22 Roo.bootstrap = Roo.bootstrap || {};
23 /**
24  * @class Roo.bootstrap.Component
25  * @extends Roo.Component
26  * Bootstrap Component base class
27  * @cfg {String} cls css class
28  * @cfg {String} style any extra css
29  * @cfg {Object} xattr extra attributes to add to 'element' (used by builder to store stuff.)
30  * @cfg {Boolean} can_build_overlaid  True if element can be rebuild from a HTML page
31  * @cfg {string} dataId cutomer id
32  * @cfg {string} name Specifies name attribute
33  * @cfg {string} tooltip  Text for the tooltip
34  * @cfg {string} container_method method to fetch parents container element (used by NavHeaderbar -  getHeaderChildContainer)
35  * @cfg {string|object} visibilityEl (el|parent) What element to use for visibility (@see getVisibilityEl())
36  
37  * @constructor
38  * Do not use directly - it does not do anything..
39  * @param {Object} config The config object
40  */
41
42
43
44 Roo.bootstrap.Component = function(config){
45     Roo.bootstrap.Component.superclass.constructor.call(this, config);
46        
47     this.addEvents({
48         /**
49          * @event childrenrendered
50          * Fires when the children have been rendered..
51          * @param {Roo.bootstrap.Component} this
52          */
53         "childrenrendered" : true
54         
55         
56         
57     });
58     
59     
60 };
61
62 Roo.extend(Roo.bootstrap.Component, Roo.BoxComponent,  {
63     
64     
65     allowDomMove : false, // to stop relocations in parent onRender...
66     
67     cls : false,
68     
69     style : false,
70     
71     autoCreate : false,
72     
73     tooltip : null,
74     /**
75      * Initialize Events for the element
76      */
77     initEvents : function() { },
78     
79     xattr : false,
80     
81     parentId : false,
82     
83     can_build_overlaid : true,
84     
85     container_method : false,
86     
87     dataId : false,
88     
89     name : false,
90     
91     parent: function() {
92         // returns the parent component..
93         return Roo.ComponentMgr.get(this.parentId)
94         
95         
96     },
97     
98     // private
99     onRender : function(ct, position)
100     {
101        // Roo.log("Call onRender: " + this.xtype);
102         
103         Roo.bootstrap.Component.superclass.onRender.call(this, ct, position);
104         
105         if(this.el){
106             if (this.el.attr('xtype')) {
107                 this.el.attr('xtypex', this.el.attr('xtype'));
108                 this.el.dom.removeAttribute('xtype');
109                 
110                 this.initEvents();
111             }
112             
113             return;
114         }
115         
116          
117         
118         var cfg = Roo.apply({},  this.getAutoCreate());
119         
120         cfg.id = this.id || Roo.id();
121         
122         // fill in the extra attributes 
123         if (this.xattr && typeof(this.xattr) =='object') {
124             for (var i in this.xattr) {
125                 cfg[i] = this.xattr[i];
126             }
127         }
128         
129         if(this.dataId){
130             cfg.dataId = this.dataId;
131         }
132         
133         if (this.cls) {
134             cfg.cls = (typeof(cfg.cls) == 'undefined') ? this.cls : cfg.cls + ' ' + this.cls;
135         }
136         
137         if (this.style) { // fixme needs to support more complex style data.
138             cfg.style = this.style;
139         }
140         
141         if(this.name){
142             cfg.name = this.name;
143         }
144         
145         this.el = ct.createChild(cfg, position);
146         
147         if (this.tooltip) {
148             this.tooltipEl().attr('tooltip', this.tooltip);
149         }
150         
151         if(this.tabIndex !== undefined){
152             this.el.dom.setAttribute('tabIndex', this.tabIndex);
153         }
154         
155         this.initEvents();
156         
157     },
158     /**
159      * Fetch the element to add children to
160      * @return {Roo.Element} defaults to this.el
161      */
162     getChildContainer : function()
163     {
164         return this.el;
165     },
166     /**
167      * Fetch the element to display the tooltip on.
168      * @return {Roo.Element} defaults to this.el
169      */
170     tooltipEl : function()
171     {
172         return this.el;
173     },
174         
175     addxtype  : function(tree,cntr)
176     {
177         var cn = this;
178         
179         cn = Roo.factory(tree);
180         //Roo.log(['addxtype', cn]);
181            
182         cn.parentType = this.xtype; //??
183         cn.parentId = this.id;
184         
185         cntr = (typeof(cntr) == 'undefined' ) ? 'getChildContainer' : cntr;
186         if (typeof(cn.container_method) == 'string') {
187             cntr = cn.container_method;
188         }
189         
190         
191         var has_flexy_each =  (typeof(tree['flexy:foreach']) != 'undefined');
192         
193         var has_flexy_if =  (typeof(tree['flexy:if']) != 'undefined');
194         
195         var build_from_html =  Roo.XComponent.build_from_html;
196           
197         var is_body  = (tree.xtype == 'Body') ;
198           
199         var page_has_body = (Roo.get(document.body).attr('xtype') == 'Roo.bootstrap.Body');
200           
201         var self_cntr_el = Roo.get(this[cntr](false));
202         
203         // do not try and build conditional elements 
204         if ((has_flexy_each || has_flexy_if || this.can_build_overlaid == false ) && build_from_html) {
205             return false;
206         }
207         
208         if (!has_flexy_each || !build_from_html || is_body || !page_has_body) {
209             if(!has_flexy_if || typeof(tree.name) == 'undefined' || !build_from_html || is_body || !page_has_body){
210                 return this.addxtypeChild(tree,cntr, is_body);
211             }
212             
213             var echild =self_cntr_el ? self_cntr_el.child('>*[name=' + tree.name + ']') : false;
214                 
215             if(echild){
216                 return this.addxtypeChild(Roo.apply({}, tree),cntr);
217             }
218             
219             Roo.log('skipping render');
220             return cn;
221             
222         }
223         
224         var ret = false;
225         if (!build_from_html) {
226             return false;
227         }
228         
229         // this i think handles overlaying multiple children of the same type
230         // with the sam eelement.. - which might be buggy..
231         while (true) {
232             var echild =self_cntr_el ? self_cntr_el.child('>*[xtype]') : false;
233             
234             if (!echild) {
235                 break;
236             }
237             
238             if (echild && echild.attr('xtype').split('.').pop() != cn.xtype) {
239                 break;
240             }
241             
242             ret = this.addxtypeChild(Roo.apply({}, tree),cntr);
243         }
244        
245         return ret;
246     },
247     
248     
249     addxtypeChild : function (tree, cntr, is_body)
250     {
251         Roo.debug && Roo.log('addxtypeChild:' + cntr);
252         var cn = this;
253         cntr = (typeof(cntr) == 'undefined' ) ? 'getChildContainer' : cntr;
254         
255         
256         var has_flexy = (typeof(tree['flexy:if']) != 'undefined') ||
257                     (typeof(tree['flexy:foreach']) != 'undefined');
258           
259     
260         
261         skip_children = false;
262         // render the element if it's not BODY.
263         if (!is_body) {
264             
265             // if parent was disabled, then do not try and create the children..
266             if(!this[cntr](true)){
267                 tree.items = [];
268                 return tree;
269             }
270            
271             cn = Roo.factory(tree);
272            
273             cn.parentType = this.xtype; //??
274             cn.parentId = this.id;
275             
276             var build_from_html =  Roo.XComponent.build_from_html;
277             
278             
279             // does the container contain child eleemnts with 'xtype' attributes.
280             // that match this xtype..
281             // note - when we render we create these as well..
282             // so we should check to see if body has xtype set.
283             if (build_from_html && Roo.get(document.body).attr('xtype') == 'Roo.bootstrap.Body') {
284                
285                 var self_cntr_el = Roo.get(this[cntr](false));
286                 var echild =self_cntr_el ? self_cntr_el.child('>*[xtype]') : false;
287                 if (echild) { 
288                     //Roo.log(Roo.XComponent.build_from_html);
289                     //Roo.log("got echild:");
290                     //Roo.log(echild);
291                 }
292                 // there is a scenario where some of the child elements are flexy:if (and all of the same type)
293                 // and are not displayed -this causes this to use up the wrong element when matching.
294                 // at present the only work around for this is to nest flexy:if elements in another element that is always rendered.
295                 
296                 
297                 if (echild && echild.attr('xtype').split('.').pop() == cn.xtype) {
298                   //  Roo.log("found child for " + this.xtype +": " + echild.attr('xtype') );
299                   
300                   
301                   
302                     cn.el = echild;
303                   //  Roo.log("GOT");
304                     //echild.dom.removeAttribute('xtype');
305                 } else {
306                     Roo.debug && Roo.log("MISSING " + cn.xtype + " on child of " + (this.el ? this.el.attr('xbuilderid') : 'no parent'));
307                     Roo.debug && Roo.log(self_cntr_el);
308                     Roo.debug && Roo.log(echild);
309                     Roo.debug && Roo.log(cn);
310                 }
311             }
312            
313             
314            
315             // if object has flexy:if - then it may or may not be rendered.
316             if (build_from_html && has_flexy && !cn.el &&  cn.can_build_overlaid) {
317                 // skip a flexy if element.
318                 Roo.debug && Roo.log('skipping render');
319                 Roo.debug && Roo.log(tree);
320                 if (!cn.el) {
321                     Roo.debug && Roo.log('skipping all children');
322                     skip_children = true;
323                 }
324                 
325              } else {
326                  
327                 // actually if flexy:foreach is found, we really want to create 
328                 // multiple copies here...
329                 //Roo.log('render');
330                 //Roo.log(this[cntr]());
331                 // some elements do not have render methods.. like the layouts...
332                 /*
333                 if(this[cntr](true) === false){
334                     cn.items = [];
335                     return cn;
336                 }
337                 */
338                 cn.render && cn.render(this[cntr](true));
339                 
340              }
341             // then add the element..
342         }
343          
344         // handle the kids..
345         
346         var nitems = [];
347         /*
348         if (typeof (tree.menu) != 'undefined') {
349             tree.menu.parentType = cn.xtype;
350             tree.menu.triggerEl = cn.el;
351             nitems.push(cn.addxtype(Roo.apply({}, tree.menu)));
352             
353         }
354         */
355         if (!tree.items || !tree.items.length) {
356             cn.items = nitems;
357             //Roo.log(["no children", this]);
358             
359             return cn;
360         }
361          
362         var items = tree.items;
363         delete tree.items;
364         
365         //Roo.log(items.length);
366             // add the items..
367         if (!skip_children) {    
368             for(var i =0;i < items.length;i++) {
369               //  Roo.log(['add child', items[i]]);
370                 nitems.push(cn.addxtype(Roo.apply({}, items[i])));
371             }
372         }
373         
374         cn.items = nitems;
375         
376         //Roo.log("fire childrenrendered");
377         
378         cn.fireEvent('childrenrendered', this);
379         
380         return cn;
381     },
382     
383     /**
384      * Set the element that will be used to show or hide
385      */
386     setVisibilityEl : function(el)
387     {
388         this.visibilityEl = el;
389     },
390     
391      /**
392      * Get the element that will be used to show or hide
393      */
394     getVisibilityEl : function()
395     {
396         if (typeof(this.visibilityEl) == 'object') {
397             return this.visibilityEl;
398         }
399         
400         if (typeof(this.visibilityEl) == 'string') {
401             return this.visibilityEl == 'parent' ? this.parent().getEl() : this.getEl();
402         }
403         
404         return this.getEl();
405     },
406     
407     /**
408      * Show a component - removes 'hidden' class
409      */
410     show : function()
411     {
412         if(!this.getVisibilityEl()){
413             return;
414         }
415          
416         this.getVisibilityEl().removeClass(['hidden','d-none']);
417         
418         this.fireEvent('show', this);
419         
420         
421     },
422     /**
423      * Hide a component - adds 'hidden' class
424      */
425     hide: function()
426     {
427         if(!this.getVisibilityEl()){
428             return;
429         }
430         
431         this.getVisibilityEl().addClass(['hidden','d-none']);
432         
433         this.fireEvent('hide', this);
434         
435     }
436 });
437
438  /*
439  * - LGPL
440  *
441  * Body
442  *
443  */
444
445 /**
446  * @class Roo.bootstrap.Body
447  * @extends Roo.bootstrap.Component
448  * Bootstrap Body class
449  *
450  * @constructor
451  * Create a new body
452  * @param {Object} config The config object
453  */
454
455 Roo.bootstrap.Body = function(config){
456
457     config = config || {};
458
459     Roo.bootstrap.Body.superclass.constructor.call(this, config);
460     this.el = Roo.get(config.el ? config.el : document.body );
461     if (this.cls && this.cls.length) {
462         Roo.get(document.body).addClass(this.cls);
463     }
464 };
465
466 Roo.extend(Roo.bootstrap.Body, Roo.bootstrap.Component,  {
467
468     is_body : true,// just to make sure it's constructed?
469
470         autoCreate : {
471         cls: 'container'
472     },
473     onRender : function(ct, position)
474     {
475        /* Roo.log("Roo.bootstrap.Body - onRender");
476         if (this.cls && this.cls.length) {
477             Roo.get(document.body).addClass(this.cls);
478         }
479         // style??? xttr???
480         */
481     }
482
483
484
485
486 });
487 /*
488  * - LGPL
489  *
490  * button group
491  * 
492  */
493
494
495 /**
496  * @class Roo.bootstrap.ButtonGroup
497  * @extends Roo.bootstrap.Component
498  * Bootstrap ButtonGroup class
499  * @cfg {String} size lg | sm | xs (default empty normal)
500  * @cfg {String} align vertical | justified  (default none)
501  * @cfg {String} direction up | down (default down)
502  * @cfg {Boolean} toolbar false | true
503  * @cfg {Boolean} btn true | false
504  * 
505  * 
506  * @constructor
507  * Create a new Input
508  * @param {Object} config The config object
509  */
510
511 Roo.bootstrap.ButtonGroup = function(config){
512     Roo.bootstrap.ButtonGroup.superclass.constructor.call(this, config);
513 };
514
515 Roo.extend(Roo.bootstrap.ButtonGroup, Roo.bootstrap.Component,  {
516     
517     size: '',
518     align: '',
519     direction: '',
520     toolbar: false,
521     btn: true,
522
523     getAutoCreate : function(){
524         var cfg = {
525             cls: 'btn-group',
526             html : null
527         };
528         
529         cfg.html = this.html || cfg.html;
530         
531         if (this.toolbar) {
532             cfg = {
533                 cls: 'btn-toolbar',
534                 html: null
535             };
536             
537             return cfg;
538         }
539         
540         if (['vertical','justified'].indexOf(this.align)!==-1) {
541             cfg.cls = 'btn-group-' + this.align;
542             
543             if (this.align == 'justified') {
544                 console.log(this.items);
545             }
546         }
547         
548         if (['lg','sm','xs'].indexOf(this.size)!==-1) {
549             cfg.cls += ' btn-group-' + this.size;
550         }
551         
552         if (this.direction == 'up') {
553             cfg.cls += ' dropup' ;
554         }
555         
556         return cfg;
557     },
558     /**
559      * Add a button to the group (similar to NavItem API.)
560      */
561     addItem : function(cfg)
562     {
563         var cn = new Roo.bootstrap.Button(cfg);
564         //this.register(cn);
565         cn.parentId = this.id;
566         cn.onRender(this.el, null);
567         return cn;
568     }
569    
570 });
571
572  /*
573  * - LGPL
574  *
575  * button
576  * 
577  */
578
579 /**
580  * @class Roo.bootstrap.Button
581  * @extends Roo.bootstrap.Component
582  * Bootstrap Button class
583  * @cfg {String} html The button content
584  * @cfg {String} weight (default | primary | secondary | success | info | warning | danger | link ) default
585  * @cfg {String} badge_weight (default | primary | secondary | success | info | warning | danger | link ) default (same as button)
586  * @cfg {Boolean} outline default false (except for weight=default which emulates old behaveiour with an outline)
587  * @cfg {String} size ( lg | sm | xs)
588  * @cfg {String} tag ( a | input | submit)
589  * @cfg {String} href empty or href
590  * @cfg {Boolean} disabled default false;
591  * @cfg {Boolean} isClose default false;
592  * @cfg {String} glyphicon depricated - use fa
593  * @cfg {String} fa fontawesome icon - eg. 'comment' - without the fa/fas etc..
594  * @cfg {String} badge text for badge
595  * @cfg {String} theme (default|glow)  
596  * @cfg {Boolean} inverse dark themed version
597  * @cfg {Boolean} toggle is it a slidy toggle button
598  * @cfg {Boolean} pressed (true|false) default null - if the button ahs active state
599  * @cfg {String} ontext text for on slidy toggle state
600  * @cfg {String} offtext text for off slidy toggle state
601  * @cfg {Boolean} preventDefault  default true (stop click event triggering the URL if it's a link.)
602  * @cfg {Boolean} removeClass remove the standard class..
603  * @cfg {String} target  target for a href. (_self|_blank|_parent|_top| other)
604  * 
605  * @constructor
606  * Create a new button
607  * @param {Object} config The config object
608  */
609
610
611 Roo.bootstrap.Button = function(config){
612     Roo.bootstrap.Button.superclass.constructor.call(this, config);
613     this.weightClass = ["btn-default btn-outline-secondary", 
614                        "btn-primary", 
615                        "btn-success", 
616                        "btn-info", 
617                        "btn-warning",
618                        "btn-danger",
619                        "btn-link"
620                       ],  
621     this.addEvents({
622         // raw events
623         /**
624          * @event click
625          * When a butotn is pressed
626          * @param {Roo.bootstrap.Button} btn
627          * @param {Roo.EventObject} e
628          */
629         "click" : true,
630          /**
631          * @event toggle
632          * After the button has been toggles
633          * @param {Roo.bootstrap.Button} btn
634          * @param {Roo.EventObject} e
635          * @param {boolean} pressed (also available as button.pressed)
636          */
637         "toggle" : true
638     });
639 };
640
641 Roo.extend(Roo.bootstrap.Button, Roo.bootstrap.Component,  {
642     html: false,
643     active: false,
644     weight: '',
645     badge_weight: '',
646     outline : false,
647     size: '',
648     tag: 'button',
649     href: '',
650     disabled: false,
651     isClose: false,
652     glyphicon: '',
653     fa: '',
654     badge: '',
655     theme: 'default',
656     inverse: false,
657     
658     toggle: false,
659     ontext: 'ON',
660     offtext: 'OFF',
661     defaulton: true,
662     preventDefault: true,
663     removeClass: false,
664     name: false,
665     target: false,
666      
667     pressed : null,
668      
669     
670     getAutoCreate : function(){
671         
672         var cfg = {
673             tag : 'button',
674             cls : 'roo-button',
675             html: ''
676         };
677         
678         if (['a', 'button', 'input', 'submit'].indexOf(this.tag) < 0) {
679             throw "Invalid value for tag: " + this.tag + ". must be a, button, input or submit.";
680             this.tag = 'button';
681         } else {
682             cfg.tag = this.tag;
683         }
684         cfg.html = '<span class="roo-button-text">' + (this.html || cfg.html) + '</span>';
685         
686         if (this.toggle == true) {
687             cfg={
688                 tag: 'div',
689                 cls: 'slider-frame roo-button',
690                 cn: [
691                     {
692                         tag: 'span',
693                         'data-on-text':'ON',
694                         'data-off-text':'OFF',
695                         cls: 'slider-button',
696                         html: this.offtext
697                     }
698                 ]
699             };
700             
701             if (['default', 'secondary' , 'primary', 'success', 'info', 'warning', 'danger', 'link'].indexOf(this.weight) > -1) {
702                 cfg.cls += ' '+this.weight;
703             }
704             
705             return cfg;
706         }
707         
708         if (this.isClose) {
709             cfg.cls += ' close';
710             
711             cfg["aria-hidden"] = true;
712             
713             cfg.html = "&times;";
714             
715             return cfg;
716         }
717         
718          
719         if (this.theme==='default') {
720             cfg.cls = 'btn roo-button';
721             
722             //if (this.parentType != 'Navbar') {
723             this.weight = this.weight.length ?  this.weight : 'default';
724             //}
725             if (['default', 'primary', 'secondary', 'success', 'info', 'warning', 'danger', 'link'].indexOf(this.weight) > -1) {
726                 
727                 var outline = this.outline || this.weight == 'default' ? 'outline-' : '';
728                 var weight = this.weight == 'default' ? 'secondary' : this.weight;
729                 cfg.cls += ' btn-' + outline + weight;
730                 if (this.weight == 'default') {
731                     // BC
732                     cfg.cls += ' btn-' + this.weight;
733                 }
734             }
735         } else if (this.theme==='glow') {
736             
737             cfg.tag = 'a';
738             cfg.cls = 'btn-glow roo-button';
739             
740             if (['default', 'primary', 'success', 'info', 'warning', 'danger', 'link'].indexOf(this.weight) > -1) {
741                 
742                 cfg.cls += ' ' + this.weight;
743             }
744         }
745    
746         
747         if (this.inverse) {
748             this.cls += ' inverse';
749         }
750         
751         
752         if (this.active || this.pressed === true) {
753             cfg.cls += ' active';
754         }
755         
756         if (this.disabled) {
757             cfg.disabled = 'disabled';
758         }
759         
760         if (this.items) {
761             Roo.log('changing to ul' );
762             cfg.tag = 'ul';
763             this.glyphicon = 'caret';
764             if (Roo.bootstrap.version == 4) {
765                 this.fa = 'caret-down';
766             }
767             
768         }
769         
770         cfg.cls += this.size.length ? (' btn-' + this.size) : '';
771          
772         //gsRoo.log(this.parentType);
773         if (this.parentType === 'Navbar' && !this.parent().bar) {
774             Roo.log('changing to li?');
775             
776             cfg.tag = 'li';
777             
778             cfg.cls = '';
779             cfg.cn =  [{
780                 tag : 'a',
781                 cls : 'roo-button',
782                 html : this.html,
783                 href : this.href || '#'
784             }];
785             if (this.menu) {
786                 cfg.cn[0].html = this.html  + ' <span class="caret"></span>';
787                 cfg.cls += ' dropdown';
788             }   
789             
790             delete cfg.html;
791             
792         }
793         
794        cfg.cls += this.parentType === 'Navbar' ?  ' navbar-btn' : '';
795         
796         if (this.glyphicon) {
797             cfg.html = ' ' + cfg.html;
798             
799             cfg.cn = [
800                 {
801                     tag: 'span',
802                     cls: 'glyphicon glyphicon-' + this.glyphicon
803                 }
804             ];
805         }
806         if (this.fa) {
807             cfg.html = ' ' + cfg.html;
808             
809             cfg.cn = [
810                 {
811                     tag: 'i',
812                     cls: 'fa fas fa-' + this.fa
813                 }
814             ];
815         }
816         
817         if (this.badge) {
818             cfg.html += ' ';
819             
820             cfg.tag = 'a';
821             
822 //            cfg.cls='btn roo-button';
823             
824             cfg.href=this.href;
825             
826             var value = cfg.html;
827             
828             if(this.glyphicon){
829                 value = {
830                     tag: 'span',
831                     cls: 'glyphicon glyphicon-' + this.glyphicon,
832                     html: this.html
833                 };
834             }
835             if(this.fa){
836                 value = {
837                     tag: 'i',
838                     cls: 'fa fas fa-' + this.fa,
839                     html: this.html
840                 };
841             }
842             
843             var bw = this.badge_weight.length ? this.badge_weight :
844                 (this.weight.length ? this.weight : 'secondary');
845             bw = bw == 'default' ? 'secondary' : bw;
846             
847             cfg.cn = [
848                 value,
849                 {
850                     tag: 'span',
851                     cls: 'badge badge-' + bw,
852                     html: this.badge
853                 }
854             ];
855             
856             cfg.html='';
857         }
858         
859         if (this.menu) {
860             cfg.cls += ' dropdown';
861             cfg.html = typeof(cfg.html) != 'undefined' ?
862                     cfg.html + ' <span class="caret"></span>' : '<span class="caret"></span>';
863         }
864         
865         if (cfg.tag !== 'a' && this.href !== '') {
866             throw "Tag must be a to set href.";
867         } else if (this.href.length > 0) {
868             cfg.href = this.href;
869         }
870         
871         if(this.removeClass){
872             cfg.cls = '';
873         }
874         
875         if(this.target){
876             cfg.target = this.target;
877         }
878         
879         return cfg;
880     },
881     initEvents: function() {
882        // Roo.log('init events?');
883 //        Roo.log(this.el.dom);
884         // add the menu...
885         
886         if (typeof (this.menu) != 'undefined') {
887             this.menu.parentType = this.xtype;
888             this.menu.triggerEl = this.el;
889             this.addxtype(Roo.apply({}, this.menu));
890         }
891
892
893        if (this.el.hasClass('roo-button')) {
894             this.el.on('click', this.onClick, this);
895        } else {
896             this.el.select('.roo-button').on('click', this.onClick, this);
897        }
898        
899        if(this.removeClass){
900            this.el.on('click', this.onClick, this);
901        }
902        
903        this.el.enableDisplayMode();
904         
905     },
906     onClick : function(e)
907     {
908         if (this.disabled) {
909             return;
910         }
911         
912         Roo.log('button on click ');
913         if(this.preventDefault){
914             e.preventDefault();
915         }
916         
917         if (this.pressed === true || this.pressed === false) {
918             this.toggleActive(e);
919         }
920         
921         
922         this.fireEvent('click', this, e);
923     },
924     
925     /**
926      * Enables this button
927      */
928     enable : function()
929     {
930         this.disabled = false;
931         this.el.removeClass('disabled');
932     },
933     
934     /**
935      * Disable this button
936      */
937     disable : function()
938     {
939         this.disabled = true;
940         this.el.addClass('disabled');
941     },
942      /**
943      * sets the active state on/off, 
944      * @param {Boolean} state (optional) Force a particular state
945      */
946     setActive : function(v) {
947         
948         this.el[v ? 'addClass' : 'removeClass']('active');
949         this.pressed = v;
950     },
951      /**
952      * toggles the current active state 
953      */
954     toggleActive : function(e)
955     {
956         this.setActive(!this.pressed);
957         this.fireEvent('toggle', this, e, !this.pressed);
958     },
959      /**
960      * get the current active state
961      * @return {boolean} true if it's active
962      */
963     isActive : function()
964     {
965         return this.el.hasClass('active');
966     },
967     /**
968      * set the text of the first selected button
969      */
970     setText : function(str)
971     {
972         this.el.select('.roo-button-text',true).first().dom.innerHTML = str;
973     },
974     /**
975      * get the text of the first selected button
976      */
977     getText : function()
978     {
979         return this.el.select('.roo-button-text',true).first().dom.innerHTML;
980     },
981     
982     setWeight : function(str)
983     {
984         this.el.removeClass(this.weightClass);
985         this.weight = str;
986         var outline = this.outline ? 'outline-' : '';
987         if (str == 'default') {
988             this.el.addClass('btn-default btn-outline-secondary');        
989             return;
990         }
991         this.el.addClass('btn-' + outline + str);        
992     }
993     
994     
995 });
996
997  /*
998  * - LGPL
999  *
1000  * column
1001  * 
1002  */
1003
1004 /**
1005  * @class Roo.bootstrap.Column
1006  * @extends Roo.bootstrap.Component
1007  * Bootstrap Column class
1008  * @cfg {Number} xs colspan out of 12 for mobile-sized screens or 0 for hidden
1009  * @cfg {Number} sm colspan out of 12 for tablet-sized screens or 0 for hidden
1010  * @cfg {Number} md colspan out of 12 for computer-sized screens or 0 for hidden
1011  * @cfg {Number} lg colspan out of 12 for large computer-sized screens or 0 for hidden
1012  * @cfg {Number} xsoff colspan offset out of 12 for mobile-sized screens or 0 for hidden
1013  * @cfg {Number} smoff colspan offset out of 12 for tablet-sized screens or 0 for hidden
1014  * @cfg {Number} mdoff colspan offset out of 12 for computer-sized screens or 0 for hidden
1015  * @cfg {Number} lgoff colspan offset out of 12 for large computer-sized screens or 0 for hidden
1016  *
1017  * 
1018  * @cfg {Boolean} hidden (true|false) hide the element
1019  * @cfg {String} alert (success|info|warning|danger) type alert (changes background / border...)
1020  * @cfg {String} fa (ban|check|...) font awesome icon
1021  * @cfg {Number} fasize (1|2|....) font awsome size
1022
1023  * @cfg {String} icon (info-sign|check|...) glyphicon name
1024
1025  * @cfg {String} html content of column.
1026  * 
1027  * @constructor
1028  * Create a new Column
1029  * @param {Object} config The config object
1030  */
1031
1032 Roo.bootstrap.Column = function(config){
1033     Roo.bootstrap.Column.superclass.constructor.call(this, config);
1034 };
1035
1036 Roo.extend(Roo.bootstrap.Column, Roo.bootstrap.Component,  {
1037     
1038     xs: false,
1039     sm: false,
1040     md: false,
1041     lg: false,
1042     xsoff: false,
1043     smoff: false,
1044     mdoff: false,
1045     lgoff: false,
1046     html: '',
1047     offset: 0,
1048     alert: false,
1049     fa: false,
1050     icon : false,
1051     hidden : false,
1052     fasize : 1,
1053     
1054     getAutoCreate : function(){
1055         var cfg = Roo.apply({}, Roo.bootstrap.Column.superclass.getAutoCreate.call(this));
1056         
1057         cfg = {
1058             tag: 'div',
1059             cls: 'column'
1060         };
1061         
1062         var settings=this;
1063         ['xs','sm','md','lg'].map(function(size){
1064             //Roo.log( size + ':' + settings[size]);
1065             
1066             if (settings[size+'off'] !== false) {
1067                 cfg.cls += ' col-' + size + '-offset-' + settings[size+'off'] ;
1068             }
1069             
1070             if (settings[size] === false) {
1071                 return;
1072             }
1073             
1074             if (!settings[size]) { // 0 = hidden
1075                 cfg.cls += ' hidden-' + size + ' hidden' + size + '-down';;
1076                 return;
1077             }
1078             cfg.cls += ' col-' + size + '-' + settings[size] + (
1079                 size == 'xs' ? (' col-' + settings[size] ) : '' // bs4 col-{num} replaces col-xs
1080             );
1081             
1082         });
1083         
1084         if (this.hidden) {
1085             cfg.cls += ' hidden';
1086         }
1087         
1088         if (this.alert && ["success","info","warning", "danger"].indexOf(this.alert) > -1) {
1089             cfg.cls +=' alert alert-' + this.alert;
1090         }
1091         
1092         
1093         if (this.html.length) {
1094             cfg.html = this.html;
1095         }
1096         if (this.fa) {
1097             var fasize = '';
1098             if (this.fasize > 1) {
1099                 fasize = ' fa-' + this.fasize + 'x';
1100             }
1101             cfg.html = '<i class="fa fa-'+this.fa + fasize + '"></i>' + (cfg.html || '');
1102             
1103             
1104         }
1105         if (this.icon) {
1106             cfg.html = '<i class="glyphicon glyphicon-'+this.icon + '"></i>' +  (cfg.html || '');
1107         }
1108         
1109         return cfg;
1110     }
1111    
1112 });
1113
1114  
1115
1116  /*
1117  * - LGPL
1118  *
1119  * page container.
1120  * 
1121  */
1122
1123
1124 /**
1125  * @class Roo.bootstrap.Container
1126  * @extends Roo.bootstrap.Component
1127  * Bootstrap Container class
1128  * @cfg {Boolean} jumbotron is it a jumbotron element
1129  * @cfg {String} html content of element
1130  * @cfg {String} well (lg|sm|md) a well, large, small or medium.
1131  * @cfg {String} panel (default|primary|success|info|warning|danger) render as panel  - type - primary/success.....
1132  * @cfg {String} header content of header (for panel)
1133  * @cfg {String} footer content of footer (for panel)
1134  * @cfg {String} sticky (footer|wrap|push) block to use as footer or body- needs css-bootstrap/sticky-footer.css
1135  * @cfg {String} tag (header|aside|section) type of HTML tag.
1136  * @cfg {String} alert (success|info|warning|danger) type alert (changes background / border...)
1137  * @cfg {String} fa font awesome icon
1138  * @cfg {String} icon (info-sign|check|...) glyphicon name
1139  * @cfg {Boolean} hidden (true|false) hide the element
1140  * @cfg {Boolean} expandable (true|false) default false
1141  * @cfg {Boolean} expanded (true|false) default true
1142  * @cfg {String} rheader contet on the right of header
1143  * @cfg {Boolean} clickable (true|false) default false
1144
1145  *     
1146  * @constructor
1147  * Create a new Container
1148  * @param {Object} config The config object
1149  */
1150
1151 Roo.bootstrap.Container = function(config){
1152     Roo.bootstrap.Container.superclass.constructor.call(this, config);
1153     
1154     this.addEvents({
1155         // raw events
1156          /**
1157          * @event expand
1158          * After the panel has been expand
1159          * 
1160          * @param {Roo.bootstrap.Container} this
1161          */
1162         "expand" : true,
1163         /**
1164          * @event collapse
1165          * After the panel has been collapsed
1166          * 
1167          * @param {Roo.bootstrap.Container} this
1168          */
1169         "collapse" : true,
1170         /**
1171          * @event click
1172          * When a element is chick
1173          * @param {Roo.bootstrap.Container} this
1174          * @param {Roo.EventObject} e
1175          */
1176         "click" : true
1177     });
1178 };
1179
1180 Roo.extend(Roo.bootstrap.Container, Roo.bootstrap.Component,  {
1181     
1182     jumbotron : false,
1183     well: '',
1184     panel : '',
1185     header: '',
1186     footer : '',
1187     sticky: '',
1188     tag : false,
1189     alert : false,
1190     fa: false,
1191     icon : false,
1192     expandable : false,
1193     rheader : '',
1194     expanded : true,
1195     clickable: false,
1196   
1197      
1198     getChildContainer : function() {
1199         
1200         if(!this.el){
1201             return false;
1202         }
1203         
1204         if (this.panel.length) {
1205             return this.el.select('.panel-body',true).first();
1206         }
1207         
1208         return this.el;
1209     },
1210     
1211     
1212     getAutoCreate : function(){
1213         
1214         var cfg = {
1215             tag : this.tag || 'div',
1216             html : '',
1217             cls : ''
1218         };
1219         if (this.jumbotron) {
1220             cfg.cls = 'jumbotron';
1221         }
1222         
1223         
1224         
1225         // - this is applied by the parent..
1226         //if (this.cls) {
1227         //    cfg.cls = this.cls + '';
1228         //}
1229         
1230         if (this.sticky.length) {
1231             
1232             var bd = Roo.get(document.body);
1233             if (!bd.hasClass('bootstrap-sticky')) {
1234                 bd.addClass('bootstrap-sticky');
1235                 Roo.select('html',true).setStyle('height', '100%');
1236             }
1237              
1238             cfg.cls += 'bootstrap-sticky-' + this.sticky;
1239         }
1240         
1241         
1242         if (this.well.length) {
1243             switch (this.well) {
1244                 case 'lg':
1245                 case 'sm':
1246                     cfg.cls +=' well well-' +this.well;
1247                     break;
1248                 default:
1249                     cfg.cls +=' well';
1250                     break;
1251             }
1252         }
1253         
1254         if (this.hidden) {
1255             cfg.cls += ' hidden';
1256         }
1257         
1258         
1259         if (this.alert && ["success","info","warning", "danger"].indexOf(this.alert) > -1) {
1260             cfg.cls +=' alert alert-' + this.alert;
1261         }
1262         
1263         var body = cfg;
1264         
1265         if (this.panel.length) {
1266             cfg.cls += ' panel panel-' + this.panel;
1267             cfg.cn = [];
1268             if (this.header.length) {
1269                 
1270                 var h = [];
1271                 
1272                 if(this.expandable){
1273                     
1274                     cfg.cls = cfg.cls + ' expandable';
1275                     
1276                     h.push({
1277                         tag: 'i',
1278                         cls: (this.expanded ? 'fa fa-minus' : 'fa fa-plus') 
1279                     });
1280                     
1281                 }
1282                 
1283                 h.push(
1284                     {
1285                         tag: 'span',
1286                         cls : 'panel-title',
1287                         html : (this.expandable ? '&nbsp;' : '') + this.header
1288                     },
1289                     {
1290                         tag: 'span',
1291                         cls: 'panel-header-right',
1292                         html: this.rheader
1293                     }
1294                 );
1295                 
1296                 cfg.cn.push({
1297                     cls : 'panel-heading',
1298                     style : this.expandable ? 'cursor: pointer' : '',
1299                     cn : h
1300                 });
1301                 
1302             }
1303             
1304             body = false;
1305             cfg.cn.push({
1306                 cls : 'panel-body' + (this.expanded ? '' : ' hide'),
1307                 html : this.html
1308             });
1309             
1310             
1311             if (this.footer.length) {
1312                 cfg.cn.push({
1313                     cls : 'panel-footer',
1314                     html : this.footer
1315                     
1316                 });
1317             }
1318             
1319         }
1320         
1321         if (body) {
1322             body.html = this.html || cfg.html;
1323             // prefix with the icons..
1324             if (this.fa) {
1325                 body.html = '<i class="fa fa-'+this.fa + '"></i>' + body.html ;
1326             }
1327             if (this.icon) {
1328                 body.html = '<i class="glyphicon glyphicon-'+this.icon + '"></i>' + body.html ;
1329             }
1330             
1331             
1332         }
1333         if ((!this.cls || !this.cls.length) && (!cfg.cls || !cfg.cls.length)) {
1334             cfg.cls =  'container';
1335         }
1336         
1337         return cfg;
1338     },
1339     
1340     initEvents: function() 
1341     {
1342         if(this.expandable){
1343             var headerEl = this.headerEl();
1344         
1345             if(headerEl){
1346                 headerEl.on('click', this.onToggleClick, this);
1347             }
1348         }
1349         
1350         if(this.clickable){
1351             this.el.on('click', this.onClick, this);
1352         }
1353         
1354     },
1355     
1356     onToggleClick : function()
1357     {
1358         var headerEl = this.headerEl();
1359         
1360         if(!headerEl){
1361             return;
1362         }
1363         
1364         if(this.expanded){
1365             this.collapse();
1366             return;
1367         }
1368         
1369         this.expand();
1370     },
1371     
1372     expand : function()
1373     {
1374         if(this.fireEvent('expand', this)) {
1375             
1376             this.expanded = true;
1377             
1378             //this.el.select('.panel-body',true).first().setVisibilityMode(Roo.Element.DISPLAY).show();
1379             
1380             this.el.select('.panel-body',true).first().removeClass('hide');
1381             
1382             var toggleEl = this.toggleEl();
1383
1384             if(!toggleEl){
1385                 return;
1386             }
1387
1388             toggleEl.removeClass(['fa-minus', 'fa-plus']).addClass(['fa-minus']);
1389         }
1390         
1391     },
1392     
1393     collapse : function()
1394     {
1395         if(this.fireEvent('collapse', this)) {
1396             
1397             this.expanded = false;
1398             
1399             //this.el.select('.panel-body',true).first().setVisibilityMode(Roo.Element.DISPLAY).hide();
1400             this.el.select('.panel-body',true).first().addClass('hide');
1401         
1402             var toggleEl = this.toggleEl();
1403
1404             if(!toggleEl){
1405                 return;
1406             }
1407
1408             toggleEl.removeClass(['fa-minus', 'fa-plus']).addClass(['fa-plus']);
1409         }
1410     },
1411     
1412     toggleEl : function()
1413     {
1414         if(!this.el || !this.panel.length || !this.header.length || !this.expandable){
1415             return;
1416         }
1417         
1418         return this.el.select('.panel-heading .fa',true).first();
1419     },
1420     
1421     headerEl : function()
1422     {
1423         if(!this.el || !this.panel.length || !this.header.length){
1424             return;
1425         }
1426         
1427         return this.el.select('.panel-heading',true).first()
1428     },
1429     
1430     bodyEl : function()
1431     {
1432         if(!this.el || !this.panel.length){
1433             return;
1434         }
1435         
1436         return this.el.select('.panel-body',true).first()
1437     },
1438     
1439     titleEl : function()
1440     {
1441         if(!this.el || !this.panel.length || !this.header.length){
1442             return;
1443         }
1444         
1445         return this.el.select('.panel-title',true).first();
1446     },
1447     
1448     setTitle : function(v)
1449     {
1450         var titleEl = this.titleEl();
1451         
1452         if(!titleEl){
1453             return;
1454         }
1455         
1456         titleEl.dom.innerHTML = v;
1457     },
1458     
1459     getTitle : function()
1460     {
1461         
1462         var titleEl = this.titleEl();
1463         
1464         if(!titleEl){
1465             return '';
1466         }
1467         
1468         return titleEl.dom.innerHTML;
1469     },
1470     
1471     setRightTitle : function(v)
1472     {
1473         var t = this.el.select('.panel-header-right',true).first();
1474         
1475         if(!t){
1476             return;
1477         }
1478         
1479         t.dom.innerHTML = v;
1480     },
1481     
1482     onClick : function(e)
1483     {
1484         e.preventDefault();
1485         
1486         this.fireEvent('click', this, e);
1487     }
1488 });
1489
1490  /*
1491  * - LGPL
1492  *
1493  * image
1494  * 
1495  */
1496
1497
1498 /**
1499  * @class Roo.bootstrap.Img
1500  * @extends Roo.bootstrap.Component
1501  * Bootstrap Img class
1502  * @cfg {Boolean} imgResponsive false | true
1503  * @cfg {String} border rounded | circle | thumbnail
1504  * @cfg {String} src image source
1505  * @cfg {String} alt image alternative text
1506  * @cfg {String} href a tag href
1507  * @cfg {String} target (_self|_blank|_parent|_top)target for a href.
1508  * @cfg {String} xsUrl xs image source
1509  * @cfg {String} smUrl sm image source
1510  * @cfg {String} mdUrl md image source
1511  * @cfg {String} lgUrl lg image source
1512  * 
1513  * @constructor
1514  * Create a new Input
1515  * @param {Object} config The config object
1516  */
1517
1518 Roo.bootstrap.Img = function(config){
1519     Roo.bootstrap.Img.superclass.constructor.call(this, config);
1520     
1521     this.addEvents({
1522         // img events
1523         /**
1524          * @event click
1525          * The img click event for the img.
1526          * @param {Roo.EventObject} e
1527          */
1528         "click" : true
1529     });
1530 };
1531
1532 Roo.extend(Roo.bootstrap.Img, Roo.bootstrap.Component,  {
1533     
1534     imgResponsive: true,
1535     border: '',
1536     src: 'about:blank',
1537     href: false,
1538     target: false,
1539     xsUrl: '',
1540     smUrl: '',
1541     mdUrl: '',
1542     lgUrl: '',
1543
1544     getAutoCreate : function()
1545     {   
1546         if(this.src || (!this.xsUrl && !this.smUrl && !this.mdUrl && !this.lgUrl)){
1547             return this.createSingleImg();
1548         }
1549         
1550         var cfg = {
1551             tag: 'div',
1552             cls: 'roo-image-responsive-group',
1553             cn: []
1554         };
1555         var _this = this;
1556         
1557         Roo.each(['xs', 'sm', 'md', 'lg'], function(size){
1558             
1559             if(!_this[size + 'Url']){
1560                 return;
1561             }
1562             
1563             var img = {
1564                 tag: 'img',
1565                 cls: (_this.imgResponsive) ? 'img-responsive' : '',
1566                 html: _this.html || cfg.html,
1567                 src: _this[size + 'Url']
1568             };
1569             
1570             img.cls += ' roo-image-responsive-' + size;
1571             
1572             var s = ['xs', 'sm', 'md', 'lg'];
1573             
1574             s.splice(s.indexOf(size), 1);
1575             
1576             Roo.each(s, function(ss){
1577                 img.cls += ' hidden-' + ss;
1578             });
1579             
1580             if (['rounded','circle','thumbnail'].indexOf(_this.border)>-1) {
1581                 cfg.cls += ' img-' + _this.border;
1582             }
1583             
1584             if(_this.alt){
1585                 cfg.alt = _this.alt;
1586             }
1587             
1588             if(_this.href){
1589                 var a = {
1590                     tag: 'a',
1591                     href: _this.href,
1592                     cn: [
1593                         img
1594                     ]
1595                 };
1596
1597                 if(this.target){
1598                     a.target = _this.target;
1599                 }
1600             }
1601             
1602             cfg.cn.push((_this.href) ? a : img);
1603             
1604         });
1605         
1606         return cfg;
1607     },
1608     
1609     createSingleImg : function()
1610     {
1611         var cfg = {
1612             tag: 'img',
1613             cls: (this.imgResponsive) ? 'img-responsive' : '',
1614             html : null,
1615             src : 'about:blank'  // just incase src get's set to undefined?!?
1616         };
1617         
1618         cfg.html = this.html || cfg.html;
1619         
1620         cfg.src = this.src || cfg.src;
1621         
1622         if (['rounded','circle','thumbnail'].indexOf(this.border)>-1) {
1623             cfg.cls += ' img-' + this.border;
1624         }
1625         
1626         if(this.alt){
1627             cfg.alt = this.alt;
1628         }
1629         
1630         if(this.href){
1631             var a = {
1632                 tag: 'a',
1633                 href: this.href,
1634                 cn: [
1635                     cfg
1636                 ]
1637             };
1638             
1639             if(this.target){
1640                 a.target = this.target;
1641             }
1642             
1643         }
1644         
1645         return (this.href) ? a : cfg;
1646     },
1647     
1648     initEvents: function() 
1649     {
1650         if(!this.href){
1651             this.el.on('click', this.onClick, this);
1652         }
1653         
1654     },
1655     
1656     onClick : function(e)
1657     {
1658         Roo.log('img onclick');
1659         this.fireEvent('click', this, e);
1660     },
1661     /**
1662      * Sets the url of the image - used to update it
1663      * @param {String} url the url of the image
1664      */
1665     
1666     setSrc : function(url)
1667     {
1668         this.src =  url;
1669         
1670         if(this.src || (!this.xsUrl && !this.smUrl && !this.mdUrl && !this.lgUrl)){
1671             this.el.dom.src =  url;
1672             return;
1673         }
1674         
1675         this.el.select('img', true).first().dom.src =  url;
1676     }
1677     
1678     
1679    
1680 });
1681
1682  /*
1683  * - LGPL
1684  *
1685  * image
1686  * 
1687  */
1688
1689
1690 /**
1691  * @class Roo.bootstrap.Link
1692  * @extends Roo.bootstrap.Component
1693  * Bootstrap Link Class
1694  * @cfg {String} alt image alternative text
1695  * @cfg {String} href a tag href
1696  * @cfg {String} target (_self|_blank|_parent|_top) target for a href.
1697  * @cfg {String} html the content of the link.
1698  * @cfg {String} anchor name for the anchor link
1699  * @cfg {String} fa - favicon
1700
1701  * @cfg {Boolean} preventDefault (true | false) default false
1702
1703  * 
1704  * @constructor
1705  * Create a new Input
1706  * @param {Object} config The config object
1707  */
1708
1709 Roo.bootstrap.Link = function(config){
1710     Roo.bootstrap.Link.superclass.constructor.call(this, config);
1711     
1712     this.addEvents({
1713         // img events
1714         /**
1715          * @event click
1716          * The img click event for the img.
1717          * @param {Roo.EventObject} e
1718          */
1719         "click" : true
1720     });
1721 };
1722
1723 Roo.extend(Roo.bootstrap.Link, Roo.bootstrap.Component,  {
1724     
1725     href: false,
1726     target: false,
1727     preventDefault: false,
1728     anchor : false,
1729     alt : false,
1730     fa: false,
1731
1732
1733     getAutoCreate : function()
1734     {
1735         var html = this.html || '';
1736         
1737         if (this.fa !== false) {
1738             html = '<i class="fa fa-' + this.fa + '"></i>';
1739         }
1740         var cfg = {
1741             tag: 'a'
1742         };
1743         // anchor's do not require html/href...
1744         if (this.anchor === false) {
1745             cfg.html = html;
1746             cfg.href = this.href || '#';
1747         } else {
1748             cfg.name = this.anchor;
1749             if (this.html !== false || this.fa !== false) {
1750                 cfg.html = html;
1751             }
1752             if (this.href !== false) {
1753                 cfg.href = this.href;
1754             }
1755         }
1756         
1757         if(this.alt !== false){
1758             cfg.alt = this.alt;
1759         }
1760         
1761         
1762         if(this.target !== false) {
1763             cfg.target = this.target;
1764         }
1765         
1766         return cfg;
1767     },
1768     
1769     initEvents: function() {
1770         
1771         if(!this.href || this.preventDefault){
1772             this.el.on('click', this.onClick, this);
1773         }
1774     },
1775     
1776     onClick : function(e)
1777     {
1778         if(this.preventDefault){
1779             e.preventDefault();
1780         }
1781         //Roo.log('img onclick');
1782         this.fireEvent('click', this, e);
1783     }
1784    
1785 });
1786
1787  /*
1788  * - LGPL
1789  *
1790  * header
1791  * 
1792  */
1793
1794 /**
1795  * @class Roo.bootstrap.Header
1796  * @extends Roo.bootstrap.Component
1797  * Bootstrap Header class
1798  * @cfg {String} html content of header
1799  * @cfg {Number} level (1|2|3|4|5|6) default 1
1800  * 
1801  * @constructor
1802  * Create a new Header
1803  * @param {Object} config The config object
1804  */
1805
1806
1807 Roo.bootstrap.Header  = function(config){
1808     Roo.bootstrap.Header.superclass.constructor.call(this, config);
1809 };
1810
1811 Roo.extend(Roo.bootstrap.Header, Roo.bootstrap.Component,  {
1812     
1813     //href : false,
1814     html : false,
1815     level : 1,
1816     
1817     
1818     
1819     getAutoCreate : function(){
1820         
1821         
1822         
1823         var cfg = {
1824             tag: 'h' + (1 *this.level),
1825             html: this.html || ''
1826         } ;
1827         
1828         return cfg;
1829     }
1830    
1831 });
1832
1833  
1834
1835  /*
1836  * Based on:
1837  * Ext JS Library 1.1.1
1838  * Copyright(c) 2006-2007, Ext JS, LLC.
1839  *
1840  * Originally Released Under LGPL - original licence link has changed is not relivant.
1841  *
1842  * Fork - LGPL
1843  * <script type="text/javascript">
1844  */
1845  
1846 /**
1847  * @class Roo.bootstrap.MenuMgr
1848  * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
1849  * @singleton
1850  */
1851 Roo.bootstrap.MenuMgr = function(){
1852    var menus, active, groups = {}, attached = false, lastShow = new Date();
1853
1854    // private - called when first menu is created
1855    function init(){
1856        menus = {};
1857        active = new Roo.util.MixedCollection();
1858        Roo.get(document).addKeyListener(27, function(){
1859            if(active.length > 0){
1860                hideAll();
1861            }
1862        });
1863    }
1864
1865    // private
1866    function hideAll(){
1867        if(active && active.length > 0){
1868            var c = active.clone();
1869            c.each(function(m){
1870                m.hide();
1871            });
1872        }
1873    }
1874
1875    // private
1876    function onHide(m){
1877        active.remove(m);
1878        if(active.length < 1){
1879            Roo.get(document).un("mouseup", onMouseDown);
1880             
1881            attached = false;
1882        }
1883    }
1884
1885    // private
1886    function onShow(m){
1887        var last = active.last();
1888        lastShow = new Date();
1889        active.add(m);
1890        if(!attached){
1891           Roo.get(document).on("mouseup", onMouseDown);
1892            
1893            attached = true;
1894        }
1895        if(m.parentMenu){
1896           //m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
1897           m.parentMenu.activeChild = m;
1898        }else if(last && last.isVisible()){
1899           //m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
1900        }
1901    }
1902
1903    // private
1904    function onBeforeHide(m){
1905        if(m.activeChild){
1906            m.activeChild.hide();
1907        }
1908        if(m.autoHideTimer){
1909            clearTimeout(m.autoHideTimer);
1910            delete m.autoHideTimer;
1911        }
1912    }
1913
1914    // private
1915    function onBeforeShow(m){
1916        var pm = m.parentMenu;
1917        if(!pm && !m.allowOtherMenus){
1918            hideAll();
1919        }else if(pm && pm.activeChild && active != m){
1920            pm.activeChild.hide();
1921        }
1922    }
1923
1924    // private this should really trigger on mouseup..
1925    function onMouseDown(e){
1926         Roo.log("on Mouse Up");
1927         
1928         if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".dropdown-menu") && !e.getTarget('.user-menu')){
1929             Roo.log("MenuManager hideAll");
1930             hideAll();
1931             e.stopEvent();
1932         }
1933         
1934         
1935    }
1936
1937    // private
1938    function onBeforeCheck(mi, state){
1939        if(state){
1940            var g = groups[mi.group];
1941            for(var i = 0, l = g.length; i < l; i++){
1942                if(g[i] != mi){
1943                    g[i].setChecked(false);
1944                }
1945            }
1946        }
1947    }
1948
1949    return {
1950
1951        /**
1952         * Hides all menus that are currently visible
1953         */
1954        hideAll : function(){
1955             hideAll();  
1956        },
1957
1958        // private
1959        register : function(menu){
1960            if(!menus){
1961                init();
1962            }
1963            menus[menu.id] = menu;
1964            menu.on("beforehide", onBeforeHide);
1965            menu.on("hide", onHide);
1966            menu.on("beforeshow", onBeforeShow);
1967            menu.on("show", onShow);
1968            var g = menu.group;
1969            if(g && menu.events["checkchange"]){
1970                if(!groups[g]){
1971                    groups[g] = [];
1972                }
1973                groups[g].push(menu);
1974                menu.on("checkchange", onCheck);
1975            }
1976        },
1977
1978         /**
1979          * Returns a {@link Roo.menu.Menu} object
1980          * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
1981          * be used to generate and return a new Menu instance.
1982          */
1983        get : function(menu){
1984            if(typeof menu == "string"){ // menu id
1985                return menus[menu];
1986            }else if(menu.events){  // menu instance
1987                return menu;
1988            }
1989            /*else if(typeof menu.length == 'number'){ // array of menu items?
1990                return new Roo.bootstrap.Menu({items:menu});
1991            }else{ // otherwise, must be a config
1992                return new Roo.bootstrap.Menu(menu);
1993            }
1994            */
1995            return false;
1996        },
1997
1998        // private
1999        unregister : function(menu){
2000            delete menus[menu.id];
2001            menu.un("beforehide", onBeforeHide);
2002            menu.un("hide", onHide);
2003            menu.un("beforeshow", onBeforeShow);
2004            menu.un("show", onShow);
2005            var g = menu.group;
2006            if(g && menu.events["checkchange"]){
2007                groups[g].remove(menu);
2008                menu.un("checkchange", onCheck);
2009            }
2010        },
2011
2012        // private
2013        registerCheckable : function(menuItem){
2014            var g = menuItem.group;
2015            if(g){
2016                if(!groups[g]){
2017                    groups[g] = [];
2018                }
2019                groups[g].push(menuItem);
2020                menuItem.on("beforecheckchange", onBeforeCheck);
2021            }
2022        },
2023
2024        // private
2025        unregisterCheckable : function(menuItem){
2026            var g = menuItem.group;
2027            if(g){
2028                groups[g].remove(menuItem);
2029                menuItem.un("beforecheckchange", onBeforeCheck);
2030            }
2031        }
2032    };
2033 }();/*
2034  * - LGPL
2035  *
2036  * menu
2037  * 
2038  */
2039
2040 /**
2041  * @class Roo.bootstrap.Menu
2042  * @extends Roo.bootstrap.Component
2043  * Bootstrap Menu class - container for MenuItems
2044  * @cfg {String} type (dropdown|treeview|submenu) type of menu
2045  * @cfg {bool} hidden  if the menu should be hidden when rendered.
2046  * @cfg {bool} stopEvent (true|false)  Stop event after trigger press (default true)
2047  * @cfg {bool} isLink (true|false)  the menu has link disable auto expand and collaspe (default false)
2048  * 
2049  * @constructor
2050  * Create a new Menu
2051  * @param {Object} config The config object
2052  */
2053
2054
2055 Roo.bootstrap.Menu = function(config){
2056     Roo.bootstrap.Menu.superclass.constructor.call(this, config);
2057     if (this.registerMenu && this.type != 'treeview')  {
2058         Roo.bootstrap.MenuMgr.register(this);
2059     }
2060     
2061     
2062     this.addEvents({
2063         /**
2064          * @event beforeshow
2065          * Fires before this menu is displayed (return false to block)
2066          * @param {Roo.menu.Menu} this
2067          */
2068         beforeshow : true,
2069         /**
2070          * @event beforehide
2071          * Fires before this menu is hidden (return false to block)
2072          * @param {Roo.menu.Menu} this
2073          */
2074         beforehide : true,
2075         /**
2076          * @event show
2077          * Fires after this menu is displayed
2078          * @param {Roo.menu.Menu} this
2079          */
2080         show : true,
2081         /**
2082          * @event hide
2083          * Fires after this menu is hidden
2084          * @param {Roo.menu.Menu} this
2085          */
2086         hide : true,
2087         /**
2088          * @event click
2089          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
2090          * @param {Roo.menu.Menu} this
2091          * @param {Roo.menu.Item} menuItem The menu item that was clicked
2092          * @param {Roo.EventObject} e
2093          */
2094         click : true,
2095         /**
2096          * @event mouseover
2097          * Fires when the mouse is hovering over this menu
2098          * @param {Roo.menu.Menu} this
2099          * @param {Roo.EventObject} e
2100          * @param {Roo.menu.Item} menuItem The menu item that was clicked
2101          */
2102         mouseover : true,
2103         /**
2104          * @event mouseout
2105          * Fires when the mouse exits this menu
2106          * @param {Roo.menu.Menu} this
2107          * @param {Roo.EventObject} e
2108          * @param {Roo.menu.Item} menuItem The menu item that was clicked
2109          */
2110         mouseout : true,
2111         /**
2112          * @event itemclick
2113          * Fires when a menu item contained in this menu is clicked
2114          * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
2115          * @param {Roo.EventObject} e
2116          */
2117         itemclick: true
2118     });
2119     this.menuitems = new Roo.util.MixedCollection(false, function(o) { return o.el.id; });
2120 };
2121
2122 Roo.extend(Roo.bootstrap.Menu, Roo.bootstrap.Component,  {
2123     
2124    /// html : false,
2125     //align : '',
2126     triggerEl : false,  // is this set by component builder? -- it should really be fetched from parent()???
2127     type: false,
2128     /**
2129      * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
2130      */
2131     registerMenu : true,
2132     
2133     menuItems :false, // stores the menu items..
2134     
2135     hidden:true,
2136         
2137     parentMenu : false,
2138     
2139     stopEvent : true,
2140     
2141     isLink : false,
2142     
2143     getChildContainer : function() {
2144         return this.el;  
2145     },
2146     
2147     getAutoCreate : function(){
2148          
2149         //if (['right'].indexOf(this.align)!==-1) {
2150         //    cfg.cn[1].cls += ' pull-right'
2151         //}
2152         
2153         
2154         var cfg = {
2155             tag : 'ul',
2156             cls : 'dropdown-menu' ,
2157             style : 'z-index:1000'
2158             
2159         };
2160         
2161         if (this.type === 'submenu') {
2162             cfg.cls = 'submenu active';
2163         }
2164         if (this.type === 'treeview') {
2165             cfg.cls = 'treeview-menu';
2166         }
2167         
2168         return cfg;
2169     },
2170     initEvents : function() {
2171         
2172        // Roo.log("ADD event");
2173        // Roo.log(this.triggerEl.dom);
2174         
2175         this.triggerEl.on('click', this.onTriggerClick, this);
2176         
2177         this.triggerEl.on(Roo.isTouch ? 'touchstart' : 'mouseup', this.onTriggerPress, this);
2178         
2179         
2180         if (this.triggerEl.hasClass('nav-item')) {
2181             // dropdown toggle on the 'a' in BS4?
2182             this.triggerEl.select('.nav-link',true).first().addClass('dropdown-toggle');
2183         } else {
2184             this.triggerEl.addClass('dropdown-toggle');
2185         }
2186         if (Roo.isTouch) {
2187             this.el.on('touchstart'  , this.onTouch, this);
2188         }
2189         this.el.on('click' , this.onClick, this);
2190
2191         this.el.on("mouseover", this.onMouseOver, this);
2192         this.el.on("mouseout", this.onMouseOut, this);
2193         
2194     },
2195     
2196     findTargetItem : function(e)
2197     {
2198         var t = e.getTarget(".dropdown-menu-item", this.el,  true);
2199         if(!t){
2200             return false;
2201         }
2202         //Roo.log(t);         Roo.log(t.id);
2203         if(t && t.id){
2204             //Roo.log(this.menuitems);
2205             return this.menuitems.get(t.id);
2206             
2207             //return this.items.get(t.menuItemId);
2208         }
2209         
2210         return false;
2211     },
2212     
2213     onTouch : function(e) 
2214     {
2215         Roo.log("menu.onTouch");
2216         //e.stopEvent(); this make the user popdown broken
2217         this.onClick(e);
2218     },
2219     
2220     onClick : function(e)
2221     {
2222         Roo.log("menu.onClick");
2223         
2224         var t = this.findTargetItem(e);
2225         if(!t || t.isContainer){
2226             return;
2227         }
2228         Roo.log(e);
2229         /*
2230         if (Roo.isTouch && e.type == 'touchstart' && t.menu  && !t.disabled) {
2231             if(t == this.activeItem && t.shouldDeactivate(e)){
2232                 this.activeItem.deactivate();
2233                 delete this.activeItem;
2234                 return;
2235             }
2236             if(t.canActivate){
2237                 this.setActiveItem(t, true);
2238             }
2239             return;
2240             
2241             
2242         }
2243         */
2244        
2245         Roo.log('pass click event');
2246         
2247         t.onClick(e);
2248         
2249         this.fireEvent("click", this, t, e);
2250         
2251         var _this = this;
2252         
2253         if(!t.href.length || t.href == '#'){
2254             (function() { _this.hide(); }).defer(100);
2255         }
2256         
2257     },
2258     
2259     onMouseOver : function(e){
2260         var t  = this.findTargetItem(e);
2261         //Roo.log(t);
2262         //if(t){
2263         //    if(t.canActivate && !t.disabled){
2264         //        this.setActiveItem(t, true);
2265         //    }
2266         //}
2267         
2268         this.fireEvent("mouseover", this, e, t);
2269     },
2270     isVisible : function(){
2271         return !this.hidden;
2272     },
2273     onMouseOut : function(e){
2274         var t  = this.findTargetItem(e);
2275         
2276         //if(t ){
2277         //    if(t == this.activeItem && t.shouldDeactivate(e)){
2278         //        this.activeItem.deactivate();
2279         //        delete this.activeItem;
2280         //    }
2281         //}
2282         this.fireEvent("mouseout", this, e, t);
2283     },
2284     
2285     
2286     /**
2287      * Displays this menu relative to another element
2288      * @param {String/HTMLElement/Roo.Element} element The element to align to
2289      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
2290      * the element (defaults to this.defaultAlign)
2291      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
2292      */
2293     show : function(el, pos, parentMenu)
2294     {
2295         if (false === this.fireEvent("beforeshow", this)) {
2296             Roo.log("show canceled");
2297             return;
2298         }
2299         this.parentMenu = parentMenu;
2300         if(!this.el){
2301             this.render();
2302         }
2303         
2304         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
2305     },
2306      /**
2307      * Displays this menu at a specific xy position
2308      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
2309      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
2310      */
2311     showAt : function(xy, parentMenu, /* private: */_e){
2312         this.parentMenu = parentMenu;
2313         if(!this.el){
2314             this.render();
2315         }
2316         if(_e !== false){
2317             this.fireEvent("beforeshow", this);
2318             //xy = this.el.adjustForConstraints(xy);
2319         }
2320         
2321         //this.el.show();
2322         this.hideMenuItems();
2323         this.hidden = false;
2324         this.triggerEl.addClass('open');
2325         this.el.addClass('show');
2326         
2327         // reassign x when hitting right
2328         if(this.el.getWidth() + xy[0] >= Roo.lib.Dom.getViewWidth()){
2329             xy[0] = xy[0] - this.el.getWidth() + this.triggerEl.getWidth();
2330         }
2331         
2332         // reassign y when hitting bottom
2333         if(this.el.getHeight() + xy[1] >= Roo.lib.Dom.getViewHeight()){
2334             xy[1] = xy[1] - this.el.getHeight() - this.triggerEl.getHeight();
2335         }
2336         
2337         // but the list may align on trigger left or trigger top... should it be a properity?
2338         
2339         if(this.el.getStyle('top') != 'auto' && this.el.getStyle('top').slice(-1) != "%"){
2340             this.el.setXY(xy);
2341         }
2342         
2343         this.focus();
2344         this.fireEvent("show", this);
2345     },
2346     
2347     focus : function(){
2348         return;
2349         if(!this.hidden){
2350             this.doFocus.defer(50, this);
2351         }
2352     },
2353
2354     doFocus : function(){
2355         if(!this.hidden){
2356             this.focusEl.focus();
2357         }
2358     },
2359
2360     /**
2361      * Hides this menu and optionally all parent menus
2362      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
2363      */
2364     hide : function(deep)
2365     {
2366         if (false === this.fireEvent("beforehide", this)) {
2367             Roo.log("hide canceled");
2368             return;
2369         }
2370         this.hideMenuItems();
2371         if(this.el && this.isVisible()){
2372            
2373             if(this.activeItem){
2374                 this.activeItem.deactivate();
2375                 this.activeItem = null;
2376             }
2377             this.triggerEl.removeClass('open');;
2378             this.el.removeClass('show');
2379             this.hidden = true;
2380             this.fireEvent("hide", this);
2381         }
2382         if(deep === true && this.parentMenu){
2383             this.parentMenu.hide(true);
2384         }
2385     },
2386     
2387     onTriggerClick : function(e)
2388     {
2389         Roo.log('trigger click');
2390         
2391         var target = e.getTarget();
2392         
2393         Roo.log(target.nodeName.toLowerCase());
2394         
2395         if(target.nodeName.toLowerCase() === 'i'){
2396             e.preventDefault();
2397         }
2398         
2399     },
2400     
2401     onTriggerPress  : function(e)
2402     {
2403         Roo.log('trigger press');
2404         //Roo.log(e.getTarget());
2405        // Roo.log(this.triggerEl.dom);
2406        
2407         // trigger only occurs on normal menu's -- if it's a treeview or dropdown... do not hide/show..
2408         var pel = Roo.get(e.getTarget());
2409         if (pel.findParent('.dropdown-menu') || pel.findParent('.treeview-menu') ) {
2410             Roo.log('is treeview or dropdown?');
2411             return;
2412         }
2413         
2414         if(e.getTarget().nodeName.toLowerCase() !== 'i' && this.isLink){
2415             return;
2416         }
2417         
2418         if (this.isVisible()) {
2419             Roo.log('hide');
2420             this.hide();
2421         } else {
2422             Roo.log('show');
2423             this.show(this.triggerEl, '?', false);
2424         }
2425         
2426         if(this.stopEvent || e.getTarget().nodeName.toLowerCase() === 'i'){
2427             e.stopEvent();
2428         }
2429         
2430     },
2431        
2432     
2433     hideMenuItems : function()
2434     {
2435         Roo.log("hide Menu Items");
2436         if (!this.el) { 
2437             return;
2438         }
2439         
2440         this.el.select('.open',true).each(function(aa) {
2441             
2442             aa.removeClass('open');
2443          
2444         });
2445     },
2446     addxtypeChild : function (tree, cntr) {
2447         var comp= Roo.bootstrap.Menu.superclass.addxtypeChild.call(this, tree, cntr);
2448           
2449         this.menuitems.add(comp);
2450         return comp;
2451
2452     },
2453     getEl : function()
2454     {
2455         Roo.log(this.el);
2456         return this.el;
2457     },
2458     
2459     clear : function()
2460     {
2461         this.getEl().dom.innerHTML = '';
2462         this.menuitems.clear();
2463     }
2464 });
2465
2466  
2467  /*
2468  * - LGPL
2469  *
2470  * menu item
2471  * 
2472  */
2473
2474
2475 /**
2476  * @class Roo.bootstrap.MenuItem
2477  * @extends Roo.bootstrap.Component
2478  * Bootstrap MenuItem class
2479  * @cfg {String} html the menu label
2480  * @cfg {String} href the link
2481  * @cfg {Boolean} preventDefault do not trigger A href on clicks (default false).
2482  * @cfg {Boolean} isContainer is it a container - just returns a drop down item..
2483  * @cfg {Boolean} active  used on sidebars to highlight active itesm
2484  * @cfg {String} fa favicon to show on left of menu item.
2485  * @cfg {Roo.bootsrap.Menu} menu the child menu.
2486  * 
2487  * 
2488  * @constructor
2489  * Create a new MenuItem
2490  * @param {Object} config The config object
2491  */
2492
2493
2494 Roo.bootstrap.MenuItem = function(config){
2495     Roo.bootstrap.MenuItem.superclass.constructor.call(this, config);
2496     this.addEvents({
2497         // raw events
2498         /**
2499          * @event click
2500          * The raw click event for the entire grid.
2501          * @param {Roo.bootstrap.MenuItem} this
2502          * @param {Roo.EventObject} e
2503          */
2504         "click" : true
2505     });
2506 };
2507
2508 Roo.extend(Roo.bootstrap.MenuItem, Roo.bootstrap.Component,  {
2509     
2510     href : false,
2511     html : false,
2512     preventDefault: false,
2513     isContainer : false,
2514     active : false,
2515     fa: false,
2516     
2517     getAutoCreate : function(){
2518         
2519         if(this.isContainer){
2520             return {
2521                 tag: 'li',
2522                 cls: 'dropdown-menu-item '
2523             };
2524         }
2525         var ctag = {
2526             tag: 'span',
2527             html: 'Link'
2528         };
2529         
2530         var anc = {
2531             tag : 'a',
2532             cls : 'dropdown-item',
2533             href : '#',
2534             cn : [  ]
2535         };
2536         
2537         if (this.fa !== false) {
2538             anc.cn.push({
2539                 tag : 'i',
2540                 cls : 'fa fa-' + this.fa
2541             });
2542         }
2543         
2544         anc.cn.push(ctag);
2545         
2546         
2547         var cfg= {
2548             tag: 'li',
2549             cls: 'dropdown-menu-item',
2550             cn: [ anc ]
2551         };
2552         if (this.parent().type == 'treeview') {
2553             cfg.cls = 'treeview-menu';
2554         }
2555         if (this.active) {
2556             cfg.cls += ' active';
2557         }
2558         
2559         
2560         
2561         anc.href = this.href || cfg.cn[0].href ;
2562         ctag.html = this.html || cfg.cn[0].html ;
2563         return cfg;
2564     },
2565     
2566     initEvents: function()
2567     {
2568         if (this.parent().type == 'treeview') {
2569             this.el.select('a').on('click', this.onClick, this);
2570         }
2571         
2572         if (this.menu) {
2573             this.menu.parentType = this.xtype;
2574             this.menu.triggerEl = this.el;
2575             this.menu = this.addxtype(Roo.apply({}, this.menu));
2576         }
2577         
2578     },
2579     onClick : function(e)
2580     {
2581         Roo.log('item on click ');
2582         
2583         if(this.preventDefault){
2584             e.preventDefault();
2585         }
2586         //this.parent().hideMenuItems();
2587         
2588         this.fireEvent('click', this, e);
2589     },
2590     getEl : function()
2591     {
2592         return this.el;
2593     } 
2594 });
2595
2596  
2597
2598  /*
2599  * - LGPL
2600  *
2601  * menu separator
2602  * 
2603  */
2604
2605
2606 /**
2607  * @class Roo.bootstrap.MenuSeparator
2608  * @extends Roo.bootstrap.Component
2609  * Bootstrap MenuSeparator class
2610  * 
2611  * @constructor
2612  * Create a new MenuItem
2613  * @param {Object} config The config object
2614  */
2615
2616
2617 Roo.bootstrap.MenuSeparator = function(config){
2618     Roo.bootstrap.MenuSeparator.superclass.constructor.call(this, config);
2619 };
2620
2621 Roo.extend(Roo.bootstrap.MenuSeparator, Roo.bootstrap.Component,  {
2622     
2623     getAutoCreate : function(){
2624         var cfg = {
2625             cls: 'divider',
2626             tag : 'li'
2627         };
2628         
2629         return cfg;
2630     }
2631    
2632 });
2633
2634  
2635
2636  
2637 /*
2638 * Licence: LGPL
2639 */
2640
2641 /**
2642  * @class Roo.bootstrap.Modal
2643  * @extends Roo.bootstrap.Component
2644  * Bootstrap Modal class
2645  * @cfg {String} title Title of dialog
2646  * @cfg {String} html - the body of the dialog (for simple ones) - you can also use template..
2647  * @cfg {Roo.Template} tmpl - a template with variables. to use it, add a handler in show:method  adn
2648  * @cfg {Boolean} specificTitle default false
2649  * @cfg {Array} buttons Array of buttons or standard button set..
2650  * @cfg {String} buttonPosition (left|right|center) default right (DEPRICATED) - use mr-auto on buttons to put them on the left
2651  * @cfg {Boolean} animate default true
2652  * @cfg {Boolean} allow_close default true
2653  * @cfg {Boolean} fitwindow default false
2654  * @cfg {Number} width fixed width - usefull for chrome extension only really.
2655  * @cfg {Number} height fixed height - usefull for chrome extension only really.
2656  * @cfg {String} size (sm|lg) default empty
2657  * @cfg {Number} max_width set the max width of modal
2658  *
2659  *
2660  * @constructor
2661  * Create a new Modal Dialog
2662  * @param {Object} config The config object
2663  */
2664
2665 Roo.bootstrap.Modal = function(config){
2666     Roo.bootstrap.Modal.superclass.constructor.call(this, config);
2667     this.addEvents({
2668         // raw events
2669         /**
2670          * @event btnclick
2671          * The raw btnclick event for the button
2672          * @param {Roo.EventObject} e
2673          */
2674         "btnclick" : true,
2675         /**
2676          * @event resize
2677          * Fire when dialog resize
2678          * @param {Roo.bootstrap.Modal} this
2679          * @param {Roo.EventObject} e
2680          */
2681         "resize" : true
2682     });
2683     this.buttons = this.buttons || [];
2684
2685     if (this.tmpl) {
2686         this.tmpl = Roo.factory(this.tmpl);
2687     }
2688
2689 };
2690
2691 Roo.extend(Roo.bootstrap.Modal, Roo.bootstrap.Component,  {
2692
2693     title : 'test dialog',
2694
2695     buttons : false,
2696
2697     // set on load...
2698
2699     html: false,
2700
2701     tmp: false,
2702
2703     specificTitle: false,
2704
2705     buttonPosition: 'right',
2706
2707     allow_close : true,
2708
2709     animate : true,
2710
2711     fitwindow: false,
2712     
2713      // private
2714     dialogEl: false,
2715     bodyEl:  false,
2716     footerEl:  false,
2717     titleEl:  false,
2718     closeEl:  false,
2719
2720     size: '',
2721     
2722     max_width: 0,
2723     
2724     max_height: 0,
2725     
2726     fit_content: false,
2727
2728     onRender : function(ct, position)
2729     {
2730         Roo.bootstrap.Component.superclass.onRender.call(this, ct, position);
2731
2732         if(!this.el){
2733             var cfg = Roo.apply({},  this.getAutoCreate());
2734             cfg.id = Roo.id();
2735             //if(!cfg.name){
2736             //    cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
2737             //}
2738             //if (!cfg.name.length) {
2739             //    delete cfg.name;
2740            // }
2741             if (this.cls) {
2742                 cfg.cls += ' ' + this.cls;
2743             }
2744             if (this.style) {
2745                 cfg.style = this.style;
2746             }
2747             this.el = Roo.get(document.body).createChild(cfg, position);
2748         }
2749         //var type = this.el.dom.type;
2750
2751
2752         if(this.tabIndex !== undefined){
2753             this.el.dom.setAttribute('tabIndex', this.tabIndex);
2754         }
2755
2756         this.dialogEl = this.el.select('.modal-dialog',true).first();
2757         this.bodyEl = this.el.select('.modal-body',true).first();
2758         this.closeEl = this.el.select('.modal-header .close', true).first();
2759         this.headerEl = this.el.select('.modal-header',true).first();
2760         this.titleEl = this.el.select('.modal-title',true).first();
2761         this.footerEl = this.el.select('.modal-footer',true).first();
2762
2763         this.maskEl = Roo.DomHelper.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
2764         
2765         //this.el.addClass("x-dlg-modal");
2766
2767         if (this.buttons.length) {
2768             Roo.each(this.buttons, function(bb) {
2769                 var b = Roo.apply({}, bb);
2770                 b.xns = b.xns || Roo.bootstrap;
2771                 b.xtype = b.xtype || 'Button';
2772                 if (typeof(b.listeners) == 'undefined') {
2773                     b.listeners = { click : this.onButtonClick.createDelegate(this)  };
2774                 }
2775
2776                 var btn = Roo.factory(b);
2777
2778                 btn.render(this.getButtonContainer());
2779
2780             },this);
2781         }
2782         // render the children.
2783         var nitems = [];
2784
2785         if(typeof(this.items) != 'undefined'){
2786             var items = this.items;
2787             delete this.items;
2788
2789             for(var i =0;i < items.length;i++) {
2790                 nitems.push(this.addxtype(Roo.apply({}, items[i])));
2791             }
2792         }
2793
2794         this.items = nitems;
2795
2796         // where are these used - they used to be body/close/footer
2797
2798
2799         this.initEvents();
2800         //this.el.addClass([this.fieldClass, this.cls]);
2801
2802     },
2803
2804     getAutoCreate : function()
2805     {
2806         // we will default to modal-body-overflow - might need to remove or make optional later.
2807         var bdy = {
2808                 cls : 'modal-body enable-modal-body-overflow ', 
2809                 html : this.html || ''
2810         };
2811
2812         var title = {
2813             tag: 'h4',
2814             cls : 'modal-title',
2815             html : this.title
2816         };
2817
2818         if(this.specificTitle){
2819             title = this.title;
2820
2821         }
2822
2823         var header = [];
2824         if (this.allow_close && Roo.bootstrap.version == 3) {
2825             header.push({
2826                 tag: 'button',
2827                 cls : 'close',
2828                 html : '&times'
2829             });
2830         }
2831
2832         header.push(title);
2833
2834         if (this.allow_close && Roo.bootstrap.version == 4) {
2835             header.push({
2836                 tag: 'button',
2837                 cls : 'close',
2838                 html : '&times'
2839             });
2840         }
2841         
2842         var size = '';
2843
2844         if(this.size.length){
2845             size = 'modal-' + this.size;
2846         }
2847         
2848         var footer = Roo.bootstrap.version == 3 ?
2849             {
2850                 cls : 'modal-footer',
2851                 cn : [
2852                     {
2853                         tag: 'div',
2854                         cls: 'btn-' + this.buttonPosition
2855                     }
2856                 ]
2857
2858             } :
2859             {  // BS4 uses mr-auto on left buttons....
2860                 cls : 'modal-footer'
2861             };
2862
2863             
2864
2865         
2866         
2867         var modal = {
2868             cls: "modal",
2869              cn : [
2870                 {
2871                     cls: "modal-dialog " + size,
2872                     cn : [
2873                         {
2874                             cls : "modal-content",
2875                             cn : [
2876                                 {
2877                                     cls : 'modal-header',
2878                                     cn : header
2879                                 },
2880                                 bdy,
2881                                 footer
2882                             ]
2883
2884                         }
2885                     ]
2886
2887                 }
2888             ]
2889         };
2890
2891         if(this.animate){
2892             modal.cls += ' fade';
2893         }
2894
2895         return modal;
2896
2897     },
2898     getChildContainer : function() {
2899
2900          return this.bodyEl;
2901
2902     },
2903     getButtonContainer : function() {
2904         
2905          return Roo.bootstrap.version == 4 ?
2906             this.el.select('.modal-footer',true).first()
2907             : this.el.select('.modal-footer div',true).first();
2908
2909     },
2910     initEvents : function()
2911     {
2912         if (this.allow_close) {
2913             this.closeEl.on('click', this.hide, this);
2914         }
2915         Roo.EventManager.onWindowResize(this.resize, this, true);
2916
2917
2918     },
2919   
2920
2921     resize : function()
2922     {
2923         this.maskEl.setSize(
2924             Roo.lib.Dom.getViewWidth(true),
2925             Roo.lib.Dom.getViewHeight(true)
2926         );
2927         
2928         if (this.fitwindow) {
2929             
2930            
2931             this.setSize(
2932                 this.width || Roo.lib.Dom.getViewportWidth(true) - 30,
2933                 this.height || Roo.lib.Dom.getViewportHeight(true) // catering margin-top 30 margin-bottom 30
2934             );
2935             return;
2936         }
2937         
2938         if(this.max_width !== 0) {
2939             
2940             var w = Math.min(this.max_width, Roo.lib.Dom.getViewportWidth(true) - 30);
2941             
2942             if(this.height) {
2943                 this.setSize(w, this.height);
2944                 return;
2945             }
2946             
2947             if(this.max_height) {
2948                 this.setSize(w,Math.min(
2949                     this.max_height,
2950                     Roo.lib.Dom.getViewportHeight(true) - 60
2951                 ));
2952                 
2953                 return;
2954             }
2955             
2956             if(!this.fit_content) {
2957                 this.setSize(w, Roo.lib.Dom.getViewportHeight(true) - 60);
2958                 return;
2959             }
2960             
2961             this.setSize(w, Math.min(
2962                 60 +
2963                 this.headerEl.getHeight() + 
2964                 this.footerEl.getHeight() + 
2965                 this.getChildHeight(this.bodyEl.dom.childNodes),
2966                 Roo.lib.Dom.getViewportHeight(true) - 60)
2967             );
2968         }
2969         
2970     },
2971
2972     setSize : function(w,h)
2973     {
2974         if (!w && !h) {
2975             return;
2976         }
2977         
2978         this.resizeTo(w,h);
2979     },
2980
2981     show : function() {
2982
2983         if (!this.rendered) {
2984             this.render();
2985         }
2986
2987         //this.el.setStyle('display', 'block');
2988         this.el.removeClass('hideing');
2989         this.el.dom.style.display='block';
2990         
2991         Roo.get(document.body).addClass('modal-open');
2992  
2993         if(this.animate){  // element has 'fade'  - so stuff happens after .3s ?- not sure why the delay?
2994             
2995             (function(){
2996                 this.el.addClass('show');
2997                 this.el.addClass('in');
2998             }).defer(50, this);
2999         }else{
3000             this.el.addClass('show');
3001             this.el.addClass('in');
3002         }
3003
3004         // not sure how we can show data in here..
3005         //if (this.tmpl) {
3006         //    this.getChildContainer().dom.innerHTML = this.tmpl.applyTemplate(this);
3007         //}
3008
3009         Roo.get(document.body).addClass("x-body-masked");
3010         
3011         this.maskEl.setSize(Roo.lib.Dom.getViewWidth(true),   Roo.lib.Dom.getViewHeight(true));
3012         this.maskEl.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
3013         this.maskEl.dom.style.display = 'block';
3014         this.maskEl.addClass('show');
3015         
3016         
3017         this.resize();
3018         
3019         this.fireEvent('show', this);
3020
3021         // set zindex here - otherwise it appears to be ignored...
3022         this.el.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
3023
3024         (function () {
3025             this.items.forEach( function(e) {
3026                 e.layout ? e.layout() : false;
3027
3028             });
3029         }).defer(100,this);
3030
3031     },
3032     hide : function()
3033     {
3034         if(this.fireEvent("beforehide", this) !== false){
3035             
3036             this.maskEl.removeClass('show');
3037             
3038             this.maskEl.dom.style.display = '';
3039             Roo.get(document.body).removeClass("x-body-masked");
3040             this.el.removeClass('in');
3041             this.el.select('.modal-dialog', true).first().setStyle('transform','');
3042
3043             if(this.animate){ // why
3044                 this.el.addClass('hideing');
3045                 this.el.removeClass('show');
3046                 (function(){
3047                     if (!this.el.hasClass('hideing')) {
3048                         return; // it's been shown again...
3049                     }
3050                     
3051                     this.el.dom.style.display='';
3052
3053                     Roo.get(document.body).removeClass('modal-open');
3054                     this.el.removeClass('hideing');
3055                 }).defer(150,this);
3056                 
3057             }else{
3058                 this.el.removeClass('show');
3059                 this.el.dom.style.display='';
3060                 Roo.get(document.body).removeClass('modal-open');
3061
3062             }
3063             this.fireEvent('hide', this);
3064         }
3065     },
3066     isVisible : function()
3067     {
3068         
3069         return this.el.hasClass('show') && !this.el.hasClass('hideing');
3070         
3071     },
3072
3073     addButton : function(str, cb)
3074     {
3075
3076
3077         var b = Roo.apply({}, { html : str } );
3078         b.xns = b.xns || Roo.bootstrap;
3079         b.xtype = b.xtype || 'Button';
3080         if (typeof(b.listeners) == 'undefined') {
3081             b.listeners = { click : cb.createDelegate(this)  };
3082         }
3083
3084         var btn = Roo.factory(b);
3085
3086         btn.render(this.getButtonContainer());
3087
3088         return btn;
3089
3090     },
3091
3092     setDefaultButton : function(btn)
3093     {
3094         //this.el.select('.modal-footer').()
3095     },
3096
3097     resizeTo: function(w,h)
3098     {
3099         this.dialogEl.setWidth(w);
3100         
3101         var diff = this.headerEl.getHeight() + this.footerEl.getHeight() + 60; // dialog margin-bottom: 30  
3102
3103         this.bodyEl.setHeight(h - diff);
3104         
3105         this.fireEvent('resize', this);
3106     },
3107     
3108     setContentSize  : function(w, h)
3109     {
3110
3111     },
3112     onButtonClick: function(btn,e)
3113     {
3114         //Roo.log([a,b,c]);
3115         this.fireEvent('btnclick', btn.name, e);
3116     },
3117      /**
3118      * Set the title of the Dialog
3119      * @param {String} str new Title
3120      */
3121     setTitle: function(str) {
3122         this.titleEl.dom.innerHTML = str;
3123     },
3124     /**
3125      * Set the body of the Dialog
3126      * @param {String} str new Title
3127      */
3128     setBody: function(str) {
3129         this.bodyEl.dom.innerHTML = str;
3130     },
3131     /**
3132      * Set the body of the Dialog using the template
3133      * @param {Obj} data - apply this data to the template and replace the body contents.
3134      */
3135     applyBody: function(obj)
3136     {
3137         if (!this.tmpl) {
3138             Roo.log("Error - using apply Body without a template");
3139             //code
3140         }
3141         this.tmpl.overwrite(this.bodyEl, obj);
3142     },
3143     
3144     getChildHeight : function(child_nodes)
3145     {
3146         if(
3147             !child_nodes ||
3148             child_nodes.length == 0
3149         ) {
3150             return;
3151         }
3152         
3153         var child_height = 0;
3154         
3155         for(var i = 0; i < child_nodes.length; i++) {
3156             
3157             /*
3158             * for modal with tabs...
3159             if(child_nodes[i].classList.contains('roo-layout-panel')) {
3160                 
3161                 var layout_childs = child_nodes[i].childNodes;
3162                 
3163                 for(var j = 0; j < layout_childs.length; j++) {
3164                     
3165                     if(layout_childs[j].classList.contains('roo-layout-panel-body')) {
3166                         
3167                         var layout_body_childs = layout_childs[j].childNodes;
3168                         
3169                         for(var k = 0; k < layout_body_childs.length; k++) {
3170                             
3171                             if(layout_body_childs[k].classList.contains('navbar')) {
3172                                 child_height += layout_body_childs[k].offsetHeight;
3173                                 continue;
3174                             }
3175                             
3176                             if(layout_body_childs[k].classList.contains('roo-layout-tabs-body')) {
3177                                 
3178                                 var layout_body_tab_childs = layout_body_childs[k].childNodes;
3179                                 
3180                                 for(var m = 0; m < layout_body_tab_childs.length; m++) {
3181                                     
3182                                     if(layout_body_tab_childs[m].classList.contains('roo-layout-active-content')) {
3183                                         child_height += this.getChildHeight(layout_body_tab_childs[m].childNodes);
3184                                         continue;
3185                                     }
3186                                     
3187                                 }
3188                                 
3189                             }
3190                             
3191                         }
3192                     }
3193                 }
3194                 continue;
3195             }
3196             */
3197             
3198             child_height += child_nodes[i].offsetHeight;
3199             // Roo.log(child_nodes[i].offsetHeight);
3200         }
3201         
3202         return child_height;
3203     }
3204
3205 });
3206
3207
3208 Roo.apply(Roo.bootstrap.Modal,  {
3209     /**
3210          * Button config that displays a single OK button
3211          * @type Object
3212          */
3213         OK :  [{
3214             name : 'ok',
3215             weight : 'primary',
3216             html : 'OK'
3217         }],
3218         /**
3219          * Button config that displays Yes and No buttons
3220          * @type Object
3221          */
3222         YESNO : [
3223             {
3224                 name  : 'no',
3225                 html : 'No'
3226             },
3227             {
3228                 name  :'yes',
3229                 weight : 'primary',
3230                 html : 'Yes'
3231             }
3232         ],
3233
3234         /**
3235          * Button config that displays OK and Cancel buttons
3236          * @type Object
3237          */
3238         OKCANCEL : [
3239             {
3240                name : 'cancel',
3241                 html : 'Cancel'
3242             },
3243             {
3244                 name : 'ok',
3245                 weight : 'primary',
3246                 html : 'OK'
3247             }
3248         ],
3249         /**
3250          * Button config that displays Yes, No and Cancel buttons
3251          * @type Object
3252          */
3253         YESNOCANCEL : [
3254             {
3255                 name : 'yes',
3256                 weight : 'primary',
3257                 html : 'Yes'
3258             },
3259             {
3260                 name : 'no',
3261                 html : 'No'
3262             },
3263             {
3264                 name : 'cancel',
3265                 html : 'Cancel'
3266             }
3267         ],
3268         
3269         zIndex : 10001
3270 });
3271 /*
3272  * - LGPL
3273  *
3274  * messagebox - can be used as a replace
3275  * 
3276  */
3277 /**
3278  * @class Roo.MessageBox
3279  * Utility class for generating different styles of message boxes.  The alias Roo.Msg can also be used.
3280  * Example usage:
3281  *<pre><code>
3282 // Basic alert:
3283 Roo.Msg.alert('Status', 'Changes saved successfully.');
3284
3285 // Prompt for user data:
3286 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
3287     if (btn == 'ok'){
3288         // process text value...
3289     }
3290 });
3291
3292 // Show a dialog using config options:
3293 Roo.Msg.show({
3294    title:'Save Changes?',
3295    msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
3296    buttons: Roo.Msg.YESNOCANCEL,
3297    fn: processResult,
3298    animEl: 'elId'
3299 });
3300 </code></pre>
3301  * @singleton
3302  */
3303 Roo.bootstrap.MessageBox = function(){
3304     var dlg, opt, mask, waitTimer;
3305     var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
3306     var buttons, activeTextEl, bwidth;
3307
3308     
3309     // private
3310     var handleButton = function(button){
3311         dlg.hide();
3312         Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
3313     };
3314
3315     // private
3316     var handleHide = function(){
3317         if(opt && opt.cls){
3318             dlg.el.removeClass(opt.cls);
3319         }
3320         //if(waitTimer){
3321         //    Roo.TaskMgr.stop(waitTimer);
3322         //    waitTimer = null;
3323         //}
3324     };
3325
3326     // private
3327     var updateButtons = function(b){
3328         var width = 0;
3329         if(!b){
3330             buttons["ok"].hide();
3331             buttons["cancel"].hide();
3332             buttons["yes"].hide();
3333             buttons["no"].hide();
3334             dlg.footerEl.hide();
3335             
3336             return width;
3337         }
3338         dlg.footerEl.show();
3339         for(var k in buttons){
3340             if(typeof buttons[k] != "function"){
3341                 if(b[k]){
3342                     buttons[k].show();
3343                     buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.bootstrap.MessageBox.buttonText[k]);
3344                     width += buttons[k].el.getWidth()+15;
3345                 }else{
3346                     buttons[k].hide();
3347                 }
3348             }
3349         }
3350         return width;
3351     };
3352
3353     // private
3354     var handleEsc = function(d, k, e){
3355         if(opt && opt.closable !== false){
3356             dlg.hide();
3357         }
3358         if(e){
3359             e.stopEvent();
3360         }
3361     };
3362
3363     return {
3364         /**
3365          * Returns a reference to the underlying {@link Roo.BasicDialog} element
3366          * @return {Roo.BasicDialog} The BasicDialog element
3367          */
3368         getDialog : function(){
3369            if(!dlg){
3370                 dlg = new Roo.bootstrap.Modal( {
3371                     //draggable: true,
3372                     //resizable:false,
3373                     //constraintoviewport:false,
3374                     //fixedcenter:true,
3375                     //collapsible : false,
3376                     //shim:true,
3377                     //modal: true,
3378                 //    width: 'auto',
3379                   //  height:100,
3380                     //buttonAlign:"center",
3381                     closeClick : function(){
3382                         if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
3383                             handleButton("no");
3384                         }else{
3385                             handleButton("cancel");
3386                         }
3387                     }
3388                 });
3389                 dlg.render();
3390                 dlg.on("hide", handleHide);
3391                 mask = dlg.mask;
3392                 //dlg.addKeyListener(27, handleEsc);
3393                 buttons = {};
3394                 this.buttons = buttons;
3395                 var bt = this.buttonText;
3396                 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
3397                 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
3398                 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
3399                 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
3400                 //Roo.log(buttons);
3401                 bodyEl = dlg.bodyEl.createChild({
3402
3403                     html:'<span class="roo-mb-text"></span><br /><input type="text" class="roo-mb-input" />' +
3404                         '<textarea class="roo-mb-textarea"></textarea>' +
3405                         '<div class="roo-mb-progress-wrap"><div class="roo-mb-progress"><div class="roo-mb-progress-bar">&#160;</div></div></div>'
3406                 });
3407                 msgEl = bodyEl.dom.firstChild;
3408                 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
3409                 textboxEl.enableDisplayMode();
3410                 textboxEl.addKeyListener([10,13], function(){
3411                     if(dlg.isVisible() && opt && opt.buttons){
3412                         if(opt.buttons.ok){
3413                             handleButton("ok");
3414                         }else if(opt.buttons.yes){
3415                             handleButton("yes");
3416                         }
3417                     }
3418                 });
3419                 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
3420                 textareaEl.enableDisplayMode();
3421                 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
3422                 progressEl.enableDisplayMode();
3423                 
3424                 // This is supposed to be the progessElement.. but I think it's controlling the height of everything..
3425                 var pf = progressEl.dom.firstChild;
3426                 if (pf) {
3427                     pp = Roo.get(pf.firstChild);
3428                     pp.setHeight(pf.offsetHeight);
3429                 }
3430                 
3431             }
3432             return dlg;
3433         },
3434
3435         /**
3436          * Updates the message box body text
3437          * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
3438          * the XHTML-compliant non-breaking space character '&amp;#160;')
3439          * @return {Roo.MessageBox} This message box
3440          */
3441         updateText : function(text)
3442         {
3443             if(!dlg.isVisible() && !opt.width){
3444                 dlg.dialogEl.setStyle({ 'max-width' : this.maxWidth});
3445                 // dlg.resizeTo(this.maxWidth, 100); // forcing the height breaks long alerts()
3446             }
3447             msgEl.innerHTML = text || '&#160;';
3448       
3449             var cw =  Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
3450             //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
3451             var w = Math.max(
3452                     Math.min(opt.width || cw , this.maxWidth), 
3453                     Math.max(opt.minWidth || this.minWidth, bwidth)
3454             );
3455             if(opt.prompt){
3456                 activeTextEl.setWidth(w);
3457             }
3458             if(dlg.isVisible()){
3459                 dlg.fixedcenter = false;
3460             }
3461             // to big, make it scroll. = But as usual stupid IE does not support
3462             // !important..
3463             
3464             if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
3465                 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
3466                 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
3467             } else {
3468                 bodyEl.dom.style.height = '';
3469                 bodyEl.dom.style.overflowY = '';
3470             }
3471             if (cw > w) {
3472                 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
3473             } else {
3474                 bodyEl.dom.style.overflowX = '';
3475             }
3476             
3477             dlg.setContentSize(w, bodyEl.getHeight());
3478             if(dlg.isVisible()){
3479                 dlg.fixedcenter = true;
3480             }
3481             return this;
3482         },
3483
3484         /**
3485          * Updates a progress-style message box's text and progress bar.  Only relevant on message boxes
3486          * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
3487          * @param {Number} value Any number between 0 and 1 (e.g., .5)
3488          * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
3489          * @return {Roo.MessageBox} This message box
3490          */
3491         updateProgress : function(value, text){
3492             if(text){
3493                 this.updateText(text);
3494             }
3495             
3496             if (pp) { // weird bug on my firefox - for some reason this is not defined
3497                 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
3498                 pp.setHeight(Math.floor(progressEl.dom.firstChild.offsetHeight));
3499             }
3500             return this;
3501         },        
3502
3503         /**
3504          * Returns true if the message box is currently displayed
3505          * @return {Boolean} True if the message box is visible, else false
3506          */
3507         isVisible : function(){
3508             return dlg && dlg.isVisible();  
3509         },
3510
3511         /**
3512          * Hides the message box if it is displayed
3513          */
3514         hide : function(){
3515             if(this.isVisible()){
3516                 dlg.hide();
3517             }  
3518         },
3519
3520         /**
3521          * Displays a new message box, or reinitializes an existing message box, based on the config options
3522          * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
3523          * The following config object properties are supported:
3524          * <pre>
3525 Property    Type             Description
3526 ----------  ---------------  ------------------------------------------------------------------------------------
3527 animEl            String/Element   An id or Element from which the message box should animate as it opens and
3528                                    closes (defaults to undefined)
3529 buttons           Object/Boolean   A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
3530                                    cancel:'Bar'}), or false to not show any buttons (defaults to false)
3531 closable          Boolean          False to hide the top-right close button (defaults to true).  Note that
3532                                    progress and wait dialogs will ignore this property and always hide the
3533                                    close button as they can only be closed programmatically.
3534 cls               String           A custom CSS class to apply to the message box element
3535 defaultTextHeight Number           The default height in pixels of the message box's multiline textarea if
3536                                    displayed (defaults to 75)
3537 fn                Function         A callback function to execute after closing the dialog.  The arguments to the
3538                                    function will be btn (the name of the button that was clicked, if applicable,
3539                                    e.g. "ok"), and text (the value of the active text field, if applicable).
3540                                    Progress and wait dialogs will ignore this option since they do not respond to
3541                                    user actions and can only be closed programmatically, so any required function
3542                                    should be called by the same code after it closes the dialog.
3543 icon              String           A CSS class that provides a background image to be used as an icon for
3544                                    the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
3545 maxWidth          Number           The maximum width in pixels of the message box (defaults to 600)
3546 minWidth          Number           The minimum width in pixels of the message box (defaults to 100)
3547 modal             Boolean          False to allow user interaction with the page while the message box is
3548                                    displayed (defaults to true)
3549 msg               String           A string that will replace the existing message box body text (defaults
3550                                    to the XHTML-compliant non-breaking space character '&#160;')
3551 multiline         Boolean          True to prompt the user to enter multi-line text (defaults to false)
3552 progress          Boolean          True to display a progress bar (defaults to false)
3553 progressText      String           The text to display inside the progress bar if progress = true (defaults to '')
3554 prompt            Boolean          True to prompt the user to enter single-line text (defaults to false)
3555 proxyDrag         Boolean          True to display a lightweight proxy while dragging (defaults to false)
3556 title             String           The title text
3557 value             String           The string value to set into the active textbox element if displayed
3558 wait              Boolean          True to display a progress bar (defaults to false)
3559 width             Number           The width of the dialog in pixels
3560 </pre>
3561          *
3562          * Example usage:
3563          * <pre><code>
3564 Roo.Msg.show({
3565    title: 'Address',
3566    msg: 'Please enter your address:',
3567    width: 300,
3568    buttons: Roo.MessageBox.OKCANCEL,
3569    multiline: true,
3570    fn: saveAddress,
3571    animEl: 'addAddressBtn'
3572 });
3573 </code></pre>
3574          * @param {Object} config Configuration options
3575          * @return {Roo.MessageBox} This message box
3576          */
3577         show : function(options)
3578         {
3579             
3580             // this causes nightmares if you show one dialog after another
3581             // especially on callbacks..
3582              
3583             if(this.isVisible()){
3584                 
3585                 this.hide();
3586                 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
3587                 Roo.log("Old Dialog Message:" +  msgEl.innerHTML );
3588                 Roo.log("New Dialog Message:" +  options.msg )
3589                 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
3590                 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
3591                 
3592             }
3593             var d = this.getDialog();
3594             opt = options;
3595             d.setTitle(opt.title || "&#160;");
3596             d.closeEl.setDisplayed(opt.closable !== false);
3597             activeTextEl = textboxEl;
3598             opt.prompt = opt.prompt || (opt.multiline ? true : false);
3599             if(opt.prompt){
3600                 if(opt.multiline){
3601                     textboxEl.hide();
3602                     textareaEl.show();
3603                     textareaEl.setHeight(typeof opt.multiline == "number" ?
3604                         opt.multiline : this.defaultTextHeight);
3605                     activeTextEl = textareaEl;
3606                 }else{
3607                     textboxEl.show();
3608                     textareaEl.hide();
3609                 }
3610             }else{
3611                 textboxEl.hide();
3612                 textareaEl.hide();
3613             }
3614             progressEl.setDisplayed(opt.progress === true);
3615             if (opt.progress) {
3616                 d.animate = false; // do not animate progress, as it may not have finished animating before we close it..
3617             }
3618             this.updateProgress(0);
3619             activeTextEl.dom.value = opt.value || "";
3620             if(opt.prompt){
3621                 dlg.setDefaultButton(activeTextEl);
3622             }else{
3623                 var bs = opt.buttons;
3624                 var db = null;
3625                 if(bs && bs.ok){
3626                     db = buttons["ok"];
3627                 }else if(bs && bs.yes){
3628                     db = buttons["yes"];
3629                 }
3630                 dlg.setDefaultButton(db);
3631             }
3632             bwidth = updateButtons(opt.buttons);
3633             this.updateText(opt.msg);
3634             if(opt.cls){
3635                 d.el.addClass(opt.cls);
3636             }
3637             d.proxyDrag = opt.proxyDrag === true;
3638             d.modal = opt.modal !== false;
3639             d.mask = opt.modal !== false ? mask : false;
3640             if(!d.isVisible()){
3641                 // force it to the end of the z-index stack so it gets a cursor in FF
3642                 document.body.appendChild(dlg.el.dom);
3643                 d.animateTarget = null;
3644                 d.show(options.animEl);
3645             }
3646             return this;
3647         },
3648
3649         /**
3650          * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
3651          * the user.  You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
3652          * and closing the message box when the process is complete.
3653          * @param {String} title The title bar text
3654          * @param {String} msg The message box body text
3655          * @return {Roo.MessageBox} This message box
3656          */
3657         progress : function(title, msg){
3658             this.show({
3659                 title : title,
3660                 msg : msg,
3661                 buttons: false,
3662                 progress:true,
3663                 closable:false,
3664                 minWidth: this.minProgressWidth,
3665                 modal : true
3666             });
3667             return this;
3668         },
3669
3670         /**
3671          * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
3672          * If a callback function is passed it will be called after the user clicks the button, and the
3673          * id of the button that was clicked will be passed as the only parameter to the callback
3674          * (could also be the top-right close button).
3675          * @param {String} title The title bar text
3676          * @param {String} msg The message box body text
3677          * @param {Function} fn (optional) The callback function invoked after the message box is closed
3678          * @param {Object} scope (optional) The scope of the callback function
3679          * @return {Roo.MessageBox} This message box
3680          */
3681         alert : function(title, msg, fn, scope)
3682         {
3683             this.show({
3684                 title : title,
3685                 msg : msg,
3686                 buttons: this.OK,
3687                 fn: fn,
3688                 closable : false,
3689                 scope : scope,
3690                 modal : true
3691             });
3692             return this;
3693         },
3694
3695         /**
3696          * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
3697          * interaction while waiting for a long-running process to complete that does not have defined intervals.
3698          * You are responsible for closing the message box when the process is complete.
3699          * @param {String} msg The message box body text
3700          * @param {String} title (optional) The title bar text
3701          * @return {Roo.MessageBox} This message box
3702          */
3703         wait : function(msg, title){
3704             this.show({
3705                 title : title,
3706                 msg : msg,
3707                 buttons: false,
3708                 closable:false,
3709                 progress:true,
3710                 modal:true,
3711                 width:300,
3712                 wait:true
3713             });
3714             waitTimer = Roo.TaskMgr.start({
3715                 run: function(i){
3716                     Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
3717                 },
3718                 interval: 1000
3719             });
3720             return this;
3721         },
3722
3723         /**
3724          * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
3725          * If a callback function is passed it will be called after the user clicks either button, and the id of the
3726          * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
3727          * @param {String} title The title bar text
3728          * @param {String} msg The message box body text
3729          * @param {Function} fn (optional) The callback function invoked after the message box is closed
3730          * @param {Object} scope (optional) The scope of the callback function
3731          * @return {Roo.MessageBox} This message box
3732          */
3733         confirm : function(title, msg, fn, scope){
3734             this.show({
3735                 title : title,
3736                 msg : msg,
3737                 buttons: this.YESNO,
3738                 fn: fn,
3739                 scope : scope,
3740                 modal : true
3741             });
3742             return this;
3743         },
3744
3745         /**
3746          * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
3747          * JavaScript's Window.prompt).  The prompt can be a single-line or multi-line textbox.  If a callback function
3748          * is passed it will be called after the user clicks either button, and the id of the button that was clicked
3749          * (could also be the top-right close button) and the text that was entered will be passed as the two
3750          * parameters to the callback.
3751          * @param {String} title The title bar text
3752          * @param {String} msg The message box body text
3753          * @param {Function} fn (optional) The callback function invoked after the message box is closed
3754          * @param {Object} scope (optional) The scope of the callback function
3755          * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
3756          * property, or the height in pixels to create the textbox (defaults to false / single-line)
3757          * @return {Roo.MessageBox} This message box
3758          */
3759         prompt : function(title, msg, fn, scope, multiline){
3760             this.show({
3761                 title : title,
3762                 msg : msg,
3763                 buttons: this.OKCANCEL,
3764                 fn: fn,
3765                 minWidth:250,
3766                 scope : scope,
3767                 prompt:true,
3768                 multiline: multiline,
3769                 modal : true
3770             });
3771             return this;
3772         },
3773
3774         /**
3775          * Button config that displays a single OK button
3776          * @type Object
3777          */
3778         OK : {ok:true},
3779         /**
3780          * Button config that displays Yes and No buttons
3781          * @type Object
3782          */
3783         YESNO : {yes:true, no:true},
3784         /**
3785          * Button config that displays OK and Cancel buttons
3786          * @type Object
3787          */
3788         OKCANCEL : {ok:true, cancel:true},
3789         /**
3790          * Button config that displays Yes, No and Cancel buttons
3791          * @type Object
3792          */
3793         YESNOCANCEL : {yes:true, no:true, cancel:true},
3794
3795         /**
3796          * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
3797          * @type Number
3798          */
3799         defaultTextHeight : 75,
3800         /**
3801          * The maximum width in pixels of the message box (defaults to 600)
3802          * @type Number
3803          */
3804         maxWidth : 600,
3805         /**
3806          * The minimum width in pixels of the message box (defaults to 100)
3807          * @type Number
3808          */
3809         minWidth : 100,
3810         /**
3811          * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
3812          * for setting a different minimum width than text-only dialogs may need (defaults to 250)
3813          * @type Number
3814          */
3815         minProgressWidth : 250,
3816         /**
3817          * An object containing the default button text strings that can be overriden for localized language support.
3818          * Supported properties are: ok, cancel, yes and no.
3819          * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
3820          * @type Object
3821          */
3822         buttonText : {
3823             ok : "OK",
3824             cancel : "Cancel",
3825             yes : "Yes",
3826             no : "No"
3827         }
3828     };
3829 }();
3830
3831 /**
3832  * Shorthand for {@link Roo.MessageBox}
3833  */
3834 Roo.MessageBox = Roo.MessageBox || Roo.bootstrap.MessageBox;
3835 Roo.Msg = Roo.Msg || Roo.MessageBox;
3836 /*
3837  * - LGPL
3838  *
3839  * navbar
3840  * 
3841  */
3842
3843 /**
3844  * @class Roo.bootstrap.Navbar
3845  * @extends Roo.bootstrap.Component
3846  * Bootstrap Navbar class
3847
3848  * @constructor
3849  * Create a new Navbar
3850  * @param {Object} config The config object
3851  */
3852
3853
3854 Roo.bootstrap.Navbar = function(config){
3855     Roo.bootstrap.Navbar.superclass.constructor.call(this, config);
3856     this.addEvents({
3857         // raw events
3858         /**
3859          * @event beforetoggle
3860          * Fire before toggle the menu
3861          * @param {Roo.EventObject} e
3862          */
3863         "beforetoggle" : true
3864     });
3865 };
3866
3867 Roo.extend(Roo.bootstrap.Navbar, Roo.bootstrap.Component,  {
3868     
3869     
3870    
3871     // private
3872     navItems : false,
3873     loadMask : false,
3874     
3875     
3876     getAutoCreate : function(){
3877         
3878         
3879         throw { message : "nav bar is now a abstract base class - use NavSimplebar / NavHeaderbar / NavSidebar etc..."};
3880         
3881     },
3882     
3883     initEvents :function ()
3884     {
3885         //Roo.log(this.el.select('.navbar-toggle',true));
3886         this.el.select('.navbar-toggle',true).on('click', this.onToggle , this);
3887         
3888         var mark = {
3889             tag: "div",
3890             cls:"x-dlg-mask"
3891         };
3892         
3893         this.maskEl = Roo.DomHelper.append(this.el, mark, true);
3894         
3895         var size = this.el.getSize();
3896         this.maskEl.setSize(size.width, size.height);
3897         this.maskEl.enableDisplayMode("block");
3898         this.maskEl.hide();
3899         
3900         if(this.loadMask){
3901             this.maskEl.show();
3902         }
3903     },
3904     
3905     
3906     getChildContainer : function()
3907     {
3908         if (this.el && this.el.select('.collapse').getCount()) {
3909             return this.el.select('.collapse',true).first();
3910         }
3911         
3912         return this.el;
3913     },
3914     
3915     mask : function()
3916     {
3917         this.maskEl.show();
3918     },
3919     
3920     unmask : function()
3921     {
3922         this.maskEl.hide();
3923     },
3924     onToggle : function()
3925     {
3926         
3927         if(this.fireEvent('beforetoggle', this) === false){
3928             return;
3929         }
3930         var ce = this.el.select('.navbar-collapse',true).first();
3931       
3932         if (!ce.hasClass('show')) {
3933            this.expand();
3934         } else {
3935             this.collapse();
3936         }
3937         
3938         
3939     
3940     },
3941     /**
3942      * Expand the navbar pulldown 
3943      */
3944     expand : function ()
3945     {
3946        
3947         var ce = this.el.select('.navbar-collapse',true).first();
3948         if (ce.hasClass('collapsing')) {
3949             return;
3950         }
3951         ce.dom.style.height = '';
3952                // show it...
3953         ce.addClass('in'); // old...
3954         ce.removeClass('collapse');
3955         ce.addClass('show');
3956         var h = ce.getHeight();
3957         Roo.log(h);
3958         ce.removeClass('show');
3959         // at this point we should be able to see it..
3960         ce.addClass('collapsing');
3961         
3962         ce.setHeight(0); // resize it ...
3963         ce.on('transitionend', function() {
3964             //Roo.log('done transition');
3965             ce.removeClass('collapsing');
3966             ce.addClass('show');
3967             ce.removeClass('collapse');
3968
3969             ce.dom.style.height = '';
3970         }, this, { single: true} );
3971         ce.setHeight(h);
3972         ce.dom.scrollTop = 0;
3973     },
3974     /**
3975      * Collapse the navbar pulldown 
3976      */
3977     collapse : function()
3978     {
3979          var ce = this.el.select('.navbar-collapse',true).first();
3980        
3981         if (ce.hasClass('collapsing') || ce.hasClass('collapse') ) {
3982             // it's collapsed or collapsing..
3983             return;
3984         }
3985         ce.removeClass('in'); // old...
3986         ce.setHeight(ce.getHeight());
3987         ce.removeClass('show');
3988         ce.addClass('collapsing');
3989         
3990         ce.on('transitionend', function() {
3991             ce.dom.style.height = '';
3992             ce.removeClass('collapsing');
3993             ce.addClass('collapse');
3994         }, this, { single: true} );
3995         ce.setHeight(0);
3996     }
3997     
3998     
3999     
4000 });
4001
4002
4003
4004  
4005
4006  /*
4007  * - LGPL
4008  *
4009  * navbar
4010  * 
4011  */
4012
4013 /**
4014  * @class Roo.bootstrap.NavSimplebar
4015  * @extends Roo.bootstrap.Navbar
4016  * Bootstrap Sidebar class
4017  *
4018  * @cfg {Boolean} inverse is inverted color
4019  * 
4020  * @cfg {String} type (nav | pills | tabs)
4021  * @cfg {Boolean} arrangement stacked | justified
4022  * @cfg {String} align (left | right) alignment
4023  * 
4024  * @cfg {Boolean} main (true|false) main nav bar? default false
4025  * @cfg {Boolean} loadMask (true|false) loadMask on the bar
4026  * 
4027  * @cfg {String} tag (header|footer|nav|div) default is nav 
4028
4029  * @cfg {String} weight (light|primary|secondary|success|danger|warning|info|dark|white) default is light.
4030  * 
4031  * 
4032  * @constructor
4033  * Create a new Sidebar
4034  * @param {Object} config The config object
4035  */
4036
4037
4038 Roo.bootstrap.NavSimplebar = function(config){
4039     Roo.bootstrap.NavSimplebar.superclass.constructor.call(this, config);
4040 };
4041
4042 Roo.extend(Roo.bootstrap.NavSimplebar, Roo.bootstrap.Navbar,  {
4043     
4044     inverse: false,
4045     
4046     type: false,
4047     arrangement: '',
4048     align : false,
4049     
4050     weight : 'light',
4051     
4052     main : false,
4053     
4054     
4055     tag : false,
4056     
4057     
4058     getAutoCreate : function(){
4059         
4060         
4061         var cfg = {
4062             tag : this.tag || 'div',
4063             cls : 'navbar roo-navbar-simple' //navbar-expand-lg ??
4064         };
4065         if (['light','white'].indexOf(this.weight) > -1) {
4066             cfg.cls += ['light','white'].indexOf(this.weight) > -1 ? ' navbar-light' : ' navbar-dark';
4067         }
4068         cfg.cls += ' bg-' + this.weight;
4069         
4070         if (this.inverse) {
4071             cfg.cls += ' navbar-inverse';
4072             
4073         }
4074         
4075         // i'm not actually sure these are really used - normally we add a navGroup to a navbar
4076         
4077         if (Roo.bootstrap.version == 4 && this.xtype == 'NavSimplebar') {
4078             return cfg;
4079         }
4080         
4081         
4082     
4083         
4084         cfg.cn = [
4085             {
4086                 cls: 'nav nav-' + this.xtype,
4087                 tag : 'ul'
4088             }
4089         ];
4090         
4091          
4092         this.type = this.type || 'nav';
4093         if (['tabs','pills'].indexOf(this.type) != -1) {
4094             cfg.cn[0].cls += ' nav-' + this.type
4095         
4096         
4097         } else {
4098             if (this.type!=='nav') {
4099                 Roo.log('nav type must be nav/tabs/pills')
4100             }
4101             cfg.cn[0].cls += ' navbar-nav'
4102         }
4103         
4104         
4105         
4106         
4107         if (['stacked','justified'].indexOf(this.arrangement) != -1) {
4108             cfg.cn[0].cls += ' nav-' + this.arrangement;
4109         }
4110         
4111         
4112         if (this.align === 'right') {
4113             cfg.cn[0].cls += ' navbar-right';
4114         }
4115         
4116         
4117         
4118         
4119         return cfg;
4120     
4121         
4122     }
4123     
4124     
4125     
4126 });
4127
4128
4129
4130  
4131
4132  
4133        /*
4134  * - LGPL
4135  *
4136  * navbar
4137  * navbar-fixed-top
4138  * navbar-expand-md  fixed-top 
4139  */
4140
4141 /**
4142  * @class Roo.bootstrap.NavHeaderbar
4143  * @extends Roo.bootstrap.NavSimplebar
4144  * Bootstrap Sidebar class
4145  *
4146  * @cfg {String} brand what is brand
4147  * @cfg {String} position (fixed-top|fixed-bottom|static-top) position
4148  * @cfg {String} brand_href href of the brand
4149  * @cfg {Boolean} srButton generate the (screen reader / mobile) sr-only button   default true
4150  * @cfg {Boolean} autohide a top nav bar header that hides on scroll.
4151  * @cfg {Boolean} desktopCenter should the header be centered on desktop using a container class
4152  * @cfg {Roo.bootstrap.Row} mobilerow - a row to display on mobile only..
4153  * 
4154  * @constructor
4155  * Create a new Sidebar
4156  * @param {Object} config The config object
4157  */
4158
4159
4160 Roo.bootstrap.NavHeaderbar = function(config){
4161     Roo.bootstrap.NavHeaderbar.superclass.constructor.call(this, config);
4162       
4163 };
4164
4165 Roo.extend(Roo.bootstrap.NavHeaderbar, Roo.bootstrap.NavSimplebar,  {
4166     
4167     position: '',
4168     brand: '',
4169     brand_href: false,
4170     srButton : true,
4171     autohide : false,
4172     desktopCenter : false,
4173    
4174     
4175     getAutoCreate : function(){
4176         
4177         var   cfg = {
4178             tag: this.nav || 'nav',
4179             cls: 'navbar navbar-expand-md',
4180             role: 'navigation',
4181             cn: []
4182         };
4183         
4184         var cn = cfg.cn;
4185         if (this.desktopCenter) {
4186             cn.push({cls : 'container', cn : []});
4187             cn = cn[0].cn;
4188         }
4189         
4190         if(this.srButton){
4191             var btn = {
4192                 tag: 'button',
4193                 type: 'button',
4194                 cls: 'navbar-toggle navbar-toggler',
4195                 'data-toggle': 'collapse',
4196                 cn: [
4197                     {
4198                         tag: 'span',
4199                         cls: 'sr-only',
4200                         html: 'Toggle navigation'
4201                     },
4202                     {
4203                         tag: 'span',
4204                         cls: 'icon-bar navbar-toggler-icon'
4205                     },
4206                     {
4207                         tag: 'span',
4208                         cls: 'icon-bar'
4209                     },
4210                     {
4211                         tag: 'span',
4212                         cls: 'icon-bar'
4213                     }
4214                 ]
4215             };
4216             
4217             cn.push( Roo.bootstrap.version == 4 ? btn : {
4218                 tag: 'div',
4219                 cls: 'navbar-header',
4220                 cn: [
4221                     btn
4222                 ]
4223             });
4224         }
4225         
4226         cn.push({
4227             tag: 'div',
4228             cls: Roo.bootstrap.version == 4  ? 'nav flex-row roo-navbar-collapse' : 'collapse navbar-collapse roo-navbar-collapse',
4229             cn : []
4230         });
4231         
4232         cfg.cls += this.inverse ? ' navbar-inverse navbar-dark bg-dark' : ' navbar-default';
4233         
4234         if (['light','white'].indexOf(this.weight) > -1) {
4235             cfg.cls += ['light','white'].indexOf(this.weight) > -1 ? ' navbar-light' : ' navbar-dark';
4236         }
4237         cfg.cls += ' bg-' + this.weight;
4238         
4239         
4240         if (['fixed-top','fixed-bottom','static-top'].indexOf(this.position)>-1) {
4241             cfg.cls += ' navbar-' + this.position + ' ' + this.position ;
4242             
4243             // tag can override this..
4244             
4245             cfg.tag = this.tag || (this.position  == 'fixed-bottom' ? 'footer' : 'header');
4246         }
4247         
4248         if (this.brand !== '') {
4249             var cp =  Roo.bootstrap.version == 4 ? cn : cn[0].cn;
4250             cp.unshift({ // changed from push ?? BS4 needs it at the start? - does this break or exsiting?
4251                 tag: 'a',
4252                 href: this.brand_href ? this.brand_href : '#',
4253                 cls: 'navbar-brand',
4254                 cn: [
4255                 this.brand
4256                 ]
4257             });
4258         }
4259         
4260         if(this.main){
4261             cfg.cls += ' main-nav';
4262         }
4263         
4264         
4265         return cfg;
4266
4267         
4268     },
4269     getHeaderChildContainer : function()
4270     {
4271         if (this.srButton && this.el.select('.navbar-header').getCount()) {
4272             return this.el.select('.navbar-header',true).first();
4273         }
4274         
4275         return this.getChildContainer();
4276     },
4277     
4278     
4279     initEvents : function()
4280     {
4281         Roo.bootstrap.NavHeaderbar.superclass.initEvents.call(this);
4282         
4283         if (this.autohide) {
4284             
4285             var prevScroll = 0;
4286             var ft = this.el;
4287             
4288             Roo.get(document).on('scroll',function(e) {
4289                 var ns = Roo.get(document).getScroll().top;
4290                 var os = prevScroll;
4291                 prevScroll = ns;
4292                 
4293                 if(ns > os){
4294                     ft.removeClass('slideDown');
4295                     ft.addClass('slideUp');
4296                     return;
4297                 }
4298                 ft.removeClass('slideUp');
4299                 ft.addClass('slideDown');
4300                  
4301               
4302           },this);
4303         }
4304     }    
4305     
4306 });
4307
4308
4309
4310  
4311
4312  /*
4313  * - LGPL
4314  *
4315  * navbar
4316  * 
4317  */
4318
4319 /**
4320  * @class Roo.bootstrap.NavSidebar
4321  * @extends Roo.bootstrap.Navbar
4322  * Bootstrap Sidebar class
4323  * 
4324  * @constructor
4325  * Create a new Sidebar
4326  * @param {Object} config The config object
4327  */
4328
4329
4330 Roo.bootstrap.NavSidebar = function(config){
4331     Roo.bootstrap.NavSidebar.superclass.constructor.call(this, config);
4332 };
4333
4334 Roo.extend(Roo.bootstrap.NavSidebar, Roo.bootstrap.Navbar,  {
4335     
4336     sidebar : true, // used by Navbar Item and NavbarGroup at present...
4337     
4338     getAutoCreate : function(){
4339         
4340         
4341         return  {
4342             tag: 'div',
4343             cls: 'sidebar sidebar-nav'
4344         };
4345     
4346         
4347     }
4348     
4349     
4350     
4351 });
4352
4353
4354
4355  
4356
4357  /*
4358  * - LGPL
4359  *
4360  * nav group
4361  * 
4362  */
4363
4364 /**
4365  * @class Roo.bootstrap.NavGroup
4366  * @extends Roo.bootstrap.Component
4367  * Bootstrap NavGroup class
4368  * @cfg {String} align (left|right)
4369  * @cfg {Boolean} inverse
4370  * @cfg {String} type (nav|pills|tab) default nav
4371  * @cfg {String} navId - reference Id for navbar.
4372
4373  * 
4374  * @constructor
4375  * Create a new nav group
4376  * @param {Object} config The config object
4377  */
4378
4379 Roo.bootstrap.NavGroup = function(config){
4380     Roo.bootstrap.NavGroup.superclass.constructor.call(this, config);
4381     this.navItems = [];
4382    
4383     Roo.bootstrap.NavGroup.register(this);
4384      this.addEvents({
4385         /**
4386              * @event changed
4387              * Fires when the active item changes
4388              * @param {Roo.bootstrap.NavGroup} this
4389              * @param {Roo.bootstrap.Navbar.Item} selected The item selected
4390              * @param {Roo.bootstrap.Navbar.Item} prev The previously selected item 
4391          */
4392         'changed': true
4393      });
4394     
4395 };
4396
4397 Roo.extend(Roo.bootstrap.NavGroup, Roo.bootstrap.Component,  {
4398     
4399     align: '',
4400     inverse: false,
4401     form: false,
4402     type: 'nav',
4403     navId : '',
4404     // private
4405     
4406     navItems : false, 
4407     
4408     getAutoCreate : function()
4409     {
4410         var cfg = Roo.apply({}, Roo.bootstrap.NavGroup.superclass.getAutoCreate.call(this));
4411         
4412         cfg = {
4413             tag : 'ul',
4414             cls: 'nav' 
4415         };
4416         if (Roo.bootstrap.version == 4) {
4417             if (['tabs','pills'].indexOf(this.type) != -1) {
4418                 cfg.cls += ' nav-' + this.type; 
4419             } else {
4420                 // trying to remove so header bar can right align top?
4421                 if (this.parent() && this.parent().xtype != 'NavHeaderbar') {
4422                     // do not use on header bar... 
4423                     cfg.cls += ' navbar-nav';
4424                 }
4425             }
4426             
4427         } else {
4428             if (['tabs','pills'].indexOf(this.type) != -1) {
4429                 cfg.cls += ' nav-' + this.type
4430             } else {
4431                 if (this.type !== 'nav') {
4432                     Roo.log('nav type must be nav/tabs/pills')
4433                 }
4434                 cfg.cls += ' navbar-nav'
4435             }
4436         }
4437         
4438         if (this.parent() && this.parent().sidebar) {
4439             cfg = {
4440                 tag: 'ul',
4441                 cls: 'dashboard-menu sidebar-menu'
4442             };
4443             
4444             return cfg;
4445         }
4446         
4447         if (this.form === true) {
4448             cfg = {
4449                 tag: 'form',
4450                 cls: 'navbar-form form-inline'
4451             };
4452             //nav navbar-right ml-md-auto
4453             if (this.align === 'right') {
4454                 cfg.cls += ' navbar-right ml-md-auto';
4455             } else {
4456                 cfg.cls += ' navbar-left';
4457             }
4458         }
4459         
4460         if (this.align === 'right') {
4461             cfg.cls += ' navbar-right ml-md-auto';
4462         } else {
4463             cfg.cls += ' mr-auto';
4464         }
4465         
4466         if (this.inverse) {
4467             cfg.cls += ' navbar-inverse';
4468             
4469         }
4470         
4471         
4472         return cfg;
4473     },
4474     /**
4475     * sets the active Navigation item
4476     * @param {Roo.bootstrap.NavItem} the new current navitem
4477     */
4478     setActiveItem : function(item)
4479     {
4480         var prev = false;
4481         Roo.each(this.navItems, function(v){
4482             if (v == item) {
4483                 return ;
4484             }
4485             if (v.isActive()) {
4486                 v.setActive(false, true);
4487                 prev = v;
4488                 
4489             }
4490             
4491         });
4492
4493         item.setActive(true, true);
4494         this.fireEvent('changed', this, item, prev);
4495         
4496         
4497     },
4498     /**
4499     * gets the active Navigation item
4500     * @return {Roo.bootstrap.NavItem} the current navitem
4501     */
4502     getActive : function()
4503     {
4504         
4505         var prev = false;
4506         Roo.each(this.navItems, function(v){
4507             
4508             if (v.isActive()) {
4509                 prev = v;
4510                 
4511             }
4512             
4513         });
4514         return prev;
4515     },
4516     
4517     indexOfNav : function()
4518     {
4519         
4520         var prev = false;
4521         Roo.each(this.navItems, function(v,i){
4522             
4523             if (v.isActive()) {
4524                 prev = i;
4525                 
4526             }
4527             
4528         });
4529         return prev;
4530     },
4531     /**
4532     * adds a Navigation item
4533     * @param {Roo.bootstrap.NavItem} the navitem to add
4534     */
4535     addItem : function(cfg)
4536     {
4537         if (this.form && Roo.bootstrap.version == 4) {
4538             cfg.tag = 'div';
4539         }
4540         var cn = new Roo.bootstrap.NavItem(cfg);
4541         this.register(cn);
4542         cn.parentId = this.id;
4543         cn.onRender(this.el, null);
4544         return cn;
4545     },
4546     /**
4547     * register a Navigation item
4548     * @param {Roo.bootstrap.NavItem} the navitem to add
4549     */
4550     register : function(item)
4551     {
4552         this.navItems.push( item);
4553         item.navId = this.navId;
4554     
4555     },
4556     
4557     /**
4558     * clear all the Navigation item
4559     */
4560    
4561     clearAll : function()
4562     {
4563         this.navItems = [];
4564         this.el.dom.innerHTML = '';
4565     },
4566     
4567     getNavItem: function(tabId)
4568     {
4569         var ret = false;
4570         Roo.each(this.navItems, function(e) {
4571             if (e.tabId == tabId) {
4572                ret =  e;
4573                return false;
4574             }
4575             return true;
4576             
4577         });
4578         return ret;
4579     },
4580     
4581     setActiveNext : function()
4582     {
4583         var i = this.indexOfNav(this.getActive());
4584         if (i > this.navItems.length) {
4585             return;
4586         }
4587         this.setActiveItem(this.navItems[i+1]);
4588     },
4589     setActivePrev : function()
4590     {
4591         var i = this.indexOfNav(this.getActive());
4592         if (i  < 1) {
4593             return;
4594         }
4595         this.setActiveItem(this.navItems[i-1]);
4596     },
4597     clearWasActive : function(except) {
4598         Roo.each(this.navItems, function(e) {
4599             if (e.tabId != except.tabId && e.was_active) {
4600                e.was_active = false;
4601                return false;
4602             }
4603             return true;
4604             
4605         });
4606     },
4607     getWasActive : function ()
4608     {
4609         var r = false;
4610         Roo.each(this.navItems, function(e) {
4611             if (e.was_active) {
4612                r = e;
4613                return false;
4614             }
4615             return true;
4616             
4617         });
4618         return r;
4619     }
4620     
4621     
4622 });
4623
4624  
4625 Roo.apply(Roo.bootstrap.NavGroup, {
4626     
4627     groups: {},
4628      /**
4629     * register a Navigation Group
4630     * @param {Roo.bootstrap.NavGroup} the navgroup to add
4631     */
4632     register : function(navgrp)
4633     {
4634         this.groups[navgrp.navId] = navgrp;
4635         
4636     },
4637     /**
4638     * fetch a Navigation Group based on the navigation ID
4639     * @param {string} the navgroup to add
4640     * @returns {Roo.bootstrap.NavGroup} the navgroup 
4641     */
4642     get: function(navId) {
4643         if (typeof(this.groups[navId]) == 'undefined') {
4644             return false;
4645             //this.register(new Roo.bootstrap.NavGroup({ navId : navId }));
4646         }
4647         return this.groups[navId] ;
4648     }
4649     
4650     
4651     
4652 });
4653
4654  /*
4655  * - LGPL
4656  *
4657  * row
4658  * 
4659  */
4660
4661 /**
4662  * @class Roo.bootstrap.NavItem
4663  * @extends Roo.bootstrap.Component
4664  * Bootstrap Navbar.NavItem class
4665  * @cfg {String} href  link to
4666  * @cfg {String} button_weight (default | primary | secondary | success | info | warning | danger | link ) default none
4667
4668  * @cfg {String} html content of button
4669  * @cfg {String} badge text inside badge
4670  * @cfg {String} badgecls (bg-green|bg-red|bg-yellow)the extra classes for the badge
4671  * @cfg {String} glyphicon DEPRICATED - use fa
4672  * @cfg {String} icon DEPRICATED - use fa
4673  * @cfg {String} fa - Fontawsome icon name (can add stuff to it like fa-2x)
4674  * @cfg {Boolean} active Is item active
4675  * @cfg {Boolean} disabled Is item disabled
4676  
4677  * @cfg {Boolean} preventDefault (true | false) default false
4678  * @cfg {String} tabId the tab that this item activates.
4679  * @cfg {String} tagtype (a|span) render as a href or span?
4680  * @cfg {Boolean} animateRef (true|false) link to element default false  
4681   
4682  * @constructor
4683  * Create a new Navbar Item
4684  * @param {Object} config The config object
4685  */
4686 Roo.bootstrap.NavItem = function(config){
4687     Roo.bootstrap.NavItem.superclass.constructor.call(this, config);
4688     this.addEvents({
4689         // raw events
4690         /**
4691          * @event click
4692          * The raw click event for the entire grid.
4693          * @param {Roo.EventObject} e
4694          */
4695         "click" : true,
4696          /**
4697             * @event changed
4698             * Fires when the active item active state changes
4699             * @param {Roo.bootstrap.NavItem} this
4700             * @param {boolean} state the new state
4701              
4702          */
4703         'changed': true,
4704         /**
4705             * @event scrollto
4706             * Fires when scroll to element
4707             * @param {Roo.bootstrap.NavItem} this
4708             * @param {Object} options
4709             * @param {Roo.EventObject} e
4710              
4711          */
4712         'scrollto': true
4713     });
4714    
4715 };
4716
4717 Roo.extend(Roo.bootstrap.NavItem, Roo.bootstrap.Component,  {
4718     
4719     href: false,
4720     html: '',
4721     badge: '',
4722     icon: false,
4723     fa : false,
4724     glyphicon: false,
4725     active: false,
4726     preventDefault : false,
4727     tabId : false,
4728     tagtype : 'a',
4729     tag: 'li',
4730     disabled : false,
4731     animateRef : false,
4732     was_active : false,
4733     button_weight : '',
4734     button_outline : false,
4735     
4736     navLink: false,
4737     
4738     getAutoCreate : function(){
4739          
4740         var cfg = {
4741             tag: this.tag,
4742             cls: 'nav-item'
4743         };
4744         
4745         if (this.active) {
4746             cfg.cls = typeof(cfg.cls) == 'undefined' ? 'active' : cfg.cls + ' active';
4747         }
4748         if (this.disabled) {
4749             cfg.cls += ' disabled';
4750         }
4751         
4752         // BS4 only?
4753         if (this.button_weight.length) {
4754             cfg.tag = this.href ? 'a' : 'button';
4755             cfg.html = this.html || '';
4756             cfg.cls += ' btn btn' + (this.button_outline ? '-outline' : '') + '-' + this.button_weight;
4757             if (this.href) {
4758                 cfg.href = this.href;
4759             }
4760             if (this.fa) {
4761                 cfg.html = '<i class="fa fas fa-'+this.fa+'"></i> <span>' + this.html + '</span>';
4762             }
4763             
4764             // menu .. should add dropdown-menu class - so no need for carat..
4765             
4766             if (this.badge !== '') {
4767                  
4768                 cfg.html += ' <span class="badge badge-secondary">' + this.badge + '</span>';
4769             }
4770             return cfg;
4771         }
4772         
4773         if (this.href || this.html || this.glyphicon || this.icon || this.fa) {
4774             cfg.cn = [
4775                 {
4776                     tag: this.tagtype,
4777                     href : this.href || "#",
4778                     html: this.html || ''
4779                 }
4780             ];
4781             if (this.tagtype == 'a') {
4782                 cfg.cn[0].cls = 'nav-link';
4783             }
4784             if (this.icon) {
4785                 cfg.cn[0].html = '<i class="'+this.icon+'"></i> <span>' + cfg.cn[0].html + '</span>';
4786             }
4787             if (this.fa) {
4788                 cfg.cn[0].html = '<i class="fa fas fa-'+this.fa+'"></i> <span>' + cfg.cn[0].html + '</span>';
4789             }
4790             if(this.glyphicon) {
4791                 cfg.cn[0].html = '<span class="glyphicon glyphicon-' + this.glyphicon + '"></span> '  + cfg.cn[0].html;
4792             }
4793             
4794             if (this.menu) {
4795                 
4796                 cfg.cn[0].html += " <span class='caret'></span>";
4797              
4798             }
4799             
4800             if (this.badge !== '') {
4801                  
4802                 cfg.cn[0].html += ' <span class="badge badge-secondary">' + this.badge + '</span>';
4803             }
4804         }
4805         
4806         
4807         
4808         return cfg;
4809     },
4810     onRender : function(ct, position)
4811     {
4812        // Roo.log("Call onRender: " + this.xtype);
4813         if (Roo.bootstrap.version == 4 && ct.dom.type != 'ul') {
4814             this.tag = 'div';
4815         }
4816         
4817         var ret = Roo.bootstrap.NavItem.superclass.onRender.call(this, ct, position);
4818         this.navLink = this.el.select('.nav-link',true).first();
4819         return ret;
4820     },
4821       
4822     
4823     initEvents: function() 
4824     {
4825         if (typeof (this.menu) != 'undefined') {
4826             this.menu.parentType = this.xtype;
4827             this.menu.triggerEl = this.el;
4828             this.menu = this.addxtype(Roo.apply({}, this.menu));
4829         }
4830         
4831         this.el.select('a',true).on('click', this.onClick, this);
4832         
4833         if(this.tagtype == 'span'){
4834             this.el.select('span',true).on('click', this.onClick, this);
4835         }
4836        
4837         // at this point parent should be available..
4838         this.parent().register(this);
4839     },
4840     
4841     onClick : function(e)
4842     {
4843         if (e.getTarget('.dropdown-menu-item')) {
4844             // did you click on a menu itemm.... - then don't trigger onclick..
4845             return;
4846         }
4847         
4848         if(
4849                 this.preventDefault || 
4850                 this.href == '#' 
4851         ){
4852             Roo.log("NavItem - prevent Default?");
4853             e.preventDefault();
4854         }
4855         
4856         if (this.disabled) {
4857             return;
4858         }
4859         
4860         var tg = Roo.bootstrap.TabGroup.get(this.navId);
4861         if (tg && tg.transition) {
4862             Roo.log("waiting for the transitionend");
4863             return;
4864         }
4865         
4866         
4867         
4868         //Roo.log("fire event clicked");
4869         if(this.fireEvent('click', this, e) === false){
4870             return;
4871         };
4872         
4873         if(this.tagtype == 'span'){
4874             return;
4875         }
4876         
4877         //Roo.log(this.href);
4878         var ael = this.el.select('a',true).first();
4879         //Roo.log(ael);
4880         
4881         if(ael && this.animateRef && this.href.indexOf('#') > -1){
4882             //Roo.log(["test:",ael.dom.href.split("#")[0], document.location.toString().split("#")[0]]);
4883             if (ael.dom.href.split("#")[0] != document.location.toString().split("#")[0]) {
4884                 return; // ignore... - it's a 'hash' to another page.
4885             }
4886             Roo.log("NavItem - prevent Default?");
4887             e.preventDefault();
4888             this.scrollToElement(e);
4889         }
4890         
4891         
4892         var p =  this.parent();
4893    
4894         if (['tabs','pills'].indexOf(p.type)!==-1) {
4895             if (typeof(p.setActiveItem) !== 'undefined') {
4896                 p.setActiveItem(this);
4897             }
4898         }
4899         
4900         // if parent is a navbarheader....- and link is probably a '#' page ref.. then remove the expanded menu.
4901         if (p.parentType == 'NavHeaderbar' && !this.menu) {
4902             // remove the collapsed menu expand...
4903             p.parent().el.select('.roo-navbar-collapse',true).removeClass('in');  
4904         }
4905     },
4906     
4907     isActive: function () {
4908         return this.active
4909     },
4910     setActive : function(state, fire, is_was_active)
4911     {
4912         if (this.active && !state && this.navId) {
4913             this.was_active = true;
4914             var nv = Roo.bootstrap.NavGroup.get(this.navId);
4915             if (nv) {
4916                 nv.clearWasActive(this);
4917             }
4918             
4919         }
4920         this.active = state;
4921         
4922         if (!state ) {
4923             this.el.removeClass('active');
4924             this.navLink ? this.navLink.removeClass('active') : false;
4925         } else if (!this.el.hasClass('active')) {
4926             
4927             this.el.addClass('active');
4928             if (Roo.bootstrap.version == 4 && this.navLink ) {
4929                 this.navLink.addClass('active');
4930             }
4931             
4932         }
4933         if (fire) {
4934             this.fireEvent('changed', this, state);
4935         }
4936         
4937         // show a panel if it's registered and related..
4938         
4939         if (!this.navId || !this.tabId || !state || is_was_active) {
4940             return;
4941         }
4942         
4943         var tg = Roo.bootstrap.TabGroup.get(this.navId);
4944         if (!tg) {
4945             return;
4946         }
4947         var pan = tg.getPanelByName(this.tabId);
4948         if (!pan) {
4949             return;
4950         }
4951         // if we can not flip to new panel - go back to old nav highlight..
4952         if (false == tg.showPanel(pan)) {
4953             var nv = Roo.bootstrap.NavGroup.get(this.navId);
4954             if (nv) {
4955                 var onav = nv.getWasActive();
4956                 if (onav) {
4957                     onav.setActive(true, false, true);
4958                 }
4959             }
4960             
4961         }
4962         
4963         
4964         
4965     },
4966      // this should not be here...
4967     setDisabled : function(state)
4968     {
4969         this.disabled = state;
4970         if (!state ) {
4971             this.el.removeClass('disabled');
4972         } else if (!this.el.hasClass('disabled')) {
4973             this.el.addClass('disabled');
4974         }
4975         
4976     },
4977     
4978     /**
4979      * Fetch the element to display the tooltip on.
4980      * @return {Roo.Element} defaults to this.el
4981      */
4982     tooltipEl : function()
4983     {
4984         return this.el.select('' + this.tagtype + '', true).first();
4985     },
4986     
4987     scrollToElement : function(e)
4988     {
4989         var c = document.body;
4990         
4991         /*
4992          * Firefox / IE places the overflow at the html level, unless specifically styled to behave differently.
4993          */
4994         if(Roo.isFirefox || Roo.isIE || Roo.isIE11){
4995             c = document.documentElement;
4996         }
4997         
4998         var target = Roo.get(c).select('a[name=' + this.href.split('#')[1] +']', true).first();
4999         
5000         if(!target){
5001             return;
5002         }
5003
5004         var o = target.calcOffsetsTo(c);
5005         
5006         var options = {
5007             target : target,
5008             value : o[1]
5009         };
5010         
5011         this.fireEvent('scrollto', this, options, e);
5012         
5013         Roo.get(c).scrollTo('top', options.value, true);
5014         
5015         return;
5016     }
5017 });
5018  
5019
5020  /*
5021  * - LGPL
5022  *
5023  * sidebar item
5024  *
5025  *  li
5026  *    <span> icon </span>
5027  *    <span> text </span>
5028  *    <span>badge </span>
5029  */
5030
5031 /**
5032  * @class Roo.bootstrap.NavSidebarItem
5033  * @extends Roo.bootstrap.NavItem
5034  * Bootstrap Navbar.NavSidebarItem class
5035  * {String} badgeWeight (default|primary|success|info|warning|danger)the extra classes for the badge
5036  * {Boolean} open is the menu open
5037  * {Boolean} buttonView use button as the tigger el rather that a (default false)
5038  * {String} buttonWeight (default|primary|success|info|warning|danger)the extra classes for the button
5039  * {String} buttonSize (sm|md|lg)the extra classes for the button
5040  * {Boolean} showArrow show arrow next to the text (default true)
5041  * @constructor
5042  * Create a new Navbar Button
5043  * @param {Object} config The config object
5044  */
5045 Roo.bootstrap.NavSidebarItem = function(config){
5046     Roo.bootstrap.NavSidebarItem.superclass.constructor.call(this, config);
5047     this.addEvents({
5048         // raw events
5049         /**
5050          * @event click
5051          * The raw click event for the entire grid.
5052          * @param {Roo.EventObject} e
5053          */
5054         "click" : true,
5055          /**
5056             * @event changed
5057             * Fires when the active item active state changes
5058             * @param {Roo.bootstrap.NavSidebarItem} this
5059             * @param {boolean} state the new state
5060              
5061          */
5062         'changed': true
5063     });
5064    
5065 };
5066
5067 Roo.extend(Roo.bootstrap.NavSidebarItem, Roo.bootstrap.NavItem,  {
5068     
5069     badgeWeight : 'default',
5070     
5071     open: false,
5072     
5073     buttonView : false,
5074     
5075     buttonWeight : 'default',
5076     
5077     buttonSize : 'md',
5078     
5079     showArrow : true,
5080     
5081     getAutoCreate : function(){
5082         
5083         
5084         var a = {
5085                 tag: 'a',
5086                 href : this.href || '#',
5087                 cls: '',
5088                 html : '',
5089                 cn : []
5090         };
5091         
5092         if(this.buttonView){
5093             a = {
5094                 tag: 'button',
5095                 href : this.href || '#',
5096                 cls: 'btn btn-' + this.buttonWeight + ' btn-' + this.buttonSize + 'roo-button-dropdown-toggle',
5097                 html : this.html,
5098                 cn : []
5099             };
5100         }
5101         
5102         var cfg = {
5103             tag: 'li',
5104             cls: '',
5105             cn: [ a ]
5106         };
5107         
5108         if (this.active) {
5109             cfg.cls += ' active';
5110         }
5111         
5112         if (this.disabled) {
5113             cfg.cls += ' disabled';
5114         }
5115         if (this.open) {
5116             cfg.cls += ' open x-open';
5117         }
5118         // left icon..
5119         if (this.glyphicon || this.icon) {
5120             var c = this.glyphicon  ? ('glyphicon glyphicon-'+this.glyphicon)  : this.icon;
5121             a.cn.push({ tag : 'i', cls : c }) ;
5122         }
5123         
5124         if(!this.buttonView){
5125             var span = {
5126                 tag: 'span',
5127                 html : this.html || ''
5128             };
5129
5130             a.cn.push(span);
5131             
5132         }
5133         
5134         if (this.badge !== '') {
5135             a.cn.push({ tag: 'span',  cls : 'badge pull-right badge-' + this.badgeWeight, html: this.badge }); 
5136         }
5137         
5138         if (this.menu) {
5139             
5140             if(this.showArrow){
5141                 a.cn.push({ tag : 'i', cls : 'glyphicon glyphicon-chevron-down pull-right'});
5142             }
5143             
5144             a.cls += ' dropdown-toggle treeview' ;
5145         }
5146         
5147         return cfg;
5148     },
5149     
5150     initEvents : function()
5151     { 
5152         if (typeof (this.menu) != 'undefined') {
5153             this.menu.parentType = this.xtype;
5154             this.menu.triggerEl = this.el;
5155             this.menu = this.addxtype(Roo.apply({}, this.menu));
5156         }
5157         
5158         this.el.on('click', this.onClick, this);
5159         
5160         if(this.badge !== ''){
5161             this.badgeEl = this.el.select('.badge', true).first().setVisibilityMode(Roo.Element.DISPLAY);
5162         }
5163         
5164     },
5165     
5166     onClick : function(e)
5167     {
5168         if(this.disabled){
5169             e.preventDefault();
5170             return;
5171         }
5172         
5173         if(this.preventDefault){
5174             e.preventDefault();
5175         }
5176         
5177         this.fireEvent('click', this, e);
5178     },
5179     
5180     disable : function()
5181     {
5182         this.setDisabled(true);
5183     },
5184     
5185     enable : function()
5186     {
5187         this.setDisabled(false);
5188     },
5189     
5190     setDisabled : function(state)
5191     {
5192         if(this.disabled == state){
5193             return;
5194         }
5195         
5196         this.disabled = state;
5197         
5198         if (state) {
5199             this.el.addClass('disabled');
5200             return;
5201         }
5202         
5203         this.el.removeClass('disabled');
5204         
5205         return;
5206     },
5207     
5208     setActive : function(state)
5209     {
5210         if(this.active == state){
5211             return;
5212         }
5213         
5214         this.active = state;
5215         
5216         if (state) {
5217             this.el.addClass('active');
5218             return;
5219         }
5220         
5221         this.el.removeClass('active');
5222         
5223         return;
5224     },
5225     
5226     isActive: function () 
5227     {
5228         return this.active;
5229     },
5230     
5231     setBadge : function(str)
5232     {
5233         if(!this.badgeEl){
5234             return;
5235         }
5236         
5237         this.badgeEl.dom.innerHTML = str;
5238     }
5239     
5240    
5241      
5242  
5243 });
5244  
5245
5246  /*
5247  * - LGPL
5248  *
5249  * row
5250  * 
5251  */
5252
5253 /**
5254  * @class Roo.bootstrap.Row
5255  * @extends Roo.bootstrap.Component
5256  * Bootstrap Row class (contains columns...)
5257  * 
5258  * @constructor
5259  * Create a new Row
5260  * @param {Object} config The config object
5261  */
5262
5263 Roo.bootstrap.Row = function(config){
5264     Roo.bootstrap.Row.superclass.constructor.call(this, config);
5265 };
5266
5267 Roo.extend(Roo.bootstrap.Row, Roo.bootstrap.Component,  {
5268     
5269     getAutoCreate : function(){
5270        return {
5271             cls: 'row clearfix'
5272        };
5273     }
5274     
5275     
5276 });
5277
5278  
5279
5280  /*
5281  * - LGPL
5282  *
5283  * element
5284  * 
5285  */
5286
5287 /**
5288  * @class Roo.bootstrap.Element
5289  * @extends Roo.bootstrap.Component
5290  * Bootstrap Element class
5291  * @cfg {String} html contents of the element
5292  * @cfg {String} tag tag of the element
5293  * @cfg {String} cls class of the element
5294  * @cfg {Boolean} preventDefault (true|false) default false
5295  * @cfg {Boolean} clickable (true|false) default false
5296  * 
5297  * @constructor
5298  * Create a new Element
5299  * @param {Object} config The config object
5300  */
5301
5302 Roo.bootstrap.Element = function(config){
5303     Roo.bootstrap.Element.superclass.constructor.call(this, config);
5304     
5305     this.addEvents({
5306         // raw events
5307         /**
5308          * @event click
5309          * When a element is chick
5310          * @param {Roo.bootstrap.Element} this
5311          * @param {Roo.EventObject} e
5312          */
5313         "click" : true
5314     });
5315 };
5316
5317 Roo.extend(Roo.bootstrap.Element, Roo.bootstrap.Component,  {
5318     
5319     tag: 'div',
5320     cls: '',
5321     html: '',
5322     preventDefault: false, 
5323     clickable: false,
5324     
5325     getAutoCreate : function(){
5326         
5327         var cfg = {
5328             tag: this.tag,
5329             // cls: this.cls, double assign in parent class Component.js :: onRender
5330             html: this.html
5331         };
5332         
5333         return cfg;
5334     },
5335     
5336     initEvents: function() 
5337     {
5338         Roo.bootstrap.Element.superclass.initEvents.call(this);
5339         
5340         if(this.clickable){
5341             this.el.on('click', this.onClick, this);
5342         }
5343         
5344     },
5345     
5346     onClick : function(e)
5347     {
5348         if(this.preventDefault){
5349             e.preventDefault();
5350         }
5351         
5352         this.fireEvent('click', this, e);
5353     },
5354     
5355     getValue : function()
5356     {
5357         return this.el.dom.innerHTML;
5358     },
5359     
5360     setValue : function(value)
5361     {
5362         this.el.dom.innerHTML = value;
5363     }
5364    
5365 });
5366
5367  
5368
5369  /*
5370  * - LGPL
5371  *
5372  * pagination
5373  * 
5374  */
5375
5376 /**
5377  * @class Roo.bootstrap.Pagination
5378  * @extends Roo.bootstrap.Component
5379  * Bootstrap Pagination class
5380  * @cfg {String} size xs | sm | md | lg
5381  * @cfg {Boolean} inverse false | true
5382  * 
5383  * @constructor
5384  * Create a new Pagination
5385  * @param {Object} config The config object
5386  */
5387
5388 Roo.bootstrap.Pagination = function(config){
5389     Roo.bootstrap.Pagination.superclass.constructor.call(this, config);
5390 };
5391
5392 Roo.extend(Roo.bootstrap.Pagination, Roo.bootstrap.Component,  {
5393     
5394     cls: false,
5395     size: false,
5396     inverse: false,
5397     
5398     getAutoCreate : function(){
5399         var cfg = {
5400             tag: 'ul',
5401                 cls: 'pagination'
5402         };
5403         if (this.inverse) {
5404             cfg.cls += ' inverse';
5405         }
5406         if (this.html) {
5407             cfg.html=this.html;
5408         }
5409         if (this.cls) {
5410             cfg.cls += " " + this.cls;
5411         }
5412         return cfg;
5413     }
5414    
5415 });
5416
5417  
5418
5419  /*
5420  * - LGPL
5421  *
5422  * Pagination item
5423  * 
5424  */
5425
5426
5427 /**
5428  * @class Roo.bootstrap.PaginationItem
5429  * @extends Roo.bootstrap.Component
5430  * Bootstrap PaginationItem class
5431  * @cfg {String} html text
5432  * @cfg {String} href the link
5433  * @cfg {Boolean} preventDefault (true | false) default true
5434  * @cfg {Boolean} active (true | false) default false
5435  * @cfg {Boolean} disabled default false
5436  * 
5437  * 
5438  * @constructor
5439  * Create a new PaginationItem
5440  * @param {Object} config The config object
5441  */
5442
5443
5444 Roo.bootstrap.PaginationItem = function(config){
5445     Roo.bootstrap.PaginationItem.superclass.constructor.call(this, config);
5446     this.addEvents({
5447         // raw events
5448         /**
5449          * @event click
5450          * The raw click event for the entire grid.
5451          * @param {Roo.EventObject} e
5452          */
5453         "click" : true
5454     });
5455 };
5456
5457 Roo.extend(Roo.bootstrap.PaginationItem, Roo.bootstrap.Component,  {
5458     
5459     href : false,
5460     html : false,
5461     preventDefault: true,
5462     active : false,
5463     cls : false,
5464     disabled: false,
5465     
5466     getAutoCreate : function(){
5467         var cfg= {
5468             tag: 'li',
5469             cn: [
5470                 {
5471                     tag : 'a',
5472                     href : this.href ? this.href : '#',
5473                     html : this.html ? this.html : ''
5474                 }
5475             ]
5476         };
5477         
5478         if(this.cls){
5479             cfg.cls = this.cls;
5480         }
5481         
5482         if(this.disabled){
5483             cfg.cls = typeof(cfg.cls) !== 'undefined' ? cfg.cls + ' disabled' : 'disabled';
5484         }
5485         
5486         if(this.active){
5487             cfg.cls = typeof(cfg.cls) !== 'undefined' ? cfg.cls + ' active' : 'active';
5488         }
5489         
5490         return cfg;
5491     },
5492     
5493     initEvents: function() {
5494         
5495         this.el.on('click', this.onClick, this);
5496         
5497     },
5498     onClick : function(e)
5499     {
5500         Roo.log('PaginationItem on click ');
5501         if(this.preventDefault){
5502             e.preventDefault();
5503         }
5504         
5505         if(this.disabled){
5506             return;
5507         }
5508         
5509         this.fireEvent('click', this, e);
5510     }
5511    
5512 });
5513
5514  
5515
5516  /*
5517  * - LGPL
5518  *
5519  * slider
5520  * 
5521  */
5522
5523
5524 /**
5525  * @class Roo.bootstrap.Slider
5526  * @extends Roo.bootstrap.Component
5527  * Bootstrap Slider class
5528  *    
5529  * @constructor
5530  * Create a new Slider
5531  * @param {Object} config The config object
5532  */
5533
5534 Roo.bootstrap.Slider = function(config){
5535     Roo.bootstrap.Slider.superclass.constructor.call(this, config);
5536 };
5537
5538 Roo.extend(Roo.bootstrap.Slider, Roo.bootstrap.Component,  {
5539     
5540     getAutoCreate : function(){
5541         
5542         var cfg = {
5543             tag: 'div',
5544             cls: 'slider slider-sample1 vertical-handler ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all',
5545             cn: [
5546                 {
5547                     tag: 'a',
5548                     cls: 'ui-slider-handle ui-state-default ui-corner-all'
5549                 }
5550             ]
5551         };
5552         
5553         return cfg;
5554     }
5555    
5556 });
5557
5558  /*
5559  * Based on:
5560  * Ext JS Library 1.1.1
5561  * Copyright(c) 2006-2007, Ext JS, LLC.
5562  *
5563  * Originally Released Under LGPL - original licence link has changed is not relivant.
5564  *
5565  * Fork - LGPL
5566  * <script type="text/javascript">
5567  */
5568  
5569
5570 /**
5571  * @class Roo.grid.ColumnModel
5572  * @extends Roo.util.Observable
5573  * This is the default implementation of a ColumnModel used by the Grid. It defines
5574  * the columns in the grid.
5575  * <br>Usage:<br>
5576  <pre><code>
5577  var colModel = new Roo.grid.ColumnModel([
5578         {header: "Ticker", width: 60, sortable: true, locked: true},
5579         {header: "Company Name", width: 150, sortable: true},
5580         {header: "Market Cap.", width: 100, sortable: true},
5581         {header: "$ Sales", width: 100, sortable: true, renderer: money},
5582         {header: "Employees", width: 100, sortable: true, resizable: false}
5583  ]);
5584  </code></pre>
5585  * <p>
5586  
5587  * The config options listed for this class are options which may appear in each
5588  * individual column definition.
5589  * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
5590  * @constructor
5591  * @param {Object} config An Array of column config objects. See this class's
5592  * config objects for details.
5593 */
5594 Roo.grid.ColumnModel = function(config){
5595         /**
5596      * The config passed into the constructor
5597      */
5598     this.config = config;
5599     this.lookup = {};
5600
5601     // if no id, create one
5602     // if the column does not have a dataIndex mapping,
5603     // map it to the order it is in the config
5604     for(var i = 0, len = config.length; i < len; i++){
5605         var c = config[i];
5606         if(typeof c.dataIndex == "undefined"){
5607             c.dataIndex = i;
5608         }
5609         if(typeof c.renderer == "string"){
5610             c.renderer = Roo.util.Format[c.renderer];
5611         }
5612         if(typeof c.id == "undefined"){
5613             c.id = Roo.id();
5614         }
5615         if(c.editor && c.editor.xtype){
5616             c.editor  = Roo.factory(c.editor, Roo.grid);
5617         }
5618         if(c.editor && c.editor.isFormField){
5619             c.editor = new Roo.grid.GridEditor(c.editor);
5620         }
5621         this.lookup[c.id] = c;
5622     }
5623
5624     /**
5625      * The width of columns which have no width specified (defaults to 100)
5626      * @type Number
5627      */
5628     this.defaultWidth = 100;
5629
5630     /**
5631      * Default sortable of columns which have no sortable specified (defaults to false)
5632      * @type Boolean
5633      */
5634     this.defaultSortable = false;
5635
5636     this.addEvents({
5637         /**
5638              * @event widthchange
5639              * Fires when the width of a column changes.
5640              * @param {ColumnModel} this
5641              * @param {Number} columnIndex The column index
5642              * @param {Number} newWidth The new width
5643              */
5644             "widthchange": true,
5645         /**
5646              * @event headerchange
5647              * Fires when the text of a header changes.
5648              * @param {ColumnModel} this
5649              * @param {Number} columnIndex The column index
5650              * @param {Number} newText The new header text
5651              */
5652             "headerchange": true,
5653         /**
5654              * @event hiddenchange
5655              * Fires when a column is hidden or "unhidden".
5656              * @param {ColumnModel} this
5657              * @param {Number} columnIndex The column index
5658              * @param {Boolean} hidden true if hidden, false otherwise
5659              */
5660             "hiddenchange": true,
5661             /**
5662          * @event columnmoved
5663          * Fires when a column is moved.
5664          * @param {ColumnModel} this
5665          * @param {Number} oldIndex
5666          * @param {Number} newIndex
5667          */
5668         "columnmoved" : true,
5669         /**
5670          * @event columlockchange
5671          * Fires when a column's locked state is changed
5672          * @param {ColumnModel} this
5673          * @param {Number} colIndex
5674          * @param {Boolean} locked true if locked
5675          */
5676         "columnlockchange" : true
5677     });
5678     Roo.grid.ColumnModel.superclass.constructor.call(this);
5679 };
5680 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
5681     /**
5682      * @cfg {String} header The header text to display in the Grid view.
5683      */
5684     /**
5685      * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
5686      * {@link Roo.data.Record} definition from which to draw the column's value. If not
5687      * specified, the column's index is used as an index into the Record's data Array.
5688      */
5689     /**
5690      * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
5691      * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
5692      */
5693     /**
5694      * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
5695      * Defaults to the value of the {@link #defaultSortable} property.
5696      * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
5697      */
5698     /**
5699      * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid.  Defaults to false.
5700      */
5701     /**
5702      * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed.  Defaults to false.
5703      */
5704     /**
5705      * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
5706      */
5707     /**
5708      * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
5709      */
5710     /**
5711      * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
5712      * given the cell's data value. See {@link #setRenderer}. If not specified, the
5713      * default renderer returns the escaped data value. If an object is returned (bootstrap only)
5714      * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
5715      */
5716        /**
5717      * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor 
5718      */
5719     /**
5720      * @cfg {String} align (Optional) Set the CSS text-align property of the column.  Defaults to undefined.
5721      */
5722     /**
5723      * @cfg {String} valign (Optional) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc).  Defaults to undefined.
5724      */
5725     /**
5726      * @cfg {String} cursor (Optional)
5727      */
5728     /**
5729      * @cfg {String} tooltip (Optional)
5730      */
5731     /**
5732      * @cfg {Number} xs (Optional)
5733      */
5734     /**
5735      * @cfg {Number} sm (Optional)
5736      */
5737     /**
5738      * @cfg {Number} md (Optional)
5739      */
5740     /**
5741      * @cfg {Number} lg (Optional)
5742      */
5743     /**
5744      * Returns the id of the column at the specified index.
5745      * @param {Number} index The column index
5746      * @return {String} the id
5747      */
5748     getColumnId : function(index){
5749         return this.config[index].id;
5750     },
5751
5752     /**
5753      * Returns the column for a specified id.
5754      * @param {String} id The column id
5755      * @return {Object} the column
5756      */
5757     getColumnById : function(id){
5758         return this.lookup[id];
5759     },
5760
5761     
5762     /**
5763      * Returns the column for a specified dataIndex.
5764      * @param {String} dataIndex The column dataIndex
5765      * @return {Object|Boolean} the column or false if not found
5766      */
5767     getColumnByDataIndex: function(dataIndex){
5768         var index = this.findColumnIndex(dataIndex);
5769         return index > -1 ? this.config[index] : false;
5770     },
5771     
5772     /**
5773      * Returns the index for a specified column id.
5774      * @param {String} id The column id
5775      * @return {Number} the index, or -1 if not found
5776      */
5777     getIndexById : function(id){
5778         for(var i = 0, len = this.config.length; i < len; i++){
5779             if(this.config[i].id == id){
5780                 return i;
5781             }
5782         }
5783         return -1;
5784     },
5785     
5786     /**
5787      * Returns the index for a specified column dataIndex.
5788      * @param {String} dataIndex The column dataIndex
5789      * @return {Number} the index, or -1 if not found
5790      */
5791     
5792     findColumnIndex : function(dataIndex){
5793         for(var i = 0, len = this.config.length; i < len; i++){
5794             if(this.config[i].dataIndex == dataIndex){
5795                 return i;
5796             }
5797         }
5798         return -1;
5799     },
5800     
5801     
5802     moveColumn : function(oldIndex, newIndex){
5803         var c = this.config[oldIndex];
5804         this.config.splice(oldIndex, 1);
5805         this.config.splice(newIndex, 0, c);
5806         this.dataMap = null;
5807         this.fireEvent("columnmoved", this, oldIndex, newIndex);
5808     },
5809
5810     isLocked : function(colIndex){
5811         return this.config[colIndex].locked === true;
5812     },
5813
5814     setLocked : function(colIndex, value, suppressEvent){
5815         if(this.isLocked(colIndex) == value){
5816             return;
5817         }
5818         this.config[colIndex].locked = value;
5819         if(!suppressEvent){
5820             this.fireEvent("columnlockchange", this, colIndex, value);
5821         }
5822     },
5823
5824     getTotalLockedWidth : function(){
5825         var totalWidth = 0;
5826         for(var i = 0; i < this.config.length; i++){
5827             if(this.isLocked(i) && !this.isHidden(i)){
5828                 this.totalWidth += this.getColumnWidth(i);
5829             }
5830         }
5831         return totalWidth;
5832     },
5833
5834     getLockedCount : function(){
5835         for(var i = 0, len = this.config.length; i < len; i++){
5836             if(!this.isLocked(i)){
5837                 return i;
5838             }
5839         }
5840         
5841         return this.config.length;
5842     },
5843
5844     /**
5845      * Returns the number of columns.
5846      * @return {Number}
5847      */
5848     getColumnCount : function(visibleOnly){
5849         if(visibleOnly === true){
5850             var c = 0;
5851             for(var i = 0, len = this.config.length; i < len; i++){
5852                 if(!this.isHidden(i)){
5853                     c++;
5854                 }
5855             }
5856             return c;
5857         }
5858         return this.config.length;
5859     },
5860
5861     /**
5862      * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
5863      * @param {Function} fn
5864      * @param {Object} scope (optional)
5865      * @return {Array} result
5866      */
5867     getColumnsBy : function(fn, scope){
5868         var r = [];
5869         for(var i = 0, len = this.config.length; i < len; i++){
5870             var c = this.config[i];
5871             if(fn.call(scope||this, c, i) === true){
5872                 r[r.length] = c;
5873             }
5874         }
5875         return r;
5876     },
5877
5878     /**
5879      * Returns true if the specified column is sortable.
5880      * @param {Number} col The column index
5881      * @return {Boolean}
5882      */
5883     isSortable : function(col){
5884         if(typeof this.config[col].sortable == "undefined"){
5885             return this.defaultSortable;
5886         }
5887         return this.config[col].sortable;
5888     },
5889
5890     /**
5891      * Returns the rendering (formatting) function defined for the column.
5892      * @param {Number} col The column index.
5893      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
5894      */
5895     getRenderer : function(col){
5896         if(!this.config[col].renderer){
5897             return Roo.grid.ColumnModel.defaultRenderer;
5898         }
5899         return this.config[col].renderer;
5900     },
5901
5902     /**
5903      * Sets the rendering (formatting) function for a column.
5904      * @param {Number} col The column index
5905      * @param {Function} fn The function to use to process the cell's raw data
5906      * to return HTML markup for the grid view. The render function is called with
5907      * the following parameters:<ul>
5908      * <li>Data value.</li>
5909      * <li>Cell metadata. An object in which you may set the following attributes:<ul>
5910      * <li>css A CSS style string to apply to the table cell.</li>
5911      * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
5912      * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
5913      * <li>Row index</li>
5914      * <li>Column index</li>
5915      * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
5916      */
5917     setRenderer : function(col, fn){
5918         this.config[col].renderer = fn;
5919     },
5920
5921     /**
5922      * Returns the width for the specified column.
5923      * @param {Number} col The column index
5924      * @return {Number}
5925      */
5926     getColumnWidth : function(col){
5927         return this.config[col].width * 1 || this.defaultWidth;
5928     },
5929
5930     /**
5931      * Sets the width for a column.
5932      * @param {Number} col The column index
5933      * @param {Number} width The new width
5934      */
5935     setColumnWidth : function(col, width, suppressEvent){
5936         this.config[col].width = width;
5937         this.totalWidth = null;
5938         if(!suppressEvent){
5939              this.fireEvent("widthchange", this, col, width);
5940         }
5941     },
5942
5943     /**
5944      * Returns the total width of all columns.
5945      * @param {Boolean} includeHidden True to include hidden column widths
5946      * @return {Number}
5947      */
5948     getTotalWidth : function(includeHidden){
5949         if(!this.totalWidth){
5950             this.totalWidth = 0;
5951             for(var i = 0, len = this.config.length; i < len; i++){
5952                 if(includeHidden || !this.isHidden(i)){
5953                     this.totalWidth += this.getColumnWidth(i);
5954                 }
5955             }
5956         }
5957         return this.totalWidth;
5958     },
5959
5960     /**
5961      * Returns the header for the specified column.
5962      * @param {Number} col The column index
5963      * @return {String}
5964      */
5965     getColumnHeader : function(col){
5966         return this.config[col].header;
5967     },
5968
5969     /**
5970      * Sets the header for a column.
5971      * @param {Number} col The column index
5972      * @param {String} header The new header
5973      */
5974     setColumnHeader : function(col, header){
5975         this.config[col].header = header;
5976         this.fireEvent("headerchange", this, col, header);
5977     },
5978
5979     /**
5980      * Returns the tooltip for the specified column.
5981      * @param {Number} col The column index
5982      * @return {String}
5983      */
5984     getColumnTooltip : function(col){
5985             return this.config[col].tooltip;
5986     },
5987     /**
5988      * Sets the tooltip for a column.
5989      * @param {Number} col The column index
5990      * @param {String} tooltip The new tooltip
5991      */
5992     setColumnTooltip : function(col, tooltip){
5993             this.config[col].tooltip = tooltip;
5994     },
5995
5996     /**
5997      * Returns the dataIndex for the specified column.
5998      * @param {Number} col The column index
5999      * @return {Number}
6000      */
6001     getDataIndex : function(col){
6002         return this.config[col].dataIndex;
6003     },
6004
6005     /**
6006      * Sets the dataIndex for a column.
6007      * @param {Number} col The column index
6008      * @param {Number} dataIndex The new dataIndex
6009      */
6010     setDataIndex : function(col, dataIndex){
6011         this.config[col].dataIndex = dataIndex;
6012     },
6013
6014     
6015     
6016     /**
6017      * Returns true if the cell is editable.
6018      * @param {Number} colIndex The column index
6019      * @param {Number} rowIndex The row index - this is nto actually used..?
6020      * @return {Boolean}
6021      */
6022     isCellEditable : function(colIndex, rowIndex){
6023         return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
6024     },
6025
6026     /**
6027      * Returns the editor defined for the cell/column.
6028      * return false or null to disable editing.
6029      * @param {Number} colIndex The column index
6030      * @param {Number} rowIndex The row index
6031      * @return {Object}
6032      */
6033     getCellEditor : function(colIndex, rowIndex){
6034         return this.config[colIndex].editor;
6035     },
6036
6037     /**
6038      * Sets if a column is editable.
6039      * @param {Number} col The column index
6040      * @param {Boolean} editable True if the column is editable
6041      */
6042     setEditable : function(col, editable){
6043         this.config[col].editable = editable;
6044     },
6045
6046
6047     /**
6048      * Returns true if the column is hidden.
6049      * @param {Number} colIndex The column index
6050      * @return {Boolean}
6051      */
6052     isHidden : function(colIndex){
6053         return this.config[colIndex].hidden;
6054     },
6055
6056
6057     /**
6058      * Returns true if the column width cannot be changed
6059      */
6060     isFixed : function(colIndex){
6061         return this.config[colIndex].fixed;
6062     },
6063
6064     /**
6065      * Returns true if the column can be resized
6066      * @return {Boolean}
6067      */
6068     isResizable : function(colIndex){
6069         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
6070     },
6071     /**
6072      * Sets if a column is hidden.
6073      * @param {Number} colIndex The column index
6074      * @param {Boolean} hidden True if the column is hidden
6075      */
6076     setHidden : function(colIndex, hidden){
6077         this.config[colIndex].hidden = hidden;
6078         this.totalWidth = null;
6079         this.fireEvent("hiddenchange", this, colIndex, hidden);
6080     },
6081
6082     /**
6083      * Sets the editor for a column.
6084      * @param {Number} col The column index
6085      * @param {Object} editor The editor object
6086      */
6087     setEditor : function(col, editor){
6088         this.config[col].editor = editor;
6089     }
6090 });
6091
6092 Roo.grid.ColumnModel.defaultRenderer = function(value)
6093 {
6094     if(typeof value == "object") {
6095         return value;
6096     }
6097         if(typeof value == "string" && value.length < 1){
6098             return "&#160;";
6099         }
6100     
6101         return String.format("{0}", value);
6102 };
6103
6104 // Alias for backwards compatibility
6105 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
6106 /*
6107  * Based on:
6108  * Ext JS Library 1.1.1
6109  * Copyright(c) 2006-2007, Ext JS, LLC.
6110  *
6111  * Originally Released Under LGPL - original licence link has changed is not relivant.
6112  *
6113  * Fork - LGPL
6114  * <script type="text/javascript">
6115  */
6116  
6117 /**
6118  * @class Roo.LoadMask
6119  * A simple utility class for generically masking elements while loading data.  If the element being masked has
6120  * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
6121  * process and the mask element will be cached for reuse.  For all other elements, this mask will replace the
6122  * element's UpdateManager load indicator and will be destroyed after the initial load.
6123  * @constructor
6124  * Create a new LoadMask
6125  * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
6126  * @param {Object} config The config object
6127  */
6128 Roo.LoadMask = function(el, config){
6129     this.el = Roo.get(el);
6130     Roo.apply(this, config);
6131     if(this.store){
6132         this.store.on('beforeload', this.onBeforeLoad, this);
6133         this.store.on('load', this.onLoad, this);
6134         this.store.on('loadexception', this.onLoadException, this);
6135         this.removeMask = false;
6136     }else{
6137         var um = this.el.getUpdateManager();
6138         um.showLoadIndicator = false; // disable the default indicator
6139         um.on('beforeupdate', this.onBeforeLoad, this);
6140         um.on('update', this.onLoad, this);
6141         um.on('failure', this.onLoad, this);
6142         this.removeMask = true;
6143     }
6144 };
6145
6146 Roo.LoadMask.prototype = {
6147     /**
6148      * @cfg {Boolean} removeMask
6149      * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
6150      * False to persist the mask element reference for multiple uses (e.g., for paged data widgets).  Defaults to false.
6151      */
6152     /**
6153      * @cfg {String} msg
6154      * The text to display in a centered loading message box (defaults to 'Loading...')
6155      */
6156     msg : 'Loading...',
6157     /**
6158      * @cfg {String} msgCls
6159      * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
6160      */
6161     msgCls : 'x-mask-loading',
6162
6163     /**
6164      * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
6165      * @type Boolean
6166      */
6167     disabled: false,
6168
6169     /**
6170      * Disables the mask to prevent it from being displayed
6171      */
6172     disable : function(){
6173        this.disabled = true;
6174     },
6175
6176     /**
6177      * Enables the mask so that it can be displayed
6178      */
6179     enable : function(){
6180         this.disabled = false;
6181     },
6182     
6183     onLoadException : function()
6184     {
6185         Roo.log(arguments);
6186         
6187         if (typeof(arguments[3]) != 'undefined') {
6188             Roo.MessageBox.alert("Error loading",arguments[3]);
6189         } 
6190         /*
6191         try {
6192             if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
6193                 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
6194             }   
6195         } catch(e) {
6196             
6197         }
6198         */
6199     
6200         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
6201     },
6202     // private
6203     onLoad : function()
6204     {
6205         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
6206     },
6207
6208     // private
6209     onBeforeLoad : function(){
6210         if(!this.disabled){
6211             (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
6212         }
6213     },
6214
6215     // private
6216     destroy : function(){
6217         if(this.store){
6218             this.store.un('beforeload', this.onBeforeLoad, this);
6219             this.store.un('load', this.onLoad, this);
6220             this.store.un('loadexception', this.onLoadException, this);
6221         }else{
6222             var um = this.el.getUpdateManager();
6223             um.un('beforeupdate', this.onBeforeLoad, this);
6224             um.un('update', this.onLoad, this);
6225             um.un('failure', this.onLoad, this);
6226         }
6227     }
6228 };/*
6229  * - LGPL
6230  *
6231  * table
6232  * 
6233  */
6234
6235 /**
6236  * @class Roo.bootstrap.Table
6237  * @extends Roo.bootstrap.Component
6238  * Bootstrap Table class
6239  * @cfg {String} cls table class
6240  * @cfg {String} align (left|center|right) Specifies the alignment of a table according to surrounding text
6241  * @cfg {String} bgcolor Specifies the background color for a table
6242  * @cfg {Number} border Specifies whether the table cells should have borders or not
6243  * @cfg {Number} cellpadding Specifies the space between the cell wall and the cell content
6244  * @cfg {Number} cellspacing Specifies the space between cells
6245  * @cfg {String} frame Specifies which parts of the outside borders that should be visible
6246  * @cfg {String} rules Specifies which parts of the inside borders that should be visible
6247  * @cfg {String} sortable Specifies that the table should be sortable
6248  * @cfg {String} summary Specifies a summary of the content of a table
6249  * @cfg {Number} width Specifies the width of a table
6250  * @cfg {String} layout table layout (auto | fixed | initial | inherit)
6251  * 
6252  * @cfg {boolean} striped Should the rows be alternative striped
6253  * @cfg {boolean} bordered Add borders to the table
6254  * @cfg {boolean} hover Add hover highlighting
6255  * @cfg {boolean} condensed Format condensed
6256  * @cfg {boolean} responsive Format condensed
6257  * @cfg {Boolean} loadMask (true|false) default false
6258  * @cfg {Boolean} footerShow (true|false) generate tfoot, default true
6259  * @cfg {Boolean} headerShow (true|false) generate thead, default true
6260  * @cfg {Boolean} rowSelection (true|false) default false
6261  * @cfg {Boolean} cellSelection (true|false) default false
6262  * @cfg {Boolean} scrollBody (true|false) default false - body scrolled / fixed header
6263  * @cfg {Roo.bootstrap.PagingToolbar} footer  a paging toolbar
6264  * @cfg {Boolean} lazyLoad  auto load data while scrolling to the end (default false)
6265  * @cfg {Boolean} auto_hide_footer  auto hide footer if only one page (default false)
6266  
6267  * 
6268  * @constructor
6269  * Create a new Table
6270  * @param {Object} config The config object
6271  */
6272
6273 Roo.bootstrap.Table = function(config){
6274     Roo.bootstrap.Table.superclass.constructor.call(this, config);
6275     
6276   
6277     
6278     // BC...
6279     this.rowSelection = (typeof(config.rowSelection) != 'undefined') ? config.rowSelection : this.rowSelection;
6280     this.cellSelection = (typeof(config.cellSelection) != 'undefined') ? config.cellSelection : this.cellSelection;
6281     this.headerShow = (typeof(config.thead) != 'undefined') ? config.thead : this.headerShow;
6282     this.footerShow = (typeof(config.tfoot) != 'undefined') ? config.tfoot : this.footerShow;
6283     
6284     this.sm = this.sm || {xtype: 'RowSelectionModel'};
6285     if (this.sm) {
6286         this.sm.grid = this;
6287         this.selModel = Roo.factory(this.sm, Roo.bootstrap.Table);
6288         this.sm = this.selModel;
6289         this.sm.xmodule = this.xmodule || false;
6290     }
6291     
6292     if (this.cm && typeof(this.cm.config) == 'undefined') {
6293         this.colModel = new Roo.grid.ColumnModel(this.cm);
6294         this.cm = this.colModel;
6295         this.cm.xmodule = this.xmodule || false;
6296     }
6297     if (this.store) {
6298         this.store= Roo.factory(this.store, Roo.data);
6299         this.ds = this.store;
6300         this.ds.xmodule = this.xmodule || false;
6301          
6302     }
6303     if (this.footer && this.store) {
6304         this.footer.dataSource = this.ds;
6305         this.footer = Roo.factory(this.footer);
6306     }
6307     
6308     /** @private */
6309     this.addEvents({
6310         /**
6311          * @event cellclick
6312          * Fires when a cell is clicked
6313          * @param {Roo.bootstrap.Table} this
6314          * @param {Roo.Element} el
6315          * @param {Number} rowIndex
6316          * @param {Number} columnIndex
6317          * @param {Roo.EventObject} e
6318          */
6319         "cellclick" : true,
6320         /**
6321          * @event celldblclick
6322          * Fires when a cell is double clicked
6323          * @param {Roo.bootstrap.Table} this
6324          * @param {Roo.Element} el
6325          * @param {Number} rowIndex
6326          * @param {Number} columnIndex
6327          * @param {Roo.EventObject} e
6328          */
6329         "celldblclick" : true,
6330         /**
6331          * @event rowclick
6332          * Fires when a row is clicked
6333          * @param {Roo.bootstrap.Table} this
6334          * @param {Roo.Element} el
6335          * @param {Number} rowIndex
6336          * @param {Roo.EventObject} e
6337          */
6338         "rowclick" : true,
6339         /**
6340          * @event rowdblclick
6341          * Fires when a row is double clicked
6342          * @param {Roo.bootstrap.Table} this
6343          * @param {Roo.Element} el
6344          * @param {Number} rowIndex
6345          * @param {Roo.EventObject} e
6346          */
6347         "rowdblclick" : true,
6348         /**
6349          * @event mouseover
6350          * Fires when a mouseover occur
6351          * @param {Roo.bootstrap.Table} this
6352          * @param {Roo.Element} el
6353          * @param {Number} rowIndex
6354          * @param {Number} columnIndex
6355          * @param {Roo.EventObject} e
6356          */
6357         "mouseover" : true,
6358         /**
6359          * @event mouseout
6360          * Fires when a mouseout occur
6361          * @param {Roo.bootstrap.Table} this
6362          * @param {Roo.Element} el
6363          * @param {Number} rowIndex
6364          * @param {Number} columnIndex
6365          * @param {Roo.EventObject} e
6366          */
6367         "mouseout" : true,
6368         /**
6369          * @event rowclass
6370          * Fires when a row is rendered, so you can change add a style to it.
6371          * @param {Roo.bootstrap.Table} this
6372          * @param {Object} rowcfg   contains record  rowIndex colIndex and rowClass - set rowClass to add a style.
6373          */
6374         'rowclass' : true,
6375           /**
6376          * @event rowsrendered
6377          * Fires when all the  rows have been rendered
6378          * @param {Roo.bootstrap.Table} this
6379          */
6380         'rowsrendered' : true,
6381         /**
6382          * @event contextmenu
6383          * The raw contextmenu event for the entire grid.
6384          * @param {Roo.EventObject} e
6385          */
6386         "contextmenu" : true,
6387         /**
6388          * @event rowcontextmenu
6389          * Fires when a row is right clicked
6390          * @param {Roo.bootstrap.Table} this
6391          * @param {Number} rowIndex
6392          * @param {Roo.EventObject} e
6393          */
6394         "rowcontextmenu" : true,
6395         /**
6396          * @event cellcontextmenu
6397          * Fires when a cell is right clicked
6398          * @param {Roo.bootstrap.Table} this
6399          * @param {Number} rowIndex
6400          * @param {Number} cellIndex
6401          * @param {Roo.EventObject} e
6402          */
6403          "cellcontextmenu" : true,
6404          /**
6405          * @event headercontextmenu
6406          * Fires when a header is right clicked
6407          * @param {Roo.bootstrap.Table} this
6408          * @param {Number} columnIndex
6409          * @param {Roo.EventObject} e
6410          */
6411         "headercontextmenu" : true
6412     });
6413 };
6414
6415 Roo.extend(Roo.bootstrap.Table, Roo.bootstrap.Component,  {
6416     
6417     cls: false,
6418     align: false,
6419     bgcolor: false,
6420     border: false,
6421     cellpadding: false,
6422     cellspacing: false,
6423     frame: false,
6424     rules: false,
6425     sortable: false,
6426     summary: false,
6427     width: false,
6428     striped : false,
6429     scrollBody : false,
6430     bordered: false,
6431     hover:  false,
6432     condensed : false,
6433     responsive : false,
6434     sm : false,
6435     cm : false,
6436     store : false,
6437     loadMask : false,
6438     footerShow : true,
6439     headerShow : true,
6440   
6441     rowSelection : false,
6442     cellSelection : false,
6443     layout : false,
6444     
6445     // Roo.Element - the tbody
6446     mainBody: false,
6447     // Roo.Element - thead element
6448     mainHead: false,
6449     
6450     container: false, // used by gridpanel...
6451     
6452     lazyLoad : false,
6453     
6454     CSS : Roo.util.CSS,
6455     
6456     auto_hide_footer : false,
6457     
6458     getAutoCreate : function()
6459     {
6460         var cfg = Roo.apply({}, Roo.bootstrap.Table.superclass.getAutoCreate.call(this));
6461         
6462         cfg = {
6463             tag: 'table',
6464             cls : 'table',
6465             cn : []
6466         };
6467         if (this.scrollBody) {
6468             cfg.cls += ' table-body-fixed';
6469         }    
6470         if (this.striped) {
6471             cfg.cls += ' table-striped';
6472         }
6473         
6474         if (this.hover) {
6475             cfg.cls += ' table-hover';
6476         }
6477         if (this.bordered) {
6478             cfg.cls += ' table-bordered';
6479         }
6480         if (this.condensed) {
6481             cfg.cls += ' table-condensed';
6482         }
6483         if (this.responsive) {
6484             cfg.cls += ' table-responsive';
6485         }
6486         
6487         if (this.cls) {
6488             cfg.cls+=  ' ' +this.cls;
6489         }
6490         
6491         // this lot should be simplifed...
6492         var _t = this;
6493         var cp = [
6494             'align',
6495             'bgcolor',
6496             'border',
6497             'cellpadding',
6498             'cellspacing',
6499             'frame',
6500             'rules',
6501             'sortable',
6502             'summary',
6503             'width'
6504         ].forEach(function(k) {
6505             if (_t[k]) {
6506                 cfg[k] = _t[k];
6507             }
6508         });
6509         
6510         
6511         if (this.layout) {
6512             cfg.style = (typeof(cfg.style) == 'undefined') ? ('table-layout:' + this.layout + ';') : (cfg.style + ('table-layout:' + this.layout + ';'));
6513         }
6514         
6515         if(this.store || this.cm){
6516             if(this.headerShow){
6517                 cfg.cn.push(this.renderHeader());
6518             }
6519             
6520             cfg.cn.push(this.renderBody());
6521             
6522             if(this.footerShow){
6523                 cfg.cn.push(this.renderFooter());
6524             }
6525             // where does this come from?
6526             //cfg.cls+=  ' TableGrid';
6527         }
6528         
6529         return { cn : [ cfg ] };
6530     },
6531     
6532     initEvents : function()
6533     {   
6534         if(!this.store || !this.cm){
6535             return;
6536         }
6537         if (this.selModel) {
6538             this.selModel.initEvents();
6539         }
6540         
6541         
6542         //Roo.log('initEvents with ds!!!!');
6543         
6544         this.mainBody = this.el.select('tbody', true).first();
6545         this.mainHead = this.el.select('thead', true).first();
6546         this.mainFoot = this.el.select('tfoot', true).first();
6547         
6548         
6549         
6550         var _this = this;
6551         
6552         Roo.each(this.el.select('thead th.sortable', true).elements, function(e){
6553             e.on('click', _this.sort, _this);
6554         });
6555         
6556         this.mainBody.on("click", this.onClick, this);
6557         this.mainBody.on("dblclick", this.onDblClick, this);
6558         
6559         // why is this done????? = it breaks dialogs??
6560         //this.parent().el.setStyle('position', 'relative');
6561         
6562         
6563         if (this.footer) {
6564             this.footer.parentId = this.id;
6565             this.footer.onRender(this.el.select('tfoot tr td').first(), null);
6566             
6567             if(this.lazyLoad){
6568                 this.el.select('tfoot tr td').first().addClass('hide');
6569             }
6570         } 
6571         
6572         if(this.loadMask) {
6573             this.maskEl = new Roo.LoadMask(this.el, { store : this.ds, msgCls: 'roo-el-mask-msg' });
6574         }
6575         
6576         this.store.on('load', this.onLoad, this);
6577         this.store.on('beforeload', this.onBeforeLoad, this);
6578         this.store.on('update', this.onUpdate, this);
6579         this.store.on('add', this.onAdd, this);
6580         this.store.on("clear", this.clear, this);
6581         
6582         this.el.on("contextmenu", this.onContextMenu, this);
6583         
6584         this.mainBody.on('scroll', this.onBodyScroll, this);
6585         
6586         this.cm.on("headerchange", this.onHeaderChange, this);
6587         
6588         this.cm.on("hiddenchange", this.onHiddenChange, this, arguments);
6589         
6590     },
6591     
6592     onContextMenu : function(e, t)
6593     {
6594         this.processEvent("contextmenu", e);
6595     },
6596     
6597     processEvent : function(name, e)
6598     {
6599         if (name != 'touchstart' ) {
6600             this.fireEvent(name, e);    
6601         }
6602         
6603         var t = e.getTarget();
6604         
6605         var cell = Roo.get(t);
6606         
6607         if(!cell){
6608             return;
6609         }
6610         
6611         if(cell.findParent('tfoot', false, true)){
6612             return;
6613         }
6614         
6615         if(cell.findParent('thead', false, true)){
6616             
6617             if(e.getTarget().nodeName.toLowerCase() != 'th'){
6618                 cell = Roo.get(t).findParent('th', false, true);
6619                 if (!cell) {
6620                     Roo.log("failed to find th in thead?");
6621                     Roo.log(e.getTarget());
6622                     return;
6623                 }
6624             }
6625             
6626             var cellIndex = cell.dom.cellIndex;
6627             
6628             var ename = name == 'touchstart' ? 'click' : name;
6629             this.fireEvent("header" + ename, this, cellIndex, e);
6630             
6631             return;
6632         }
6633         
6634         if(e.getTarget().nodeName.toLowerCase() != 'td'){
6635             cell = Roo.get(t).findParent('td', false, true);
6636             if (!cell) {
6637                 Roo.log("failed to find th in tbody?");
6638                 Roo.log(e.getTarget());
6639                 return;
6640             }
6641         }
6642         
6643         var row = cell.findParent('tr', false, true);
6644         var cellIndex = cell.dom.cellIndex;
6645         var rowIndex = row.dom.rowIndex - 1;
6646         
6647         if(row !== false){
6648             
6649             this.fireEvent("row" + name, this, rowIndex, e);
6650             
6651             if(cell !== false){
6652             
6653                 this.fireEvent("cell" + name, this, rowIndex, cellIndex, e);
6654             }
6655         }
6656         
6657     },
6658     
6659     onMouseover : function(e, el)
6660     {
6661         var cell = Roo.get(el);
6662         
6663         if(!cell){
6664             return;
6665         }
6666         
6667         if(e.getTarget().nodeName.toLowerCase() != 'td'){
6668             cell = cell.findParent('td', false, true);
6669         }
6670         
6671         var row = cell.findParent('tr', false, true);
6672         var cellIndex = cell.dom.cellIndex;
6673         var rowIndex = row.dom.rowIndex - 1; // start from 0
6674         
6675         this.fireEvent('mouseover', this, cell, rowIndex, cellIndex, e);
6676         
6677     },
6678     
6679     onMouseout : function(e, el)
6680     {
6681         var cell = Roo.get(el);
6682         
6683         if(!cell){
6684             return;
6685         }
6686         
6687         if(e.getTarget().nodeName.toLowerCase() != 'td'){
6688             cell = cell.findParent('td', false, true);
6689         }
6690         
6691         var row = cell.findParent('tr', false, true);
6692         var cellIndex = cell.dom.cellIndex;
6693         var rowIndex = row.dom.rowIndex - 1; // start from 0
6694         
6695         this.fireEvent('mouseout', this, cell, rowIndex, cellIndex, e);
6696         
6697     },
6698     
6699     onClick : function(e, el)
6700     {
6701         var cell = Roo.get(el);
6702         
6703         if(!cell || (!this.cellSelection && !this.rowSelection)){
6704             return;
6705         }
6706         
6707         if(e.getTarget().nodeName.toLowerCase() != 'td'){
6708             cell = cell.findParent('td', false, true);
6709         }
6710         
6711         if(!cell || typeof(cell) == 'undefined'){
6712             return;
6713         }
6714         
6715         var row = cell.findParent('tr', false, true);
6716         
6717         if(!row || typeof(row) == 'undefined'){
6718             return;
6719         }
6720         
6721         var cellIndex = cell.dom.cellIndex;
6722         var rowIndex = this.getRowIndex(row);
6723         
6724         // why??? - should these not be based on SelectionModel?
6725         if(this.cellSelection){
6726             this.fireEvent('cellclick', this, cell, rowIndex, cellIndex, e);
6727         }
6728         
6729         if(this.rowSelection){
6730             this.fireEvent('rowclick', this, row, rowIndex, e);
6731         }
6732         
6733         
6734     },
6735         
6736     onDblClick : function(e,el)
6737     {
6738         var cell = Roo.get(el);
6739         
6740         if(!cell || (!this.cellSelection && !this.rowSelection)){
6741             return;
6742         }
6743         
6744         if(e.getTarget().nodeName.toLowerCase() != 'td'){
6745             cell = cell.findParent('td', false, true);
6746         }
6747         
6748         if(!cell || typeof(cell) == 'undefined'){
6749             return;
6750         }
6751         
6752         var row = cell.findParent('tr', false, true);
6753         
6754         if(!row || typeof(row) == 'undefined'){
6755             return;
6756         }
6757         
6758         var cellIndex = cell.dom.cellIndex;
6759         var rowIndex = this.getRowIndex(row);
6760         
6761         if(this.cellSelection){
6762             this.fireEvent('celldblclick', this, cell, rowIndex, cellIndex, e);
6763         }
6764         
6765         if(this.rowSelection){
6766             this.fireEvent('rowdblclick', this, row, rowIndex, e);
6767         }
6768     },
6769     
6770     sort : function(e,el)
6771     {
6772         var col = Roo.get(el);
6773         
6774         if(!col.hasClass('sortable')){
6775             return;
6776         }
6777         
6778         var sort = col.attr('sort');
6779         var dir = 'ASC';
6780         
6781         if(col.select('i', true).first().hasClass('glyphicon-arrow-up')){
6782             dir = 'DESC';
6783         }
6784         
6785         this.store.sortInfo = {field : sort, direction : dir};
6786         
6787         if (this.footer) {
6788             Roo.log("calling footer first");
6789             this.footer.onClick('first');
6790         } else {
6791         
6792             this.store.load({ params : { start : 0 } });
6793         }
6794     },
6795     
6796     renderHeader : function()
6797     {
6798         var header = {
6799             tag: 'thead',
6800             cn : []
6801         };
6802         
6803         var cm = this.cm;
6804         this.totalWidth = 0;
6805         
6806         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
6807             
6808             var config = cm.config[i];
6809             
6810             var c = {
6811                 tag: 'th',
6812                 cls : 'x-hcol-' + i,
6813                 style : '',
6814                 html: cm.getColumnHeader(i)
6815             };
6816             
6817             var hh = '';
6818             
6819             if(typeof(config.sortable) != 'undefined' && config.sortable){
6820                 c.cls = 'sortable';
6821                 c.html = '<i class="glyphicon"></i>' + c.html;
6822             }
6823             
6824             // could use BS4 hidden-..-down 
6825             
6826             if(typeof(config.lgHeader) != 'undefined'){
6827                 hh += '<span class="hidden-xs hidden-sm hidden-md ">' + config.lgHeader + '</span>';
6828             }
6829             
6830             if(typeof(config.mdHeader) != 'undefined'){
6831                 hh += '<span class="hidden-xs hidden-sm hidden-lg">' + config.mdHeader + '</span>';
6832             }
6833             
6834             if(typeof(config.smHeader) != 'undefined'){
6835                 hh += '<span class="hidden-xs hidden-md hidden-lg">' + config.smHeader + '</span>';
6836             }
6837             
6838             if(typeof(config.xsHeader) != 'undefined'){
6839                 hh += '<span class="hidden-sm hidden-md hidden-lg">' + config.xsHeader + '</span>';
6840             }
6841             
6842             if(hh.length){
6843                 c.html = hh;
6844             }
6845             
6846             if(typeof(config.tooltip) != 'undefined'){
6847                 c.tooltip = config.tooltip;
6848             }
6849             
6850             if(typeof(config.colspan) != 'undefined'){
6851                 c.colspan = config.colspan;
6852             }
6853             
6854             if(typeof(config.hidden) != 'undefined' && config.hidden){
6855                 c.style += ' display:none;';
6856             }
6857             
6858             if(typeof(config.dataIndex) != 'undefined'){
6859                 c.sort = config.dataIndex;
6860             }
6861             
6862            
6863             
6864             if(typeof(config.align) != 'undefined' && config.align.length){
6865                 c.style += ' text-align:' + config.align + ';';
6866             }
6867             
6868             if(typeof(config.width) != 'undefined'){
6869                 c.style += ' width:' + config.width + 'px;';
6870                 this.totalWidth += config.width;
6871             } else {
6872                 this.totalWidth += 100; // assume minimum of 100 per column?
6873             }
6874             
6875             if(typeof(config.cls) != 'undefined'){
6876                 c.cls = (typeof(c.cls) == 'undefined') ? config.cls : (c.cls + ' ' + config.cls);
6877             }
6878             
6879             ['xs','sm','md','lg'].map(function(size){
6880                 
6881                 if(typeof(config[size]) == 'undefined'){
6882                     return;
6883                 }
6884                  
6885                 if (!config[size]) { // 0 = hidden
6886                     // BS 4 '0' is treated as hide that column and below.
6887                     c.cls += ' hidden-' + size + ' hidden' + size + '-down';
6888                     return;
6889                 }
6890                 
6891                 c.cls += ' col-' + size + '-' + config[size] + (
6892                     size == 'xs' ? (' col-' + config[size] ) : '' // bs4 col-{num} replaces col-xs
6893                 );
6894                 
6895                 
6896             });
6897             
6898             header.cn.push(c)
6899         }
6900         
6901         return header;
6902     },
6903     
6904     renderBody : function()
6905     {
6906         var body = {
6907             tag: 'tbody',
6908             cn : [
6909                 {
6910                     tag: 'tr',
6911                     cn : [
6912                         {
6913                             tag : 'td',
6914                             colspan :  this.cm.getColumnCount()
6915                         }
6916                     ]
6917                 }
6918             ]
6919         };
6920         
6921         return body;
6922     },
6923     
6924     renderFooter : function()
6925     {
6926         var footer = {
6927             tag: 'tfoot',
6928             cn : [
6929                 {
6930                     tag: 'tr',
6931                     cn : [
6932                         {
6933                             tag : 'td',
6934                             colspan :  this.cm.getColumnCount()
6935                         }
6936                     ]
6937                 }
6938             ]
6939         };
6940         
6941         return footer;
6942     },
6943     
6944     
6945     
6946     onLoad : function()
6947     {
6948 //        Roo.log('ds onload');
6949         this.clear();
6950         
6951         var _this = this;
6952         var cm = this.cm;
6953         var ds = this.store;
6954         
6955         Roo.each(this.el.select('thead th.sortable', true).elements, function(e){
6956             e.select('i', true).removeClass(['glyphicon-arrow-up', 'glyphicon-arrow-down']);
6957             if (_this.store.sortInfo) {
6958                     
6959                 if(e.hasClass('sortable') && e.attr('sort') == _this.store.sortInfo.field && _this.store.sortInfo.direction.toUpperCase() == 'ASC'){
6960                     e.select('i', true).addClass(['glyphicon-arrow-up']);
6961                 }
6962                 
6963                 if(e.hasClass('sortable') && e.attr('sort') == _this.store.sortInfo.field && _this.store.sortInfo.direction.toUpperCase() == 'DESC'){
6964                     e.select('i', true).addClass(['glyphicon-arrow-down']);
6965                 }
6966             }
6967         });
6968         
6969         var tbody =  this.mainBody;
6970               
6971         if(ds.getCount() > 0){
6972             ds.data.each(function(d,rowIndex){
6973                 var row =  this.renderRow(cm, ds, rowIndex);
6974                 
6975                 tbody.createChild(row);
6976                 
6977                 var _this = this;
6978                 
6979                 if(row.cellObjects.length){
6980                     Roo.each(row.cellObjects, function(r){
6981                         _this.renderCellObject(r);
6982                     })
6983                 }
6984                 
6985             }, this);
6986         }
6987         
6988         var tfoot = this.el.select('tfoot', true).first();
6989         
6990         if(this.footerShow && this.auto_hide_footer && this.mainFoot){
6991             
6992             this.mainFoot.setVisibilityMode(Roo.Element.DISPLAY).hide();
6993             
6994             var total = this.ds.getTotalCount();
6995             
6996             if(this.footer.pageSize < total){
6997                 this.mainFoot.show();
6998             }
6999         }
7000         
7001         Roo.each(this.el.select('tbody td', true).elements, function(e){
7002             e.on('mouseover', _this.onMouseover, _this);
7003         });
7004         
7005         Roo.each(this.el.select('tbody td', true).elements, function(e){
7006             e.on('mouseout', _this.onMouseout, _this);
7007         });
7008         this.fireEvent('rowsrendered', this);
7009         
7010         this.autoSize();
7011     },
7012     
7013     
7014     onUpdate : function(ds,record)
7015     {
7016         this.refreshRow(record);
7017         this.autoSize();
7018     },
7019     
7020     onRemove : function(ds, record, index, isUpdate){
7021         if(isUpdate !== true){
7022             this.fireEvent("beforerowremoved", this, index, record);
7023         }
7024         var bt = this.mainBody.dom;
7025         
7026         var rows = this.el.select('tbody > tr', true).elements;
7027         
7028         if(typeof(rows[index]) != 'undefined'){
7029             bt.removeChild(rows[index].dom);
7030         }
7031         
7032 //        if(bt.rows[index]){
7033 //            bt.removeChild(bt.rows[index]);
7034 //        }
7035         
7036         if(isUpdate !== true){
7037             //this.stripeRows(index);
7038             //this.syncRowHeights(index, index);
7039             //this.layout();
7040             this.fireEvent("rowremoved", this, index, record);
7041         }
7042     },
7043     
7044     onAdd : function(ds, records, rowIndex)
7045     {
7046         //Roo.log('on Add called');
7047         // - note this does not handle multiple adding very well..
7048         var bt = this.mainBody.dom;
7049         for (var i =0 ; i < records.length;i++) {
7050             //Roo.log('call insert row Add called on ' + rowIndex + ':' + i);
7051             //Roo.log(records[i]);
7052             //Roo.log(this.store.getAt(rowIndex+i));
7053             this.insertRow(this.store, rowIndex + i, false);
7054             return;
7055         }
7056         
7057     },
7058     
7059     
7060     refreshRow : function(record){
7061         var ds = this.store, index;
7062         if(typeof record == 'number'){
7063             index = record;
7064             record = ds.getAt(index);
7065         }else{
7066             index = ds.indexOf(record);
7067         }
7068         this.insertRow(ds, index, true);
7069         this.autoSize();
7070         this.onRemove(ds, record, index+1, true);
7071         this.autoSize();
7072         //this.syncRowHeights(index, index);
7073         //this.layout();
7074         this.fireEvent("rowupdated", this, index, record);
7075     },
7076     
7077     insertRow : function(dm, rowIndex, isUpdate){
7078         
7079         if(!isUpdate){
7080             this.fireEvent("beforerowsinserted", this, rowIndex);
7081         }
7082             //var s = this.getScrollState();
7083         var row = this.renderRow(this.cm, this.store, rowIndex);
7084         // insert before rowIndex..
7085         var e = this.mainBody.createChild(row,this.getRowDom(rowIndex));
7086         
7087         var _this = this;
7088                 
7089         if(row.cellObjects.length){
7090             Roo.each(row.cellObjects, function(r){
7091                 _this.renderCellObject(r);
7092             })
7093         }
7094             
7095         if(!isUpdate){
7096             this.fireEvent("rowsinserted", this, rowIndex);
7097             //this.syncRowHeights(firstRow, lastRow);
7098             //this.stripeRows(firstRow);
7099             //this.layout();
7100         }
7101         
7102     },
7103     
7104     
7105     getRowDom : function(rowIndex)
7106     {
7107         var rows = this.el.select('tbody > tr', true).elements;
7108         
7109         return (typeof(rows[rowIndex]) == 'undefined') ? false : rows[rowIndex];
7110         
7111     },
7112     // returns the object tree for a tr..
7113   
7114     
7115     renderRow : function(cm, ds, rowIndex) 
7116     {
7117         var d = ds.getAt(rowIndex);
7118         
7119         var row = {
7120             tag : 'tr',
7121             cls : 'x-row-' + rowIndex,
7122             cn : []
7123         };
7124             
7125         var cellObjects = [];
7126         
7127         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
7128             var config = cm.config[i];
7129             
7130             var renderer = cm.getRenderer(i);
7131             var value = '';
7132             var id = false;
7133             
7134             if(typeof(renderer) !== 'undefined'){
7135                 value = renderer(d.data[cm.getDataIndex(i)], false, d);
7136             }
7137             // if object are returned, then they are expected to be Roo.bootstrap.Component instances
7138             // and are rendered into the cells after the row is rendered - using the id for the element.
7139             
7140             if(typeof(value) === 'object'){
7141                 id = Roo.id();
7142                 cellObjects.push({
7143                     container : id,
7144                     cfg : value 
7145                 })
7146             }
7147             
7148             var rowcfg = {
7149                 record: d,
7150                 rowIndex : rowIndex,
7151                 colIndex : i,
7152                 rowClass : ''
7153             };
7154
7155             this.fireEvent('rowclass', this, rowcfg);
7156             
7157             var td = {
7158                 tag: 'td',
7159                 cls : rowcfg.rowClass + ' x-col-' + i,
7160                 style: '',
7161                 html: (typeof(value) === 'object') ? '' : value
7162             };
7163             
7164             if (id) {
7165                 td.id = id;
7166             }
7167             
7168             if(typeof(config.colspan) != 'undefined'){
7169                 td.colspan = config.colspan;
7170             }
7171             
7172             if(typeof(config.hidden) != 'undefined' && config.hidden){
7173                 td.style += ' display:none;';
7174             }
7175             
7176             if(typeof(config.align) != 'undefined' && config.align.length){
7177                 td.style += ' text-align:' + config.align + ';';
7178             }
7179             if(typeof(config.valign) != 'undefined' && config.valign.length){
7180                 td.style += ' vertical-align:' + config.valign + ';';
7181             }
7182             
7183             if(typeof(config.width) != 'undefined'){
7184                 td.style += ' width:' +  config.width + 'px;';
7185             }
7186             
7187             if(typeof(config.cursor) != 'undefined'){
7188                 td.style += ' cursor:' +  config.cursor + ';';
7189             }
7190             
7191             if(typeof(config.cls) != 'undefined'){
7192                 td.cls = (typeof(td.cls) == 'undefined') ? config.cls : (td.cls + ' ' + config.cls);
7193             }
7194             
7195             ['xs','sm','md','lg'].map(function(size){
7196                 
7197                 if(typeof(config[size]) == 'undefined'){
7198                     return;
7199                 }
7200                 
7201                 
7202                   
7203                 if (!config[size]) { // 0 = hidden
7204                     // BS 4 '0' is treated as hide that column and below.
7205                     td.cls += ' hidden-' + size + ' hidden' + size + '-down';
7206                     return;
7207                 }
7208                 
7209                 td.cls += ' col-' + size + '-' + config[size] + (
7210                     size == 'xs' ? (' col-' +   config[size] ) : '' // bs4 col-{num} replaces col-xs
7211                 );
7212                  
7213
7214             });
7215             
7216             row.cn.push(td);
7217            
7218         }
7219         
7220         row.cellObjects = cellObjects;
7221         
7222         return row;
7223           
7224     },
7225     
7226     
7227     
7228     onBeforeLoad : function()
7229     {
7230         
7231     },
7232      /**
7233      * Remove all rows
7234      */
7235     clear : function()
7236     {
7237         this.el.select('tbody', true).first().dom.innerHTML = '';
7238     },
7239     /**
7240      * Show or hide a row.
7241      * @param {Number} rowIndex to show or hide
7242      * @param {Boolean} state hide
7243      */
7244     setRowVisibility : function(rowIndex, state)
7245     {
7246         var bt = this.mainBody.dom;
7247         
7248         var rows = this.el.select('tbody > tr', true).elements;
7249         
7250         if(typeof(rows[rowIndex]) == 'undefined'){
7251             return;
7252         }
7253         rows[rowIndex].dom.style.display = state ? '' : 'none';
7254     },
7255     
7256     
7257     getSelectionModel : function(){
7258         if(!this.selModel){
7259             this.selModel = new Roo.bootstrap.Table.RowSelectionModel({grid: this});
7260         }
7261         return this.selModel;
7262     },
7263     /*
7264      * Render the Roo.bootstrap object from renderder
7265      */
7266     renderCellObject : function(r)
7267     {
7268         var _this = this;
7269         
7270         r.cfg.parentId = (typeof(r.container) == 'string') ? r.container : r.container.id;
7271         
7272         var t = r.cfg.render(r.container);
7273         
7274         if(r.cfg.cn){
7275             Roo.each(r.cfg.cn, function(c){
7276                 var child = {
7277                     container: t.getChildContainer(),
7278                     cfg: c
7279                 };
7280                 _this.renderCellObject(child);
7281             })
7282         }
7283     },
7284     
7285     getRowIndex : function(row)
7286     {
7287         var rowIndex = -1;
7288         
7289         Roo.each(this.el.select('tbody > tr', true).elements, function(el, index){
7290             if(el != row){
7291                 return;
7292             }
7293             
7294             rowIndex = index;
7295         });
7296         
7297         return rowIndex;
7298     },
7299      /**
7300      * Returns the grid's underlying element = used by panel.Grid
7301      * @return {Element} The element
7302      */
7303     getGridEl : function(){
7304         return this.el;
7305     },
7306      /**
7307      * Forces a resize - used by panel.Grid
7308      * @return {Element} The element
7309      */
7310     autoSize : function()
7311     {
7312         //var ctr = Roo.get(this.container.dom.parentElement);
7313         var ctr = Roo.get(this.el.dom);
7314         
7315         var thd = this.getGridEl().select('thead',true).first();
7316         var tbd = this.getGridEl().select('tbody', true).first();
7317         var tfd = this.getGridEl().select('tfoot', true).first();
7318         
7319         var cw = ctr.getWidth();
7320         
7321         if (tbd) {
7322             
7323             tbd.setSize(ctr.getWidth(),
7324                         ctr.getHeight() - ((thd ? thd.getHeight() : 0) + (tfd ? tfd.getHeight() : 0))
7325             );
7326             var barsize = (tbd.dom.offsetWidth - tbd.dom.clientWidth);
7327             cw -= barsize;
7328         }
7329         cw = Math.max(cw, this.totalWidth);
7330         this.getGridEl().select('tr',true).setWidth(cw);
7331         // resize 'expandable coloumn?
7332         
7333         return; // we doe not have a view in this design..
7334         
7335     },
7336     onBodyScroll: function()
7337     {
7338         //Roo.log("body scrolled');" + this.mainBody.dom.scrollLeft);
7339         if(this.mainHead){
7340             this.mainHead.setStyle({
7341                 'position' : 'relative',
7342                 'left': (-1* this.mainBody.dom.scrollLeft) + 'px'
7343             });
7344         }
7345         
7346         if(this.lazyLoad){
7347             
7348             var scrollHeight = this.mainBody.dom.scrollHeight;
7349             
7350             var scrollTop = Math.ceil(this.mainBody.getScroll().top);
7351             
7352             var height = this.mainBody.getHeight();
7353             
7354             if(scrollHeight - height == scrollTop) {
7355                 
7356                 var total = this.ds.getTotalCount();
7357                 
7358                 if(this.footer.cursor + this.footer.pageSize < total){
7359                     
7360                     this.footer.ds.load({
7361                         params : {
7362                             start : this.footer.cursor + this.footer.pageSize,
7363                             limit : this.footer.pageSize
7364                         },
7365                         add : true
7366                     });
7367                 }
7368             }
7369             
7370         }
7371     },
7372     
7373     onHeaderChange : function()
7374     {
7375         var header = this.renderHeader();
7376         var table = this.el.select('table', true).first();
7377         
7378         this.mainHead.remove();
7379         this.mainHead = table.createChild(header, this.mainBody, false);
7380     },
7381     
7382     onHiddenChange : function(colModel, colIndex, hidden)
7383     {
7384         var thSelector = '#' + this.id + ' .x-hcol-' + colIndex;
7385         var tdSelector = '#' + this.id + ' .x-col-' + colIndex;
7386         
7387         this.CSS.updateRule(thSelector, "display", "");
7388         this.CSS.updateRule(tdSelector, "display", "");
7389         
7390         if(hidden){
7391             this.CSS.updateRule(thSelector, "display", "none");
7392             this.CSS.updateRule(tdSelector, "display", "none");
7393         }
7394         
7395         this.onHeaderChange();
7396         this.onLoad();
7397     },
7398     
7399     setColumnWidth: function(col_index, width)
7400     {
7401         // width = "md-2 xs-2..."
7402         if(!this.colModel.config[col_index]) {
7403             return;
7404         }
7405         
7406         var w = width.split(" ");
7407         
7408         var rows = this.el.dom.getElementsByClassName("x-col-"+col_index);
7409         
7410         var h_row = this.el.dom.getElementsByClassName("x-hcol-"+col_index);
7411         
7412         
7413         for(var j = 0; j < w.length; j++) {
7414             
7415             if(!w[j]) {
7416                 continue;
7417             }
7418             
7419             var size_cls = w[j].split("-");
7420             
7421             if(!Number.isInteger(size_cls[1] * 1)) {
7422                 continue;
7423             }
7424             
7425             if(!this.colModel.config[col_index][size_cls[0]]) {
7426                 continue;
7427             }
7428             
7429             if(!h_row[0].classList.contains("col-"+size_cls[0]+"-"+this.colModel.config[col_index][size_cls[0]])) {
7430                 continue;
7431             }
7432             
7433             h_row[0].classList.replace(
7434                 "col-"+size_cls[0]+"-"+this.colModel.config[col_index][size_cls[0]],
7435                 "col-"+size_cls[0]+"-"+size_cls[1]
7436             );
7437             
7438             for(var i = 0; i < rows.length; i++) {
7439                 
7440                 var size_cls = w[j].split("-");
7441                 
7442                 if(!Number.isInteger(size_cls[1] * 1)) {
7443                     continue;
7444                 }
7445                 
7446                 if(!this.colModel.config[col_index][size_cls[0]]) {
7447                     continue;
7448                 }
7449                 
7450                 if(!rows[i].classList.contains("col-"+size_cls[0]+"-"+this.colModel.config[col_index][size_cls[0]])) {
7451                     continue;
7452                 }
7453                 
7454                 rows[i].classList.replace(
7455                     "col-"+size_cls[0]+"-"+this.colModel.config[col_index][size_cls[0]],
7456                     "col-"+size_cls[0]+"-"+size_cls[1]
7457                 );
7458             }
7459             
7460             this.colModel.config[col_index][size_cls[0]] = size_cls[1];
7461         }
7462     }
7463 });
7464
7465  
7466
7467  /*
7468  * - LGPL
7469  *
7470  * table cell
7471  * 
7472  */
7473
7474 /**
7475  * @class Roo.bootstrap.TableCell
7476  * @extends Roo.bootstrap.Component
7477  * Bootstrap TableCell class
7478  * @cfg {String} html cell contain text
7479  * @cfg {String} cls cell class
7480  * @cfg {String} tag cell tag (td|th) default td
7481  * @cfg {String} abbr Specifies an abbreviated version of the content in a cell
7482  * @cfg {String} align Aligns the content in a cell
7483  * @cfg {String} axis Categorizes cells
7484  * @cfg {String} bgcolor Specifies the background color of a cell
7485  * @cfg {Number} charoff Sets the number of characters the content will be aligned from the character specified by the char attribute
7486  * @cfg {Number} colspan Specifies the number of columns a cell should span
7487  * @cfg {String} headers Specifies one or more header cells a cell is related to
7488  * @cfg {Number} height Sets the height of a cell
7489  * @cfg {String} nowrap Specifies that the content inside a cell should not wrap
7490  * @cfg {Number} rowspan Sets the number of rows a cell should span
7491  * @cfg {String} scope Defines a way to associate header cells and data cells in a table
7492  * @cfg {String} valign Vertical aligns the content in a cell
7493  * @cfg {Number} width Specifies the width of a cell
7494  * 
7495  * @constructor
7496  * Create a new TableCell
7497  * @param {Object} config The config object
7498  */
7499
7500 Roo.bootstrap.TableCell = function(config){
7501     Roo.bootstrap.TableCell.superclass.constructor.call(this, config);
7502 };
7503
7504 Roo.extend(Roo.bootstrap.TableCell, Roo.bootstrap.Component,  {
7505     
7506     html: false,
7507     cls: false,
7508     tag: false,
7509     abbr: false,
7510     align: false,
7511     axis: false,
7512     bgcolor: false,
7513     charoff: false,
7514     colspan: false,
7515     headers: false,
7516     height: false,
7517     nowrap: false,
7518     rowspan: false,
7519     scope: false,
7520     valign: false,
7521     width: false,
7522     
7523     
7524     getAutoCreate : function(){
7525         var cfg = Roo.apply({}, Roo.bootstrap.TableCell.superclass.getAutoCreate.call(this));
7526         
7527         cfg = {
7528             tag: 'td'
7529         };
7530         
7531         if(this.tag){
7532             cfg.tag = this.tag;
7533         }
7534         
7535         if (this.html) {
7536             cfg.html=this.html
7537         }
7538         if (this.cls) {
7539             cfg.cls=this.cls
7540         }
7541         if (this.abbr) {
7542             cfg.abbr=this.abbr
7543         }
7544         if (this.align) {
7545             cfg.align=this.align
7546         }
7547         if (this.axis) {
7548             cfg.axis=this.axis
7549         }
7550         if (this.bgcolor) {
7551             cfg.bgcolor=this.bgcolor
7552         }
7553         if (this.charoff) {
7554             cfg.charoff=this.charoff
7555         }
7556         if (this.colspan) {
7557             cfg.colspan=this.colspan
7558         }
7559         if (this.headers) {
7560             cfg.headers=this.headers
7561         }
7562         if (this.height) {
7563             cfg.height=this.height
7564         }
7565         if (this.nowrap) {
7566             cfg.nowrap=this.nowrap
7567         }
7568         if (this.rowspan) {
7569             cfg.rowspan=this.rowspan
7570         }
7571         if (this.scope) {
7572             cfg.scope=this.scope
7573         }
7574         if (this.valign) {
7575             cfg.valign=this.valign
7576         }
7577         if (this.width) {
7578             cfg.width=this.width
7579         }
7580         
7581         
7582         return cfg;
7583     }
7584    
7585 });
7586
7587  
7588
7589  /*
7590  * - LGPL
7591  *
7592  * table row
7593  * 
7594  */
7595
7596 /**
7597  * @class Roo.bootstrap.TableRow
7598  * @extends Roo.bootstrap.Component
7599  * Bootstrap TableRow class
7600  * @cfg {String} cls row class
7601  * @cfg {String} align Aligns the content in a table row
7602  * @cfg {String} bgcolor Specifies a background color for a table row
7603  * @cfg {Number} charoff Sets the number of characters the content will be aligned from the character specified by the char attribute
7604  * @cfg {String} valign Vertical aligns the content in a table row
7605  * 
7606  * @constructor
7607  * Create a new TableRow
7608  * @param {Object} config The config object
7609  */
7610
7611 Roo.bootstrap.TableRow = function(config){
7612     Roo.bootstrap.TableRow.superclass.constructor.call(this, config);
7613 };
7614
7615 Roo.extend(Roo.bootstrap.TableRow, Roo.bootstrap.Component,  {
7616     
7617     cls: false,
7618     align: false,
7619     bgcolor: false,
7620     charoff: false,
7621     valign: false,
7622     
7623     getAutoCreate : function(){
7624         var cfg = Roo.apply({}, Roo.bootstrap.TableRow.superclass.getAutoCreate.call(this));
7625         
7626         cfg = {
7627             tag: 'tr'
7628         };
7629             
7630         if(this.cls){
7631             cfg.cls = this.cls;
7632         }
7633         if(this.align){
7634             cfg.align = this.align;
7635         }
7636         if(this.bgcolor){
7637             cfg.bgcolor = this.bgcolor;
7638         }
7639         if(this.charoff){
7640             cfg.charoff = this.charoff;
7641         }
7642         if(this.valign){
7643             cfg.valign = this.valign;
7644         }
7645         
7646         return cfg;
7647     }
7648    
7649 });
7650
7651  
7652
7653  /*
7654  * - LGPL
7655  *
7656  * table body
7657  * 
7658  */
7659
7660 /**
7661  * @class Roo.bootstrap.TableBody
7662  * @extends Roo.bootstrap.Component
7663  * Bootstrap TableBody class
7664  * @cfg {String} cls element class
7665  * @cfg {String} tag element tag (thead|tbody|tfoot) default tbody
7666  * @cfg {String} align Aligns the content inside the element
7667  * @cfg {Number} charoff Sets the number of characters the content inside the element will be aligned from the character specified by the char attribute
7668  * @cfg {String} valign Vertical aligns the content inside the <tbody> element
7669  * 
7670  * @constructor
7671  * Create a new TableBody
7672  * @param {Object} config The config object
7673  */
7674
7675 Roo.bootstrap.TableBody = function(config){
7676     Roo.bootstrap.TableBody.superclass.constructor.call(this, config);
7677 };
7678
7679 Roo.extend(Roo.bootstrap.TableBody, Roo.bootstrap.Component,  {
7680     
7681     cls: false,
7682     tag: false,
7683     align: false,
7684     charoff: false,
7685     valign: false,
7686     
7687     getAutoCreate : function(){
7688         var cfg = Roo.apply({}, Roo.bootstrap.TableBody.superclass.getAutoCreate.call(this));
7689         
7690         cfg = {
7691             tag: 'tbody'
7692         };
7693             
7694         if (this.cls) {
7695             cfg.cls=this.cls
7696         }
7697         if(this.tag){
7698             cfg.tag = this.tag;
7699         }
7700         
7701         if(this.align){
7702             cfg.align = this.align;
7703         }
7704         if(this.charoff){
7705             cfg.charoff = this.charoff;
7706         }
7707         if(this.valign){
7708             cfg.valign = this.valign;
7709         }
7710         
7711         return cfg;
7712     }
7713     
7714     
7715 //    initEvents : function()
7716 //    {
7717 //        
7718 //        if(!this.store){
7719 //            return;
7720 //        }
7721 //        
7722 //        this.store = Roo.factory(this.store, Roo.data);
7723 //        this.store.on('load', this.onLoad, this);
7724 //        
7725 //        this.store.load();
7726 //        
7727 //    },
7728 //    
7729 //    onLoad: function () 
7730 //    {   
7731 //        this.fireEvent('load', this);
7732 //    }
7733 //    
7734 //   
7735 });
7736
7737  
7738
7739  /*
7740  * Based on:
7741  * Ext JS Library 1.1.1
7742  * Copyright(c) 2006-2007, Ext JS, LLC.
7743  *
7744  * Originally Released Under LGPL - original licence link has changed is not relivant.
7745  *
7746  * Fork - LGPL
7747  * <script type="text/javascript">
7748  */
7749
7750 // as we use this in bootstrap.
7751 Roo.namespace('Roo.form');
7752  /**
7753  * @class Roo.form.Action
7754  * Internal Class used to handle form actions
7755  * @constructor
7756  * @param {Roo.form.BasicForm} el The form element or its id
7757  * @param {Object} config Configuration options
7758  */
7759
7760  
7761  
7762 // define the action interface
7763 Roo.form.Action = function(form, options){
7764     this.form = form;
7765     this.options = options || {};
7766 };
7767 /**
7768  * Client Validation Failed
7769  * @const 
7770  */
7771 Roo.form.Action.CLIENT_INVALID = 'client';
7772 /**
7773  * Server Validation Failed
7774  * @const 
7775  */
7776 Roo.form.Action.SERVER_INVALID = 'server';
7777  /**
7778  * Connect to Server Failed
7779  * @const 
7780  */
7781 Roo.form.Action.CONNECT_FAILURE = 'connect';
7782 /**
7783  * Reading Data from Server Failed
7784  * @const 
7785  */
7786 Roo.form.Action.LOAD_FAILURE = 'load';
7787
7788 Roo.form.Action.prototype = {
7789     type : 'default',
7790     failureType : undefined,
7791     response : undefined,
7792     result : undefined,
7793
7794     // interface method
7795     run : function(options){
7796
7797     },
7798
7799     // interface method
7800     success : function(response){
7801
7802     },
7803
7804     // interface method
7805     handleResponse : function(response){
7806
7807     },
7808
7809     // default connection failure
7810     failure : function(response){
7811         
7812         this.response = response;
7813         this.failureType = Roo.form.Action.CONNECT_FAILURE;
7814         this.form.afterAction(this, false);
7815     },
7816
7817     processResponse : function(response){
7818         this.response = response;
7819         if(!response.responseText){
7820             return true;
7821         }
7822         this.result = this.handleResponse(response);
7823         return this.result;
7824     },
7825
7826     // utility functions used internally
7827     getUrl : function(appendParams){
7828         var url = this.options.url || this.form.url || this.form.el.dom.action;
7829         if(appendParams){
7830             var p = this.getParams();
7831             if(p){
7832                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
7833             }
7834         }
7835         return url;
7836     },
7837
7838     getMethod : function(){
7839         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
7840     },
7841
7842     getParams : function(){
7843         var bp = this.form.baseParams;
7844         var p = this.options.params;
7845         if(p){
7846             if(typeof p == "object"){
7847                 p = Roo.urlEncode(Roo.applyIf(p, bp));
7848             }else if(typeof p == 'string' && bp){
7849                 p += '&' + Roo.urlEncode(bp);
7850             }
7851         }else if(bp){
7852             p = Roo.urlEncode(bp);
7853         }
7854         return p;
7855     },
7856
7857     createCallback : function(){
7858         return {
7859             success: this.success,
7860             failure: this.failure,
7861             scope: this,
7862             timeout: (this.form.timeout*1000),
7863             upload: this.form.fileUpload ? this.success : undefined
7864         };
7865     }
7866 };
7867
7868 Roo.form.Action.Submit = function(form, options){
7869     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
7870 };
7871
7872 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
7873     type : 'submit',
7874
7875     haveProgress : false,
7876     uploadComplete : false,
7877     
7878     // uploadProgress indicator.
7879     uploadProgress : function()
7880     {
7881         if (!this.form.progressUrl) {
7882             return;
7883         }
7884         
7885         if (!this.haveProgress) {
7886             Roo.MessageBox.progress("Uploading", "Uploading");
7887         }
7888         if (this.uploadComplete) {
7889            Roo.MessageBox.hide();
7890            return;
7891         }
7892         
7893         this.haveProgress = true;
7894    
7895         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
7896         
7897         var c = new Roo.data.Connection();
7898         c.request({
7899             url : this.form.progressUrl,
7900             params: {
7901                 id : uid
7902             },
7903             method: 'GET',
7904             success : function(req){
7905                //console.log(data);
7906                 var rdata = false;
7907                 var edata;
7908                 try  {
7909                    rdata = Roo.decode(req.responseText)
7910                 } catch (e) {
7911                     Roo.log("Invalid data from server..");
7912                     Roo.log(edata);
7913                     return;
7914                 }
7915                 if (!rdata || !rdata.success) {
7916                     Roo.log(rdata);
7917                     Roo.MessageBox.alert(Roo.encode(rdata));
7918                     return;
7919                 }
7920                 var data = rdata.data;
7921                 
7922                 if (this.uploadComplete) {
7923                    Roo.MessageBox.hide();
7924                    return;
7925                 }
7926                    
7927                 if (data){
7928                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
7929                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
7930                     );
7931                 }
7932                 this.uploadProgress.defer(2000,this);
7933             },
7934        
7935             failure: function(data) {
7936                 Roo.log('progress url failed ');
7937                 Roo.log(data);
7938             },
7939             scope : this
7940         });
7941            
7942     },
7943     
7944     
7945     run : function()
7946     {
7947         // run get Values on the form, so it syncs any secondary forms.
7948         this.form.getValues();
7949         
7950         var o = this.options;
7951         var method = this.getMethod();
7952         var isPost = method == 'POST';
7953         if(o.clientValidation === false || this.form.isValid()){
7954             
7955             if (this.form.progressUrl) {
7956                 this.form.findField('UPLOAD_IDENTIFIER').setValue(
7957                     (new Date() * 1) + '' + Math.random());
7958                     
7959             } 
7960             
7961             
7962             Roo.Ajax.request(Roo.apply(this.createCallback(), {
7963                 form:this.form.el.dom,
7964                 url:this.getUrl(!isPost),
7965                 method: method,
7966                 params:isPost ? this.getParams() : null,
7967                 isUpload: this.form.fileUpload,
7968                 formData : this.form.formData
7969             }));
7970             
7971             this.uploadProgress();
7972
7973         }else if (o.clientValidation !== false){ // client validation failed
7974             this.failureType = Roo.form.Action.CLIENT_INVALID;
7975             this.form.afterAction(this, false);
7976         }
7977     },
7978
7979     success : function(response)
7980     {
7981         this.uploadComplete= true;
7982         if (this.haveProgress) {
7983             Roo.MessageBox.hide();
7984         }
7985         
7986         
7987         var result = this.processResponse(response);
7988         if(result === true || result.success){
7989             this.form.afterAction(this, true);
7990             return;
7991         }
7992         if(result.errors){
7993             this.form.markInvalid(result.errors);
7994             this.failureType = Roo.form.Action.SERVER_INVALID;
7995         }
7996         this.form.afterAction(this, false);
7997     },
7998     failure : function(response)
7999     {
8000         this.uploadComplete= true;
8001         if (this.haveProgress) {
8002             Roo.MessageBox.hide();
8003         }
8004         
8005         this.response = response;
8006         this.failureType = Roo.form.Action.CONNECT_FAILURE;
8007         this.form.afterAction(this, false);
8008     },
8009     
8010     handleResponse : function(response){
8011         if(this.form.errorReader){
8012             var rs = this.form.errorReader.read(response);
8013             var errors = [];
8014             if(rs.records){
8015                 for(var i = 0, len = rs.records.length; i < len; i++) {
8016                     var r = rs.records[i];
8017                     errors[i] = r.data;
8018                 }
8019             }
8020             if(errors.length < 1){
8021                 errors = null;
8022             }
8023             return {
8024                 success : rs.success,
8025                 errors : errors
8026             };
8027         }
8028         var ret = false;
8029         try {
8030             ret = Roo.decode(response.responseText);
8031         } catch (e) {
8032             ret = {
8033                 success: false,
8034                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
8035                 errors : []
8036             };
8037         }
8038         return ret;
8039         
8040     }
8041 });
8042
8043
8044 Roo.form.Action.Load = function(form, options){
8045     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
8046     this.reader = this.form.reader;
8047 };
8048
8049 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
8050     type : 'load',
8051
8052     run : function(){
8053         
8054         Roo.Ajax.request(Roo.apply(
8055                 this.createCallback(), {
8056                     method:this.getMethod(),
8057                     url:this.getUrl(false),
8058                     params:this.getParams()
8059         }));
8060     },
8061
8062     success : function(response){
8063         
8064         var result = this.processResponse(response);
8065         if(result === true || !result.success || !result.data){
8066             this.failureType = Roo.form.Action.LOAD_FAILURE;
8067             this.form.afterAction(this, false);
8068             return;
8069         }
8070         this.form.clearInvalid();
8071         this.form.setValues(result.data);
8072         this.form.afterAction(this, true);
8073     },
8074
8075     handleResponse : function(response){
8076         if(this.form.reader){
8077             var rs = this.form.reader.read(response);
8078             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
8079             return {
8080                 success : rs.success,
8081                 data : data
8082             };
8083         }
8084         return Roo.decode(response.responseText);
8085     }
8086 });
8087
8088 Roo.form.Action.ACTION_TYPES = {
8089     'load' : Roo.form.Action.Load,
8090     'submit' : Roo.form.Action.Submit
8091 };/*
8092  * - LGPL
8093  *
8094  * form
8095  *
8096  */
8097
8098 /**
8099  * @class Roo.bootstrap.Form
8100  * @extends Roo.bootstrap.Component
8101  * Bootstrap Form class
8102  * @cfg {String} method  GET | POST (default POST)
8103  * @cfg {String} labelAlign top | left (default top)
8104  * @cfg {String} align left  | right - for navbars
8105  * @cfg {Boolean} loadMask load mask when submit (default true)
8106
8107  *
8108  * @constructor
8109  * Create a new Form
8110  * @param {Object} config The config object
8111  */
8112
8113
8114 Roo.bootstrap.Form = function(config){
8115     
8116     Roo.bootstrap.Form.superclass.constructor.call(this, config);
8117     
8118     Roo.bootstrap.Form.popover.apply();
8119     
8120     this.addEvents({
8121         /**
8122          * @event clientvalidation
8123          * If the monitorValid config option is true, this event fires repetitively to notify of valid state
8124          * @param {Form} this
8125          * @param {Boolean} valid true if the form has passed client-side validation
8126          */
8127         clientvalidation: true,
8128         /**
8129          * @event beforeaction
8130          * Fires before any action is performed. Return false to cancel the action.
8131          * @param {Form} this
8132          * @param {Action} action The action to be performed
8133          */
8134         beforeaction: true,
8135         /**
8136          * @event actionfailed
8137          * Fires when an action fails.
8138          * @param {Form} this
8139          * @param {Action} action The action that failed
8140          */
8141         actionfailed : true,
8142         /**
8143          * @event actioncomplete
8144          * Fires when an action is completed.
8145          * @param {Form} this
8146          * @param {Action} action The action that completed
8147          */
8148         actioncomplete : true
8149     });
8150 };
8151
8152 Roo.extend(Roo.bootstrap.Form, Roo.bootstrap.Component,  {
8153
8154      /**
8155      * @cfg {String} method
8156      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
8157      */
8158     method : 'POST',
8159     /**
8160      * @cfg {String} url
8161      * The URL to use for form actions if one isn't supplied in the action options.
8162      */
8163     /**
8164      * @cfg {Boolean} fileUpload
8165      * Set to true if this form is a file upload.
8166      */
8167
8168     /**
8169      * @cfg {Object} baseParams
8170      * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
8171      */
8172
8173     /**
8174      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
8175      */
8176     timeout: 30,
8177     /**
8178      * @cfg {Sting} align (left|right) for navbar forms
8179      */
8180     align : 'left',
8181
8182     // private
8183     activeAction : null,
8184
8185     /**
8186      * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
8187      * element by passing it or its id or mask the form itself by passing in true.
8188      * @type Mixed
8189      */
8190     waitMsgTarget : false,
8191
8192     loadMask : true,
8193     
8194     /**
8195      * @cfg {Boolean} errorMask (true|false) default false
8196      */
8197     errorMask : false,
8198     
8199     /**
8200      * @cfg {Number} maskOffset Default 100
8201      */
8202     maskOffset : 100,
8203     
8204     /**
8205      * @cfg {Boolean} maskBody
8206      */
8207     maskBody : false,
8208
8209     getAutoCreate : function(){
8210
8211         var cfg = {
8212             tag: 'form',
8213             method : this.method || 'POST',
8214             id : this.id || Roo.id(),
8215             cls : ''
8216         };
8217         if (this.parent().xtype.match(/^Nav/)) {
8218             cfg.cls = 'navbar-form form-inline navbar-' + this.align;
8219
8220         }
8221
8222         if (this.labelAlign == 'left' ) {
8223             cfg.cls += ' form-horizontal';
8224         }
8225
8226
8227         return cfg;
8228     },
8229     initEvents : function()
8230     {
8231         this.el.on('submit', this.onSubmit, this);
8232         // this was added as random key presses on the form where triggering form submit.
8233         this.el.on('keypress', function(e) {
8234             if (e.getCharCode() != 13) {
8235                 return true;
8236             }
8237             // we might need to allow it for textareas.. and some other items.
8238             // check e.getTarget().
8239
8240             if(e.getTarget().nodeName.toLowerCase() === 'textarea'){
8241                 return true;
8242             }
8243
8244             Roo.log("keypress blocked");
8245
8246             e.preventDefault();
8247             return false;
8248         });
8249         
8250     },
8251     // private
8252     onSubmit : function(e){
8253         e.stopEvent();
8254     },
8255
8256      /**
8257      * Returns true if client-side validation on the form is successful.
8258      * @return Boolean
8259      */
8260     isValid : function(){
8261         var items = this.getItems();
8262         var valid = true;
8263         var target = false;
8264         
8265         items.each(function(f){
8266             
8267             if(f.validate()){
8268                 return;
8269             }
8270             
8271             Roo.log('invalid field: ' + f.name);
8272             
8273             valid = false;
8274
8275             if(!target && f.el.isVisible(true)){
8276                 target = f;
8277             }
8278            
8279         });
8280         
8281         if(this.errorMask && !valid){
8282             Roo.bootstrap.Form.popover.mask(this, target);
8283         }
8284         
8285         return valid;
8286     },
8287     
8288     /**
8289      * Returns true if any fields in this form have changed since their original load.
8290      * @return Boolean
8291      */
8292     isDirty : function(){
8293         var dirty = false;
8294         var items = this.getItems();
8295         items.each(function(f){
8296            if(f.isDirty()){
8297                dirty = true;
8298                return false;
8299            }
8300            return true;
8301         });
8302         return dirty;
8303     },
8304      /**
8305      * Performs a predefined action (submit or load) or custom actions you define on this form.
8306      * @param {String} actionName The name of the action type
8307      * @param {Object} options (optional) The options to pass to the action.  All of the config options listed
8308      * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
8309      * accept other config options):
8310      * <pre>
8311 Property          Type             Description
8312 ----------------  ---------------  ----------------------------------------------------------------------------------
8313 url               String           The url for the action (defaults to the form's url)
8314 method            String           The form method to use (defaults to the form's method, or POST if not defined)
8315 params            String/Object    The params to pass (defaults to the form's baseParams, or none if not defined)
8316 clientValidation  Boolean          Applies to submit only.  Pass true to call form.isValid() prior to posting to
8317                                    validate the form on the client (defaults to false)
8318      * </pre>
8319      * @return {BasicForm} this
8320      */
8321     doAction : function(action, options){
8322         if(typeof action == 'string'){
8323             action = new Roo.form.Action.ACTION_TYPES[action](this, options);
8324         }
8325         if(this.fireEvent('beforeaction', this, action) !== false){
8326             this.beforeAction(action);
8327             action.run.defer(100, action);
8328         }
8329         return this;
8330     },
8331
8332     // private
8333     beforeAction : function(action){
8334         var o = action.options;
8335         
8336         if(this.loadMask){
8337             
8338             if(this.maskBody){
8339                 Roo.get(document.body).mask(o.waitMsg || "Sending", 'x-mask-loading')
8340             } else {
8341                 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
8342             }
8343         }
8344         // not really supported yet.. ??
8345
8346         //if(this.waitMsgTarget === true){
8347         //  this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
8348         //}else if(this.waitMsgTarget){
8349         //    this.waitMsgTarget = Roo.get(this.waitMsgTarget);
8350         //    this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
8351         //}else {
8352         //    Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
8353        // }
8354
8355     },
8356
8357     // private
8358     afterAction : function(action, success){
8359         this.activeAction = null;
8360         var o = action.options;
8361
8362         if(this.loadMask){
8363             
8364             if(this.maskBody){
8365                 Roo.get(document.body).unmask();
8366             } else {
8367                 this.el.unmask();
8368             }
8369         }
8370         
8371         //if(this.waitMsgTarget === true){
8372 //            this.el.unmask();
8373         //}else if(this.waitMsgTarget){
8374         //    this.waitMsgTarget.unmask();
8375         //}else{
8376         //    Roo.MessageBox.updateProgress(1);
8377         //    Roo.MessageBox.hide();
8378        // }
8379         //
8380         if(success){
8381             if(o.reset){
8382                 this.reset();
8383             }
8384             Roo.callback(o.success, o.scope, [this, action]);
8385             this.fireEvent('actioncomplete', this, action);
8386
8387         }else{
8388
8389             // failure condition..
8390             // we have a scenario where updates need confirming.
8391             // eg. if a locking scenario exists..
8392             // we look for { errors : { needs_confirm : true }} in the response.
8393             if (
8394                 (typeof(action.result) != 'undefined')  &&
8395                 (typeof(action.result.errors) != 'undefined')  &&
8396                 (typeof(action.result.errors.needs_confirm) != 'undefined')
8397            ){
8398                 var _t = this;
8399                 Roo.log("not supported yet");
8400                  /*
8401
8402                 Roo.MessageBox.confirm(
8403                     "Change requires confirmation",
8404                     action.result.errorMsg,
8405                     function(r) {
8406                         if (r != 'yes') {
8407                             return;
8408                         }
8409                         _t.doAction('submit', { params :  { _submit_confirmed : 1 } }  );
8410                     }
8411
8412                 );
8413                 */
8414
8415
8416                 return;
8417             }
8418
8419             Roo.callback(o.failure, o.scope, [this, action]);
8420             // show an error message if no failed handler is set..
8421             if (!this.hasListener('actionfailed')) {
8422                 Roo.log("need to add dialog support");
8423                 /*
8424                 Roo.MessageBox.alert("Error",
8425                     (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
8426                         action.result.errorMsg :
8427                         "Saving Failed, please check your entries or try again"
8428                 );
8429                 */
8430             }
8431
8432             this.fireEvent('actionfailed', this, action);
8433         }
8434
8435     },
8436     /**
8437      * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
8438      * @param {String} id The value to search for
8439      * @return Field
8440      */
8441     findField : function(id){
8442         var items = this.getItems();
8443         var field = items.get(id);
8444         if(!field){
8445              items.each(function(f){
8446                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
8447                     field = f;
8448                     return false;
8449                 }
8450                 return true;
8451             });
8452         }
8453         return field || null;
8454     },
8455      /**
8456      * Mark fields in this form invalid in bulk.
8457      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
8458      * @return {BasicForm} this
8459      */
8460     markInvalid : function(errors){
8461         if(errors instanceof Array){
8462             for(var i = 0, len = errors.length; i < len; i++){
8463                 var fieldError = errors[i];
8464                 var f = this.findField(fieldError.id);
8465                 if(f){
8466                     f.markInvalid(fieldError.msg);
8467                 }
8468             }
8469         }else{
8470             var field, id;
8471             for(id in errors){
8472                 if(typeof errors[id] != 'function' && (field = this.findField(id))){
8473                     field.markInvalid(errors[id]);
8474                 }
8475             }
8476         }
8477         //Roo.each(this.childForms || [], function (f) {
8478         //    f.markInvalid(errors);
8479         //});
8480
8481         return this;
8482     },
8483
8484     /**
8485      * Set values for fields in this form in bulk.
8486      * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
8487      * @return {BasicForm} this
8488      */
8489     setValues : function(values){
8490         if(values instanceof Array){ // array of objects
8491             for(var i = 0, len = values.length; i < len; i++){
8492                 var v = values[i];
8493                 var f = this.findField(v.id);
8494                 if(f){
8495                     f.setValue(v.value);
8496                     if(this.trackResetOnLoad){
8497                         f.originalValue = f.getValue();
8498                     }
8499                 }
8500             }
8501         }else{ // object hash
8502             var field, id;
8503             for(id in values){
8504                 if(typeof values[id] != 'function' && (field = this.findField(id))){
8505
8506                     if (field.setFromData &&
8507                         field.valueField &&
8508                         field.displayField &&
8509                         // combos' with local stores can
8510                         // be queried via setValue()
8511                         // to set their value..
8512                         (field.store && !field.store.isLocal)
8513                         ) {
8514                         // it's a combo
8515                         var sd = { };
8516                         sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
8517                         sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
8518                         field.setFromData(sd);
8519
8520                     } else if(field.setFromData && (field.store && !field.store.isLocal)) {
8521                         
8522                         field.setFromData(values);
8523                         
8524                     } else {
8525                         field.setValue(values[id]);
8526                     }
8527
8528
8529                     if(this.trackResetOnLoad){
8530                         field.originalValue = field.getValue();
8531                     }
8532                 }
8533             }
8534         }
8535
8536         //Roo.each(this.childForms || [], function (f) {
8537         //    f.setValues(values);
8538         //});
8539
8540         return this;
8541     },
8542
8543     /**
8544      * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
8545      * they are returned as an array.
8546      * @param {Boolean} asString
8547      * @return {Object}
8548      */
8549     getValues : function(asString){
8550         //if (this.childForms) {
8551             // copy values from the child forms
8552         //    Roo.each(this.childForms, function (f) {
8553         //        this.setValues(f.getValues());
8554         //    }, this);
8555         //}
8556
8557
8558
8559         var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
8560         if(asString === true){
8561             return fs;
8562         }
8563         return Roo.urlDecode(fs);
8564     },
8565
8566     /**
8567      * Returns the fields in this form as an object with key/value pairs.
8568      * This differs from getValues as it calls getValue on each child item, rather than using dom data.
8569      * @return {Object}
8570      */
8571     getFieldValues : function(with_hidden)
8572     {
8573         var items = this.getItems();
8574         var ret = {};
8575         items.each(function(f){
8576             
8577             if (!f.getName()) {
8578                 return;
8579             }
8580             
8581             var v = f.getValue();
8582             
8583             if (f.inputType =='radio') {
8584                 if (typeof(ret[f.getName()]) == 'undefined') {
8585                     ret[f.getName()] = ''; // empty..
8586                 }
8587
8588                 if (!f.el.dom.checked) {
8589                     return;
8590
8591                 }
8592                 v = f.el.dom.value;
8593
8594             }
8595             
8596             if(f.xtype == 'MoneyField'){
8597                 ret[f.currencyName] = f.getCurrency();
8598             }
8599
8600             // not sure if this supported any more..
8601             if ((typeof(v) == 'object') && f.getRawValue) {
8602                 v = f.getRawValue() ; // dates..
8603             }
8604             // combo boxes where name != hiddenName...
8605             if (f.name !== false && f.name != '' && f.name != f.getName()) {
8606                 ret[f.name] = f.getRawValue();
8607             }
8608             ret[f.getName()] = v;
8609         });
8610
8611         return ret;
8612     },
8613
8614     /**
8615      * Clears all invalid messages in this form.
8616      * @return {BasicForm} this
8617      */
8618     clearInvalid : function(){
8619         var items = this.getItems();
8620
8621         items.each(function(f){
8622            f.clearInvalid();
8623         });
8624
8625         return this;
8626     },
8627
8628     /**
8629      * Resets this form.
8630      * @return {BasicForm} this
8631      */
8632     reset : function(){
8633         var items = this.getItems();
8634         items.each(function(f){
8635             f.reset();
8636         });
8637
8638         Roo.each(this.childForms || [], function (f) {
8639             f.reset();
8640         });
8641
8642
8643         return this;
8644     },
8645     
8646     getItems : function()
8647     {
8648         var r=new Roo.util.MixedCollection(false, function(o){
8649             return o.id || (o.id = Roo.id());
8650         });
8651         var iter = function(el) {
8652             if (el.inputEl) {
8653                 r.add(el);
8654             }
8655             if (!el.items) {
8656                 return;
8657             }
8658             Roo.each(el.items,function(e) {
8659                 iter(e);
8660             });
8661         };
8662
8663         iter(this);
8664         return r;
8665     },
8666     
8667     hideFields : function(items)
8668     {
8669         Roo.each(items, function(i){
8670             
8671             var f = this.findField(i);
8672             
8673             if(!f){
8674                 return;
8675             }
8676             
8677             f.hide();
8678             
8679         }, this);
8680     },
8681     
8682     showFields : function(items)
8683     {
8684         Roo.each(items, function(i){
8685             
8686             var f = this.findField(i);
8687             
8688             if(!f){
8689                 return;
8690             }
8691             
8692             f.show();
8693             
8694         }, this);
8695     }
8696
8697 });
8698
8699 Roo.apply(Roo.bootstrap.Form, {
8700     
8701     popover : {
8702         
8703         padding : 5,
8704         
8705         isApplied : false,
8706         
8707         isMasked : false,
8708         
8709         form : false,
8710         
8711         target : false,
8712         
8713         toolTip : false,
8714         
8715         intervalID : false,
8716         
8717         maskEl : false,
8718         
8719         apply : function()
8720         {
8721             if(this.isApplied){
8722                 return;
8723             }
8724             
8725             this.maskEl = {
8726                 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
8727                 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
8728                 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
8729                 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
8730             };
8731             
8732             this.maskEl.top.enableDisplayMode("block");
8733             this.maskEl.left.enableDisplayMode("block");
8734             this.maskEl.bottom.enableDisplayMode("block");
8735             this.maskEl.right.enableDisplayMode("block");
8736             
8737             this.toolTip = new Roo.bootstrap.Tooltip({
8738                 cls : 'roo-form-error-popover',
8739                 alignment : {
8740                     'left' : ['r-l', [-2,0], 'right'],
8741                     'right' : ['l-r', [2,0], 'left'],
8742                     'bottom' : ['tl-bl', [0,2], 'top'],
8743                     'top' : [ 'bl-tl', [0,-2], 'bottom']
8744                 }
8745             });
8746             
8747             this.toolTip.render(Roo.get(document.body));
8748
8749             this.toolTip.el.enableDisplayMode("block");
8750             
8751             Roo.get(document.body).on('click', function(){
8752                 this.unmask();
8753             }, this);
8754             
8755             Roo.get(document.body).on('touchstart', function(){
8756                 this.unmask();
8757             }, this);
8758             
8759             this.isApplied = true
8760         },
8761         
8762         mask : function(form, target)
8763         {
8764             this.form = form;
8765             
8766             this.target = target;
8767             
8768             if(!this.form.errorMask || !target.el){
8769                 return;
8770             }
8771             
8772             var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.modal', 100, true) || Roo.get(document.body);
8773             
8774             Roo.log(scrollable);
8775             
8776             var ot = this.target.el.calcOffsetsTo(scrollable);
8777             
8778             var scrollTo = ot[1] - this.form.maskOffset;
8779             
8780             scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
8781             
8782             scrollable.scrollTo('top', scrollTo);
8783             
8784             var box = this.target.el.getBox();
8785             Roo.log(box);
8786             var zIndex = Roo.bootstrap.Modal.zIndex++;
8787
8788             
8789             this.maskEl.top.setStyle('position', 'absolute');
8790             this.maskEl.top.setStyle('z-index', zIndex);
8791             this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
8792             this.maskEl.top.setLeft(0);
8793             this.maskEl.top.setTop(0);
8794             this.maskEl.top.show();
8795             
8796             this.maskEl.left.setStyle('position', 'absolute');
8797             this.maskEl.left.setStyle('z-index', zIndex);
8798             this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
8799             this.maskEl.left.setLeft(0);
8800             this.maskEl.left.setTop(box.y - this.padding);
8801             this.maskEl.left.show();
8802
8803             this.maskEl.bottom.setStyle('position', 'absolute');
8804             this.maskEl.bottom.setStyle('z-index', zIndex);
8805             this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
8806             this.maskEl.bottom.setLeft(0);
8807             this.maskEl.bottom.setTop(box.bottom + this.padding);
8808             this.maskEl.bottom.show();
8809
8810             this.maskEl.right.setStyle('position', 'absolute');
8811             this.maskEl.right.setStyle('z-index', zIndex);
8812             this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
8813             this.maskEl.right.setLeft(box.right + this.padding);
8814             this.maskEl.right.setTop(box.y - this.padding);
8815             this.maskEl.right.show();
8816
8817             this.toolTip.bindEl = this.target.el;
8818
8819             this.toolTip.el.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
8820
8821             var tip = this.target.blankText;
8822
8823             if(this.target.getValue() !== '' ) {
8824                 
8825                 if (this.target.invalidText.length) {
8826                     tip = this.target.invalidText;
8827                 } else if (this.target.regexText.length){
8828                     tip = this.target.regexText;
8829                 }
8830             }
8831
8832             this.toolTip.show(tip);
8833
8834             this.intervalID = window.setInterval(function() {
8835                 Roo.bootstrap.Form.popover.unmask();
8836             }, 10000);
8837
8838             window.onwheel = function(){ return false;};
8839             
8840             (function(){ this.isMasked = true; }).defer(500, this);
8841             
8842         },
8843         
8844         unmask : function()
8845         {
8846             if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
8847                 return;
8848             }
8849             
8850             this.maskEl.top.setStyle('position', 'absolute');
8851             this.maskEl.top.setSize(0, 0).setXY([0, 0]);
8852             this.maskEl.top.hide();
8853
8854             this.maskEl.left.setStyle('position', 'absolute');
8855             this.maskEl.left.setSize(0, 0).setXY([0, 0]);
8856             this.maskEl.left.hide();
8857
8858             this.maskEl.bottom.setStyle('position', 'absolute');
8859             this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
8860             this.maskEl.bottom.hide();
8861
8862             this.maskEl.right.setStyle('position', 'absolute');
8863             this.maskEl.right.setSize(0, 0).setXY([0, 0]);
8864             this.maskEl.right.hide();
8865             
8866             this.toolTip.hide();
8867             
8868             this.toolTip.el.hide();
8869             
8870             window.onwheel = function(){ return true;};
8871             
8872             if(this.intervalID){
8873                 window.clearInterval(this.intervalID);
8874                 this.intervalID = false;
8875             }
8876             
8877             this.isMasked = false;
8878             
8879         }
8880         
8881     }
8882     
8883 });
8884
8885 /*
8886  * Based on:
8887  * Ext JS Library 1.1.1
8888  * Copyright(c) 2006-2007, Ext JS, LLC.
8889  *
8890  * Originally Released Under LGPL - original licence link has changed is not relivant.
8891  *
8892  * Fork - LGPL
8893  * <script type="text/javascript">
8894  */
8895 /**
8896  * @class Roo.form.VTypes
8897  * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
8898  * @singleton
8899  */
8900 Roo.form.VTypes = function(){
8901     // closure these in so they are only created once.
8902     var alpha = /^[a-zA-Z_]+$/;
8903     var alphanum = /^[a-zA-Z0-9_]+$/;
8904     var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
8905     var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
8906
8907     // All these messages and functions are configurable
8908     return {
8909         /**
8910          * The function used to validate email addresses
8911          * @param {String} value The email address
8912          */
8913         'email' : function(v){
8914             return email.test(v);
8915         },
8916         /**
8917          * The error text to display when the email validation function returns false
8918          * @type String
8919          */
8920         'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
8921         /**
8922          * The keystroke filter mask to be applied on email input
8923          * @type RegExp
8924          */
8925         'emailMask' : /[a-z0-9_\.\-@]/i,
8926
8927         /**
8928          * The function used to validate URLs
8929          * @param {String} value The URL
8930          */
8931         'url' : function(v){
8932             return url.test(v);
8933         },
8934         /**
8935          * The error text to display when the url validation function returns false
8936          * @type String
8937          */
8938         'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
8939         
8940         /**
8941          * The function used to validate alpha values
8942          * @param {String} value The value
8943          */
8944         'alpha' : function(v){
8945             return alpha.test(v);
8946         },
8947         /**
8948          * The error text to display when the alpha validation function returns false
8949          * @type String
8950          */
8951         'alphaText' : 'This field should only contain letters and _',
8952         /**
8953          * The keystroke filter mask to be applied on alpha input
8954          * @type RegExp
8955          */
8956         'alphaMask' : /[a-z_]/i,
8957
8958         /**
8959          * The function used to validate alphanumeric values
8960          * @param {String} value The value
8961          */
8962         'alphanum' : function(v){
8963             return alphanum.test(v);
8964         },
8965         /**
8966          * The error text to display when the alphanumeric validation function returns false
8967          * @type String
8968          */
8969         'alphanumText' : 'This field should only contain letters, numbers and _',
8970         /**
8971          * The keystroke filter mask to be applied on alphanumeric input
8972          * @type RegExp
8973          */
8974         'alphanumMask' : /[a-z0-9_]/i
8975     };
8976 }();/*
8977  * - LGPL
8978  *
8979  * Input
8980  * 
8981  */
8982
8983 /**
8984  * @class Roo.bootstrap.Input
8985  * @extends Roo.bootstrap.Component
8986  * Bootstrap Input class
8987  * @cfg {Boolean} disabled is it disabled
8988  * @cfg {String} inputType button | checkbox | email | file | hidden | image | number | password | radio | range | reset | search | submit | text
8989  * @cfg {String} name name of the input
8990  * @cfg {string} fieldLabel - the label associated
8991  * @cfg {string} placeholder - placeholder to put in text.
8992  * @cfg {string}  before - input group add on before
8993  * @cfg {string} after - input group add on after
8994  * @cfg {string} size - (lg|sm) or leave empty..
8995  * @cfg {Number} xs colspan out of 12 for mobile-sized screens
8996  * @cfg {Number} sm colspan out of 12 for tablet-sized screens
8997  * @cfg {Number} md colspan out of 12 for computer-sized screens
8998  * @cfg {Number} lg colspan out of 12 for large computer-sized screens
8999  * @cfg {string} value default value of the input
9000  * @cfg {Number} labelWidth set the width of label 
9001  * @cfg {Number} labellg set the width of label (1-12)
9002  * @cfg {Number} labelmd set the width of label (1-12)
9003  * @cfg {Number} labelsm set the width of label (1-12)
9004  * @cfg {Number} labelxs set the width of label (1-12)
9005  * @cfg {String} labelAlign (top|left)
9006  * @cfg {Boolean} readOnly Specifies that the field should be read-only
9007  * @cfg {String} autocomplete - default is new-password see: https://developers.google.com/web/fundamentals/input/form/label-and-name-inputs?hl=en
9008  * @cfg {String} indicatorpos (left|right) default left
9009  * @cfg {String} capture (user|camera) use for file input only. (default empty)
9010  * @cfg {String} accept (image|video|audio) use for file input only. (default empty)
9011
9012  * @cfg {String} align (left|center|right) Default left
9013  * @cfg {Boolean} forceFeedback (true|false) Default false
9014  * 
9015  * @constructor
9016  * Create a new Input
9017  * @param {Object} config The config object
9018  */
9019
9020 Roo.bootstrap.Input = function(config){
9021     
9022     Roo.bootstrap.Input.superclass.constructor.call(this, config);
9023     
9024     this.addEvents({
9025         /**
9026          * @event focus
9027          * Fires when this field receives input focus.
9028          * @param {Roo.form.Field} this
9029          */
9030         focus : true,
9031         /**
9032          * @event blur
9033          * Fires when this field loses input focus.
9034          * @param {Roo.form.Field} this
9035          */
9036         blur : true,
9037         /**
9038          * @event specialkey
9039          * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
9040          * {@link Roo.EventObject#getKey} to determine which key was pressed.
9041          * @param {Roo.form.Field} this
9042          * @param {Roo.EventObject} e The event object
9043          */
9044         specialkey : true,
9045         /**
9046          * @event change
9047          * Fires just before the field blurs if the field value has changed.
9048          * @param {Roo.form.Field} this
9049          * @param {Mixed} newValue The new value
9050          * @param {Mixed} oldValue The original value
9051          */
9052         change : true,
9053         /**
9054          * @event invalid
9055          * Fires after the field has been marked as invalid.
9056          * @param {Roo.form.Field} this
9057          * @param {String} msg The validation message
9058          */
9059         invalid : true,
9060         /**
9061          * @event valid
9062          * Fires after the field has been validated with no errors.
9063          * @param {Roo.form.Field} this
9064          */
9065         valid : true,
9066          /**
9067          * @event keyup
9068          * Fires after the key up
9069          * @param {Roo.form.Field} this
9070          * @param {Roo.EventObject}  e The event Object
9071          */
9072         keyup : true
9073     });
9074 };
9075
9076 Roo.extend(Roo.bootstrap.Input, Roo.bootstrap.Component,  {
9077      /**
9078      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
9079       automatic validation (defaults to "keyup").
9080      */
9081     validationEvent : "keyup",
9082      /**
9083      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
9084      */
9085     validateOnBlur : true,
9086     /**
9087      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
9088      */
9089     validationDelay : 250,
9090      /**
9091      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
9092      */
9093     focusClass : "x-form-focus",  // not needed???
9094     
9095        
9096     /**
9097      * @cfg {String} invalidClass DEPRICATED - code uses BS4 - is-valid / is-invalid
9098      */
9099     invalidClass : "has-warning",
9100     
9101     /**
9102      * @cfg {String} validClass DEPRICATED - code uses BS4 - is-valid / is-invalid
9103      */
9104     validClass : "has-success",
9105     
9106     /**
9107      * @cfg {Boolean} hasFeedback (true|false) default true
9108      */
9109     hasFeedback : true,
9110     
9111     /**
9112      * @cfg {String} invalidFeedbackIcon The CSS class to use when create feedback icon (defaults to "x-form-invalid")
9113      */
9114     invalidFeedbackClass : "glyphicon-warning-sign",
9115     
9116     /**
9117      * @cfg {String} validFeedbackIcon The CSS class to use when create feedback icon (defaults to "x-form-invalid")
9118      */
9119     validFeedbackClass : "glyphicon-ok",
9120     
9121     /**
9122      * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
9123      */
9124     selectOnFocus : false,
9125     
9126      /**
9127      * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
9128      */
9129     maskRe : null,
9130        /**
9131      * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
9132      */
9133     vtype : null,
9134     
9135       /**
9136      * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
9137      */
9138     disableKeyFilter : false,
9139     
9140        /**
9141      * @cfg {Boolean} disabled True to disable the field (defaults to false).
9142      */
9143     disabled : false,
9144      /**
9145      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
9146      */
9147     allowBlank : true,
9148     /**
9149      * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
9150      */
9151     blankText : "Please complete this mandatory field",
9152     
9153      /**
9154      * @cfg {Number} minLength Minimum input field length required (defaults to 0)
9155      */
9156     minLength : 0,
9157     /**
9158      * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
9159      */
9160     maxLength : Number.MAX_VALUE,
9161     /**
9162      * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
9163      */
9164     minLengthText : "The minimum length for this field is {0}",
9165     /**
9166      * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
9167      */
9168     maxLengthText : "The maximum length for this field is {0}",
9169   
9170     
9171     /**
9172      * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
9173      * If available, this function will be called only after the basic validators all return true, and will be passed the
9174      * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
9175      */
9176     validator : null,
9177     /**
9178      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
9179      * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
9180      * current field value.  If the test fails, the field will be marked invalid using {@link #regexText}.
9181      */
9182     regex : null,
9183     /**
9184      * @cfg {String} regexText -- Depricated - use Invalid Text
9185      */
9186     regexText : "",
9187     
9188     /**
9189      * @cfg {String} invalidText The error text to display if {@link #validator} test fails during validation (defaults to "")
9190      */
9191     invalidText : "",
9192     
9193     
9194     
9195     autocomplete: false,
9196     
9197     
9198     fieldLabel : '',
9199     inputType : 'text',
9200     
9201     name : false,
9202     placeholder: false,
9203     before : false,
9204     after : false,
9205     size : false,
9206     hasFocus : false,
9207     preventMark: false,
9208     isFormField : true,
9209     value : '',
9210     labelWidth : 2,
9211     labelAlign : false,
9212     readOnly : false,
9213     align : false,
9214     formatedValue : false,
9215     forceFeedback : false,
9216     
9217     indicatorpos : 'left',
9218     
9219     labellg : 0,
9220     labelmd : 0,
9221     labelsm : 0,
9222     labelxs : 0,
9223     
9224     capture : '',
9225     accept : '',
9226     
9227     parentLabelAlign : function()
9228     {
9229         var parent = this;
9230         while (parent.parent()) {
9231             parent = parent.parent();
9232             if (typeof(parent.labelAlign) !='undefined') {
9233                 return parent.labelAlign;
9234             }
9235         }
9236         return 'left';
9237         
9238     },
9239     
9240     getAutoCreate : function()
9241     {
9242         var align = (!this.labelAlign) ? this.parentLabelAlign() : this.labelAlign;
9243         
9244         var id = Roo.id();
9245         
9246         var cfg = {};
9247         
9248         if(this.inputType != 'hidden'){
9249             cfg.cls = 'form-group' //input-group
9250         }
9251         
9252         var input =  {
9253             tag: 'input',
9254             id : id,
9255             type : this.inputType,
9256             value : this.value,
9257             cls : 'form-control',
9258             placeholder : this.placeholder || '',
9259             autocomplete : this.autocomplete || 'new-password'
9260         };
9261         
9262         if(this.capture.length){
9263             input.capture = this.capture;
9264         }
9265         
9266         if(this.accept.length){
9267             input.accept = this.accept + "/*";
9268         }
9269         
9270         if(this.align){
9271             input.style = (typeof(input.style) == 'undefined') ? ('text-align:' + this.align) : (input.style + 'text-align:' + this.align);
9272         }
9273         
9274         if(this.maxLength && this.maxLength != Number.MAX_VALUE){
9275             input.maxLength = this.maxLength;
9276         }
9277         
9278         if (this.disabled) {
9279             input.disabled=true;
9280         }
9281         
9282         if (this.readOnly) {
9283             input.readonly=true;
9284         }
9285         
9286         if (this.name) {
9287             input.name = this.name;
9288         }
9289         
9290         if (this.size) {
9291             input.cls += ' input-' + this.size;
9292         }
9293         
9294         var settings=this;
9295         ['xs','sm','md','lg'].map(function(size){
9296             if (settings[size]) {
9297                 cfg.cls += ' col-' + size + '-' + settings[size];
9298             }
9299         });
9300         
9301         var inputblock = input;
9302         
9303         var feedback = {
9304             tag: 'span',
9305             cls: 'glyphicon form-control-feedback'
9306         };
9307             
9308         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
9309             
9310             inputblock = {
9311                 cls : 'has-feedback',
9312                 cn :  [
9313                     input,
9314                     feedback
9315                 ] 
9316             };  
9317         }
9318         
9319         if (this.before || this.after) {
9320             
9321             inputblock = {
9322                 cls : 'input-group',
9323                 cn :  [] 
9324             };
9325             
9326             if (this.before && typeof(this.before) == 'string') {
9327                 
9328                 inputblock.cn.push({
9329                     tag :'span',
9330                     cls : 'roo-input-before input-group-addon input-group-prepend input-group-text',
9331                     html : this.before
9332                 });
9333             }
9334             if (this.before && typeof(this.before) == 'object') {
9335                 this.before = Roo.factory(this.before);
9336                 
9337                 inputblock.cn.push({
9338                     tag :'span',
9339                     cls : 'roo-input-before input-group-prepend input-group-text input-group-' +
9340                         (this.before.xtype == 'Button' ? 'btn' : 'addon')  //?? what about checkboxes - that looks like a bit of a hack thought? 
9341                 });
9342             }
9343             
9344             inputblock.cn.push(input);
9345             
9346             if (this.after && typeof(this.after) == 'string') {
9347                 inputblock.cn.push({
9348                     tag :'span',
9349                     cls : 'roo-input-after input-group-append input-group-text input-group-addon',
9350                     html : this.after
9351                 });
9352             }
9353             if (this.after && typeof(this.after) == 'object') {
9354                 this.after = Roo.factory(this.after);
9355                 
9356                 inputblock.cn.push({
9357                     tag :'span',
9358                     cls : 'roo-input-after input-group-append input-group-text input-group-' +
9359                         (this.after.xtype == 'Button' ? 'btn' : 'addon')  //?? what about checkboxes - that looks like a bit of a hack thought? 
9360                 });
9361             }
9362             
9363             if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
9364                 inputblock.cls += ' has-feedback';
9365                 inputblock.cn.push(feedback);
9366             }
9367         };
9368         var indicator = {
9369             tag : 'i',
9370             cls : 'roo-required-indicator ' + (this.indicatorpos == 'right'  ? 'right' : 'left') +'-indicator text-danger fa fa-lg fa-star',
9371             tooltip : 'This field is required'
9372         };
9373         if (Roo.bootstrap.version == 4) {
9374             indicator = {
9375                 tag : 'i',
9376                 style : 'display-none'
9377             };
9378         }
9379         if (align ==='left' && this.fieldLabel.length) {
9380             
9381             cfg.cls += ' roo-form-group-label-left'  + (Roo.bootstrap.version == 4 ? ' row' : '');
9382             
9383             cfg.cn = [
9384                 indicator,
9385                 {
9386                     tag: 'label',
9387                     'for' :  id,
9388                     cls : 'control-label col-form-label',
9389                     html : this.fieldLabel
9390
9391                 },
9392                 {
9393                     cls : "", 
9394                     cn: [
9395                         inputblock
9396                     ]
9397                 }
9398             ];
9399             
9400             var labelCfg = cfg.cn[1];
9401             var contentCfg = cfg.cn[2];
9402             
9403             if(this.indicatorpos == 'right'){
9404                 cfg.cn = [
9405                     {
9406                         tag: 'label',
9407                         'for' :  id,
9408                         cls : 'control-label col-form-label',
9409                         cn : [
9410                             {
9411                                 tag : 'span',
9412                                 html : this.fieldLabel
9413                             },
9414                             indicator
9415                         ]
9416                     },
9417                     {
9418                         cls : "",
9419                         cn: [
9420                             inputblock
9421                         ]
9422                     }
9423
9424                 ];
9425                 
9426                 labelCfg = cfg.cn[0];
9427                 contentCfg = cfg.cn[1];
9428             
9429             }
9430             
9431             if(this.labelWidth > 12){
9432                 labelCfg.style = "width: " + this.labelWidth + 'px';
9433             }
9434             
9435             if(this.labelWidth < 13 && this.labelmd == 0){
9436                 this.labelmd = this.labelWidth;
9437             }
9438             
9439             if(this.labellg > 0){
9440                 labelCfg.cls += ' col-lg-' + this.labellg;
9441                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
9442             }
9443             
9444             if(this.labelmd > 0){
9445                 labelCfg.cls += ' col-md-' + this.labelmd;
9446                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
9447             }
9448             
9449             if(this.labelsm > 0){
9450                 labelCfg.cls += ' col-sm-' + this.labelsm;
9451                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
9452             }
9453             
9454             if(this.labelxs > 0){
9455                 labelCfg.cls += ' col-xs-' + this.labelxs;
9456                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
9457             }
9458             
9459             
9460         } else if ( this.fieldLabel.length) {
9461                 
9462             cfg.cn = [
9463                 {
9464                     tag : 'i',
9465                     cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
9466                     tooltip : 'This field is required'
9467                 },
9468                 {
9469                     tag: 'label',
9470                    //cls : 'input-group-addon',
9471                     html : this.fieldLabel
9472
9473                 },
9474
9475                inputblock
9476
9477            ];
9478            
9479            if(this.indicatorpos == 'right'){
9480                 
9481                 cfg.cn = [
9482                     {
9483                         tag: 'label',
9484                        //cls : 'input-group-addon',
9485                         html : this.fieldLabel
9486
9487                     },
9488                     {
9489                         tag : 'i',
9490                         cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
9491                         tooltip : 'This field is required'
9492                     },
9493
9494                    inputblock
9495
9496                ];
9497
9498             }
9499
9500         } else {
9501             
9502             cfg.cn = [
9503
9504                     inputblock
9505
9506             ];
9507                 
9508                 
9509         };
9510         
9511         if (this.parentType === 'Navbar' &&  this.parent().bar) {
9512            cfg.cls += ' navbar-form';
9513         }
9514         
9515         if (this.parentType === 'NavGroup' && !(Roo.bootstrap.version == 4 && this.parent().form)) {
9516             // on BS4 we do this only if not form 
9517             cfg.cls += ' navbar-form';
9518             cfg.tag = 'li';
9519         }
9520         
9521         return cfg;
9522         
9523     },
9524     /**
9525      * return the real input element.
9526      */
9527     inputEl: function ()
9528     {
9529         return this.el.select('input.form-control',true).first();
9530     },
9531     
9532     tooltipEl : function()
9533     {
9534         return this.inputEl();
9535     },
9536     
9537     indicatorEl : function()
9538     {
9539         if (Roo.bootstrap.version == 4) {
9540             return false; // not enabled in v4 yet.
9541         }
9542         
9543         var indicator = this.el.select('i.roo-required-indicator',true).first();
9544         
9545         if(!indicator){
9546             return false;
9547         }
9548         
9549         return indicator;
9550         
9551     },
9552     
9553     setDisabled : function(v)
9554     {
9555         var i  = this.inputEl().dom;
9556         if (!v) {
9557             i.removeAttribute('disabled');
9558             return;
9559             
9560         }
9561         i.setAttribute('disabled','true');
9562     },
9563     initEvents : function()
9564     {
9565           
9566         this.inputEl().on("keydown" , this.fireKey,  this);
9567         this.inputEl().on("focus", this.onFocus,  this);
9568         this.inputEl().on("blur", this.onBlur,  this);
9569         
9570         this.inputEl().relayEvent('keyup', this);
9571         
9572         this.indicator = this.indicatorEl();
9573         
9574         if(this.indicator){
9575             this.indicator.addClass(this.indicatorpos == 'right' ? 'hidden' : 'invisible'); // changed from invisible??? - 
9576         }
9577  
9578         // reference to original value for reset
9579         this.originalValue = this.getValue();
9580         //Roo.form.TextField.superclass.initEvents.call(this);
9581         if(this.validationEvent == 'keyup'){
9582             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
9583             this.inputEl().on('keyup', this.filterValidation, this);
9584         }
9585         else if(this.validationEvent !== false){
9586             this.inputEl().on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
9587         }
9588         
9589         if(this.selectOnFocus){
9590             this.on("focus", this.preFocus, this);
9591             
9592         }
9593         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
9594             this.inputEl().on("keypress", this.filterKeys, this);
9595         } else {
9596             this.inputEl().relayEvent('keypress', this);
9597         }
9598        /* if(this.grow){
9599             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
9600             this.el.on("click", this.autoSize,  this);
9601         }
9602         */
9603         if(this.inputEl().is('input[type=password]') && Roo.isSafari){
9604             this.inputEl().on('keydown', this.SafariOnKeyDown, this);
9605         }
9606         
9607         if (typeof(this.before) == 'object') {
9608             this.before.render(this.el.select('.roo-input-before',true).first());
9609         }
9610         if (typeof(this.after) == 'object') {
9611             this.after.render(this.el.select('.roo-input-after',true).first());
9612         }
9613         
9614         this.inputEl().on('change', this.onChange, this);
9615         
9616     },
9617     filterValidation : function(e){
9618         if(!e.isNavKeyPress()){
9619             this.validationTask.delay(this.validationDelay);
9620         }
9621     },
9622      /**
9623      * Validates the field value
9624      * @return {Boolean} True if the value is valid, else false
9625      */
9626     validate : function(){
9627         //if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
9628         if(this.disabled || this.validateValue(this.getRawValue())){
9629             this.markValid();
9630             return true;
9631         }
9632         
9633         this.markInvalid();
9634         return false;
9635     },
9636     
9637     
9638     /**
9639      * Validates a value according to the field's validation rules and marks the field as invalid
9640      * if the validation fails
9641      * @param {Mixed} value The value to validate
9642      * @return {Boolean} True if the value is valid, else false
9643      */
9644     validateValue : function(value)
9645     {
9646         if(this.getVisibilityEl().hasClass('hidden')){
9647             return true;
9648         }
9649         
9650         if(value.length < 1)  { // if it's blank
9651             if(this.allowBlank){
9652                 return true;
9653             }
9654             return false;
9655         }
9656         
9657         if(value.length < this.minLength){
9658             return false;
9659         }
9660         if(value.length > this.maxLength){
9661             return false;
9662         }
9663         if(this.vtype){
9664             var vt = Roo.form.VTypes;
9665             if(!vt[this.vtype](value, this)){
9666                 return false;
9667             }
9668         }
9669         if(typeof this.validator == "function"){
9670             var msg = this.validator(value);
9671             if(msg !== true){
9672                 return false;
9673             }
9674             if (typeof(msg) == 'string') {
9675                 this.invalidText = msg;
9676             }
9677         }
9678         
9679         if(this.regex && !this.regex.test(value)){
9680             return false;
9681         }
9682         
9683         return true;
9684     },
9685     
9686      // private
9687     fireKey : function(e){
9688         //Roo.log('field ' + e.getKey());
9689         if(e.isNavKeyPress()){
9690             this.fireEvent("specialkey", this, e);
9691         }
9692     },
9693     focus : function (selectText){
9694         if(this.rendered){
9695             this.inputEl().focus();
9696             if(selectText === true){
9697                 this.inputEl().dom.select();
9698             }
9699         }
9700         return this;
9701     } ,
9702     
9703     onFocus : function(){
9704         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
9705            // this.el.addClass(this.focusClass);
9706         }
9707         if(!this.hasFocus){
9708             this.hasFocus = true;
9709             this.startValue = this.getValue();
9710             this.fireEvent("focus", this);
9711         }
9712     },
9713     
9714     beforeBlur : Roo.emptyFn,
9715
9716     
9717     // private
9718     onBlur : function(){
9719         this.beforeBlur();
9720         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
9721             //this.el.removeClass(this.focusClass);
9722         }
9723         this.hasFocus = false;
9724         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
9725             this.validate();
9726         }
9727         var v = this.getValue();
9728         if(String(v) !== String(this.startValue)){
9729             this.fireEvent('change', this, v, this.startValue);
9730         }
9731         this.fireEvent("blur", this);
9732     },
9733     
9734     onChange : function(e)
9735     {
9736         var v = this.getValue();
9737         if(String(v) !== String(this.startValue)){
9738             this.fireEvent('change', this, v, this.startValue);
9739         }
9740         
9741     },
9742     
9743     /**
9744      * Resets the current field value to the originally loaded value and clears any validation messages
9745      */
9746     reset : function(){
9747         this.setValue(this.originalValue);
9748         this.validate();
9749     },
9750      /**
9751      * Returns the name of the field
9752      * @return {Mixed} name The name field
9753      */
9754     getName: function(){
9755         return this.name;
9756     },
9757      /**
9758      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
9759      * @return {Mixed} value The field value
9760      */
9761     getValue : function(){
9762         
9763         var v = this.inputEl().getValue();
9764         
9765         return v;
9766     },
9767     /**
9768      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
9769      * @return {Mixed} value The field value
9770      */
9771     getRawValue : function(){
9772         var v = this.inputEl().getValue();
9773         
9774         return v;
9775     },
9776     
9777     /**
9778      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
9779      * @param {Mixed} value The value to set
9780      */
9781     setRawValue : function(v){
9782         return this.inputEl().dom.value = (v === null || v === undefined ? '' : v);
9783     },
9784     
9785     selectText : function(start, end){
9786         var v = this.getRawValue();
9787         if(v.length > 0){
9788             start = start === undefined ? 0 : start;
9789             end = end === undefined ? v.length : end;
9790             var d = this.inputEl().dom;
9791             if(d.setSelectionRange){
9792                 d.setSelectionRange(start, end);
9793             }else if(d.createTextRange){
9794                 var range = d.createTextRange();
9795                 range.moveStart("character", start);
9796                 range.moveEnd("character", v.length-end);
9797                 range.select();
9798             }
9799         }
9800     },
9801     
9802     /**
9803      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
9804      * @param {Mixed} value The value to set
9805      */
9806     setValue : function(v){
9807         this.value = v;
9808         if(this.rendered){
9809             this.inputEl().dom.value = (v === null || v === undefined ? '' : v);
9810             this.validate();
9811         }
9812     },
9813     
9814     /*
9815     processValue : function(value){
9816         if(this.stripCharsRe){
9817             var newValue = value.replace(this.stripCharsRe, '');
9818             if(newValue !== value){
9819                 this.setRawValue(newValue);
9820                 return newValue;
9821             }
9822         }
9823         return value;
9824     },
9825   */
9826     preFocus : function(){
9827         
9828         if(this.selectOnFocus){
9829             this.inputEl().dom.select();
9830         }
9831     },
9832     filterKeys : function(e){
9833         var k = e.getKey();
9834         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
9835             return;
9836         }
9837         var c = e.getCharCode(), cc = String.fromCharCode(c);
9838         if(Roo.isIE && (e.isSpecialKey() || !cc)){
9839             return;
9840         }
9841         if(!this.maskRe.test(cc)){
9842             e.stopEvent();
9843         }
9844     },
9845      /**
9846      * Clear any invalid styles/messages for this field
9847      */
9848     clearInvalid : function(){
9849         
9850         if(!this.el || this.preventMark){ // not rendered
9851             return;
9852         }
9853         
9854         
9855         this.el.removeClass([this.invalidClass, 'is-invalid']);
9856         
9857         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
9858             
9859             var feedback = this.el.select('.form-control-feedback', true).first();
9860             
9861             if(feedback){
9862                 this.el.select('.form-control-feedback', true).first().removeClass(this.invalidFeedbackClass);
9863             }
9864             
9865         }
9866         
9867         if(this.indicator){
9868             this.indicator.removeClass('visible');
9869             this.indicator.addClass(this.indicatorpos == 'right' ? 'hidden' : 'invisible');
9870         }
9871         
9872         this.fireEvent('valid', this);
9873     },
9874     
9875      /**
9876      * Mark this field as valid
9877      */
9878     markValid : function()
9879     {
9880         if(!this.el  || this.preventMark){ // not rendered...
9881             return;
9882         }
9883         
9884         this.el.removeClass([this.invalidClass, this.validClass]);
9885         this.inputEl().removeClass(['is-valid', 'is-invalid']);
9886
9887         var feedback = this.el.select('.form-control-feedback', true).first();
9888             
9889         if(feedback){
9890             this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
9891         }
9892         
9893         if(this.indicator){
9894             this.indicator.removeClass('visible');
9895             this.indicator.addClass(this.indicatorpos == 'right' ? 'hidden' : 'invisible');
9896         }
9897         
9898         if(this.disabled){
9899             return;
9900         }
9901         
9902         if(this.allowBlank && !this.getRawValue().length){
9903             return;
9904         }
9905         if (Roo.bootstrap.version == 3) {
9906             this.el.addClass(this.validClass);
9907         } else {
9908             this.inputEl().addClass('is-valid');
9909         }
9910
9911         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank && (this.getValue().length || this.forceFeedback)){
9912             
9913             var feedback = this.el.select('.form-control-feedback', true).first();
9914             
9915             if(feedback){
9916                 this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
9917                 this.el.select('.form-control-feedback', true).first().addClass([this.validFeedbackClass]);
9918             }
9919             
9920         }
9921         
9922         this.fireEvent('valid', this);
9923     },
9924     
9925      /**
9926      * Mark this field as invalid
9927      * @param {String} msg The validation message
9928      */
9929     markInvalid : function(msg)
9930     {
9931         if(!this.el  || this.preventMark){ // not rendered
9932             return;
9933         }
9934         
9935         this.el.removeClass([this.invalidClass, this.validClass]);
9936         this.inputEl().removeClass(['is-valid', 'is-invalid']);
9937         
9938         var feedback = this.el.select('.form-control-feedback', true).first();
9939             
9940         if(feedback){
9941             this.el.select('.form-control-feedback', true).first().removeClass(
9942                     [this.invalidFeedbackClass, this.validFeedbackClass]);
9943         }
9944
9945         if(this.disabled){
9946             return;
9947         }
9948         
9949         if(this.allowBlank && !this.getRawValue().length){
9950             return;
9951         }
9952         
9953         if(this.indicator){
9954             this.indicator.removeClass(this.indicatorpos == 'right' ? 'hidden' : 'invisible');
9955             this.indicator.addClass('visible');
9956         }
9957         if (Roo.bootstrap.version == 3) {
9958             this.el.addClass(this.invalidClass);
9959         } else {
9960             this.inputEl().addClass('is-invalid');
9961         }
9962         
9963         
9964         
9965         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
9966             
9967             var feedback = this.el.select('.form-control-feedback', true).first();
9968             
9969             if(feedback){
9970                 this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
9971                 
9972                 if(this.getValue().length || this.forceFeedback){
9973                     this.el.select('.form-control-feedback', true).first().addClass([this.invalidFeedbackClass]);
9974                 }
9975                 
9976             }
9977             
9978         }
9979         
9980         this.fireEvent('invalid', this, msg);
9981     },
9982     // private
9983     SafariOnKeyDown : function(event)
9984     {
9985         // this is a workaround for a password hang bug on chrome/ webkit.
9986         if (this.inputEl().dom.type != 'password') {
9987             return;
9988         }
9989         
9990         var isSelectAll = false;
9991         
9992         if(this.inputEl().dom.selectionEnd > 0){
9993             isSelectAll = (this.inputEl().dom.selectionEnd - this.inputEl().dom.selectionStart - this.getValue().length == 0) ? true : false;
9994         }
9995         if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
9996             event.preventDefault();
9997             this.setValue('');
9998             return;
9999         }
10000         
10001         if(isSelectAll  && event.getCharCode() > 31 && !event.ctrlKey) { // not backspace and delete key (or ctrl-v)
10002             
10003             event.preventDefault();
10004             // this is very hacky as keydown always get's upper case.
10005             //
10006             var cc = String.fromCharCode(event.getCharCode());
10007             this.setValue( event.shiftKey ?  cc : cc.toLowerCase());
10008             
10009         }
10010     },
10011     adjustWidth : function(tag, w){
10012         tag = tag.toLowerCase();
10013         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
10014             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
10015                 if(tag == 'input'){
10016                     return w + 2;
10017                 }
10018                 if(tag == 'textarea'){
10019                     return w-2;
10020                 }
10021             }else if(Roo.isOpera){
10022                 if(tag == 'input'){
10023                     return w + 2;
10024                 }
10025                 if(tag == 'textarea'){
10026                     return w-2;
10027                 }
10028             }
10029         }
10030         return w;
10031     },
10032     
10033     setFieldLabel : function(v)
10034     {
10035         if(!this.rendered){
10036             return;
10037         }
10038         
10039         if(this.indicatorEl()){
10040             var ar = this.el.select('label > span',true);
10041             
10042             if (ar.elements.length) {
10043                 this.el.select('label > span',true).first().dom.innerHTML = (v === null || v === undefined ? '' : v);
10044                 this.fieldLabel = v;
10045                 return;
10046             }
10047             
10048             var br = this.el.select('label',true);
10049             
10050             if(br.elements.length) {
10051                 this.el.select('label',true).first().dom.innerHTML = (v === null || v === undefined ? '' : v);
10052                 this.fieldLabel = v;
10053                 return;
10054             }
10055             
10056             Roo.log('Cannot Found any of label > span || label in input');
10057             return;
10058         }
10059         
10060         this.el.select('label',true).first().dom.innerHTML = (v === null || v === undefined ? '' : v);
10061         this.fieldLabel = v;
10062         
10063         
10064     }
10065 });
10066
10067  
10068 /*
10069  * - LGPL
10070  *
10071  * Input
10072  * 
10073  */
10074
10075 /**
10076  * @class Roo.bootstrap.TextArea
10077  * @extends Roo.bootstrap.Input
10078  * Bootstrap TextArea class
10079  * @cfg {Number} cols Specifies the visible width of a text area
10080  * @cfg {Number} rows Specifies the visible number of lines in a text area
10081  * @cfg {string} wrap (soft|hard)Specifies how the text in a text area is to be wrapped when submitted in a form
10082  * @cfg {string} resize (none|both|horizontal|vertical|inherit|initial)
10083  * @cfg {string} html text
10084  * 
10085  * @constructor
10086  * Create a new TextArea
10087  * @param {Object} config The config object
10088  */
10089
10090 Roo.bootstrap.TextArea = function(config){
10091     Roo.bootstrap.TextArea.superclass.constructor.call(this, config);
10092    
10093 };
10094
10095 Roo.extend(Roo.bootstrap.TextArea, Roo.bootstrap.Input,  {
10096      
10097     cols : false,
10098     rows : 5,
10099     readOnly : false,
10100     warp : 'soft',
10101     resize : false,
10102     value: false,
10103     html: false,
10104     
10105     getAutoCreate : function(){
10106         
10107         var align = (!this.labelAlign) ? this.parentLabelAlign() : this.labelAlign;
10108         
10109         var id = Roo.id();
10110         
10111         var cfg = {};
10112         
10113         if(this.inputType != 'hidden'){
10114             cfg.cls = 'form-group' //input-group
10115         }
10116         
10117         var input =  {
10118             tag: 'textarea',
10119             id : id,
10120             warp : this.warp,
10121             rows : this.rows,
10122             value : this.value || '',
10123             html: this.html || '',
10124             cls : 'form-control',
10125             placeholder : this.placeholder || '' 
10126             
10127         };
10128         
10129         if(this.maxLength && this.maxLength != Number.MAX_VALUE){
10130             input.maxLength = this.maxLength;
10131         }
10132         
10133         if(this.resize){
10134             input.style = (typeof(input.style) == 'undefined') ? 'resize:' + this.resize : input.style + 'resize:' + this.resize;
10135         }
10136         
10137         if(this.cols){
10138             input.cols = this.cols;
10139         }
10140         
10141         if (this.readOnly) {
10142             input.readonly = true;
10143         }
10144         
10145         if (this.name) {
10146             input.name = this.name;
10147         }
10148         
10149         if (this.size) {
10150             input.cls = (typeof(input.cls) == 'undefined') ? 'input-' + this.size : input.cls + ' input-' + this.size;
10151         }
10152         
10153         var settings=this;
10154         ['xs','sm','md','lg'].map(function(size){
10155             if (settings[size]) {
10156                 cfg.cls += ' col-' + size + '-' + settings[size];
10157             }
10158         });
10159         
10160         var inputblock = input;
10161         
10162         if(this.hasFeedback && !this.allowBlank){
10163             
10164             var feedback = {
10165                 tag: 'span',
10166                 cls: 'glyphicon form-control-feedback'
10167             };
10168
10169             inputblock = {
10170                 cls : 'has-feedback',
10171                 cn :  [
10172                     input,
10173                     feedback
10174                 ] 
10175             };  
10176         }
10177         
10178         
10179         if (this.before || this.after) {
10180             
10181             inputblock = {
10182                 cls : 'input-group',
10183                 cn :  [] 
10184             };
10185             if (this.before) {
10186                 inputblock.cn.push({
10187                     tag :'span',
10188                     cls : 'input-group-addon',
10189                     html : this.before
10190                 });
10191             }
10192             
10193             inputblock.cn.push(input);
10194             
10195             if(this.hasFeedback && !this.allowBlank){
10196                 inputblock.cls += ' has-feedback';
10197                 inputblock.cn.push(feedback);
10198             }
10199             
10200             if (this.after) {
10201                 inputblock.cn.push({
10202                     tag :'span',
10203                     cls : 'input-group-addon',
10204                     html : this.after
10205                 });
10206             }
10207             
10208         }
10209         
10210         if (align ==='left' && this.fieldLabel.length) {
10211             cfg.cn = [
10212                 {
10213                     tag: 'label',
10214                     'for' :  id,
10215                     cls : 'control-label',
10216                     html : this.fieldLabel
10217                 },
10218                 {
10219                     cls : "",
10220                     cn: [
10221                         inputblock
10222                     ]
10223                 }
10224
10225             ];
10226             
10227             if(this.labelWidth > 12){
10228                 cfg.cn[0].style = "width: " + this.labelWidth + 'px';
10229             }
10230
10231             if(this.labelWidth < 13 && this.labelmd == 0){
10232                 this.labelmd = this.labelWidth;
10233             }
10234
10235             if(this.labellg > 0){
10236                 cfg.cn[0].cls += ' col-lg-' + this.labellg;
10237                 cfg.cn[1].cls += ' col-lg-' + (12 - this.labellg);
10238             }
10239
10240             if(this.labelmd > 0){
10241                 cfg.cn[0].cls += ' col-md-' + this.labelmd;
10242                 cfg.cn[1].cls += ' col-md-' + (12 - this.labelmd);
10243             }
10244
10245             if(this.labelsm > 0){
10246                 cfg.cn[0].cls += ' col-sm-' + this.labelsm;
10247                 cfg.cn[1].cls += ' col-sm-' + (12 - this.labelsm);
10248             }
10249
10250             if(this.labelxs > 0){
10251                 cfg.cn[0].cls += ' col-xs-' + this.labelxs;
10252                 cfg.cn[1].cls += ' col-xs-' + (12 - this.labelxs);
10253             }
10254             
10255         } else if ( this.fieldLabel.length) {
10256             cfg.cn = [
10257
10258                {
10259                    tag: 'label',
10260                    //cls : 'input-group-addon',
10261                    html : this.fieldLabel
10262
10263                },
10264
10265                inputblock
10266
10267            ];
10268
10269         } else {
10270
10271             cfg.cn = [
10272
10273                 inputblock
10274
10275             ];
10276                 
10277         }
10278         
10279         if (this.disabled) {
10280             input.disabled=true;
10281         }
10282         
10283         return cfg;
10284         
10285     },
10286     /**
10287      * return the real textarea element.
10288      */
10289     inputEl: function ()
10290     {
10291         return this.el.select('textarea.form-control',true).first();
10292     },
10293     
10294     /**
10295      * Clear any invalid styles/messages for this field
10296      */
10297     clearInvalid : function()
10298     {
10299         
10300         if(!this.el || this.preventMark){ // not rendered
10301             return;
10302         }
10303         
10304         var label = this.el.select('label', true).first();
10305         var icon = this.el.select('i.fa-star', true).first();
10306         
10307         if(label && icon){
10308             icon.remove();
10309         }
10310         this.el.removeClass( this.validClass);
10311         this.inputEl().removeClass('is-invalid');
10312          
10313         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
10314             
10315             var feedback = this.el.select('.form-control-feedback', true).first();
10316             
10317             if(feedback){
10318                 this.el.select('.form-control-feedback', true).first().removeClass(this.invalidFeedbackClass);
10319             }
10320             
10321         }
10322         
10323         this.fireEvent('valid', this);
10324     },
10325     
10326      /**
10327      * Mark this field as valid
10328      */
10329     markValid : function()
10330     {
10331         if(!this.el  || this.preventMark){ // not rendered
10332             return;
10333         }
10334         
10335         this.el.removeClass([this.invalidClass, this.validClass]);
10336         this.inputEl().removeClass(['is-valid', 'is-invalid']);
10337         
10338         var feedback = this.el.select('.form-control-feedback', true).first();
10339             
10340         if(feedback){
10341             this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
10342         }
10343
10344         if(this.disabled || this.allowBlank){
10345             return;
10346         }
10347         
10348         var label = this.el.select('label', true).first();
10349         var icon = this.el.select('i.fa-star', true).first();
10350         
10351         if(label && icon){
10352             icon.remove();
10353         }
10354         if (Roo.bootstrap.version == 3) {
10355             this.el.addClass(this.validClass);
10356         } else {
10357             this.inputEl().addClass('is-valid');
10358         }
10359         
10360         
10361         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank && (this.getValue().length || this.forceFeedback)){
10362             
10363             var feedback = this.el.select('.form-control-feedback', true).first();
10364             
10365             if(feedback){
10366                 this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
10367                 this.el.select('.form-control-feedback', true).first().addClass([this.validFeedbackClass]);
10368             }
10369             
10370         }
10371         
10372         this.fireEvent('valid', this);
10373     },
10374     
10375      /**
10376      * Mark this field as invalid
10377      * @param {String} msg The validation message
10378      */
10379     markInvalid : function(msg)
10380     {
10381         if(!this.el  || this.preventMark){ // not rendered
10382             return;
10383         }
10384         
10385         this.el.removeClass([this.invalidClass, this.validClass]);
10386         this.inputEl().removeClass(['is-valid', 'is-invalid']);
10387         
10388         var feedback = this.el.select('.form-control-feedback', true).first();
10389             
10390         if(feedback){
10391             this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
10392         }
10393
10394         if(this.disabled || this.allowBlank){
10395             return;
10396         }
10397         
10398         var label = this.el.select('label', true).first();
10399         var icon = this.el.select('i.fa-star', true).first();
10400         
10401         if(!this.getValue().length && label && !icon){
10402             this.el.createChild({
10403                 tag : 'i',
10404                 cls : 'text-danger fa fa-lg fa-star',
10405                 tooltip : 'This field is required',
10406                 style : 'margin-right:5px;'
10407             }, label, true);
10408         }
10409         
10410         if (Roo.bootstrap.version == 3) {
10411             this.el.addClass(this.invalidClass);
10412         } else {
10413             this.inputEl().addClass('is-invalid');
10414         }
10415         
10416         // fixme ... this may be depricated need to test..
10417         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
10418             
10419             var feedback = this.el.select('.form-control-feedback', true).first();
10420             
10421             if(feedback){
10422                 this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
10423                 
10424                 if(this.getValue().length || this.forceFeedback){
10425                     this.el.select('.form-control-feedback', true).first().addClass([this.invalidFeedbackClass]);
10426                 }
10427                 
10428             }
10429             
10430         }
10431         
10432         this.fireEvent('invalid', this, msg);
10433     }
10434 });
10435
10436  
10437 /*
10438  * - LGPL
10439  *
10440  * trigger field - base class for combo..
10441  * 
10442  */
10443  
10444 /**
10445  * @class Roo.bootstrap.TriggerField
10446  * @extends Roo.bootstrap.Input
10447  * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
10448  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
10449  * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
10450  * for which you can provide a custom implementation.  For example:
10451  * <pre><code>
10452 var trigger = new Roo.bootstrap.TriggerField();
10453 trigger.onTriggerClick = myTriggerFn;
10454 trigger.applyTo('my-field');
10455 </code></pre>
10456  *
10457  * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
10458  * {@link Roo.bootstrap.DateField} and {@link Roo.bootstrap.ComboBox} are perfect examples of this.
10459  * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
10460  * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
10461  * @cfg {String} caret (search|calendar) BS3 only - carat fa name
10462
10463  * @constructor
10464  * Create a new TriggerField.
10465  * @param {Object} config Configuration options (valid {@Roo.bootstrap.Input} config options will also be applied
10466  * to the base TextField)
10467  */
10468 Roo.bootstrap.TriggerField = function(config){
10469     this.mimicing = false;
10470     Roo.bootstrap.TriggerField.superclass.constructor.call(this, config);
10471 };
10472
10473 Roo.extend(Roo.bootstrap.TriggerField, Roo.bootstrap.Input,  {
10474     /**
10475      * @cfg {String} triggerClass A CSS class to apply to the trigger
10476      */
10477      /**
10478      * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
10479      */
10480     hideTrigger:false,
10481
10482     /**
10483      * @cfg {Boolean} removable (true|false) special filter default false
10484      */
10485     removable : false,
10486     
10487     /** @cfg {Boolean} grow @hide */
10488     /** @cfg {Number} growMin @hide */
10489     /** @cfg {Number} growMax @hide */
10490
10491     /**
10492      * @hide 
10493      * @method
10494      */
10495     autoSize: Roo.emptyFn,
10496     // private
10497     monitorTab : true,
10498     // private
10499     deferHeight : true,
10500
10501     
10502     actionMode : 'wrap',
10503     
10504     caret : false,
10505     
10506     
10507     getAutoCreate : function(){
10508        
10509         var align = this.labelAlign || this.parentLabelAlign();
10510         
10511         var id = Roo.id();
10512         
10513         var cfg = {
10514             cls: 'form-group' //input-group
10515         };
10516         
10517         
10518         var input =  {
10519             tag: 'input',
10520             id : id,
10521             type : this.inputType,
10522             cls : 'form-control',
10523             autocomplete: 'new-password',
10524             placeholder : this.placeholder || '' 
10525             
10526         };
10527         if (this.name) {
10528             input.name = this.name;
10529         }
10530         if (this.size) {
10531             input.cls += ' input-' + this.size;
10532         }
10533         
10534         if (this.disabled) {
10535             input.disabled=true;
10536         }
10537         
10538         var inputblock = input;
10539         
10540         if(this.hasFeedback && !this.allowBlank){
10541             
10542             var feedback = {
10543                 tag: 'span',
10544                 cls: 'glyphicon form-control-feedback'
10545             };
10546             
10547             if(this.removable && !this.editable && !this.tickable){
10548                 inputblock = {
10549                     cls : 'has-feedback',
10550                     cn :  [
10551                         inputblock,
10552                         {
10553                             tag: 'button',
10554                             html : 'x',
10555                             cls : 'roo-combo-removable-btn close'
10556                         },
10557                         feedback
10558                     ] 
10559                 };
10560             } else {
10561                 inputblock = {
10562                     cls : 'has-feedback',
10563                     cn :  [
10564                         inputblock,
10565                         feedback
10566                     ] 
10567                 };
10568             }
10569
10570         } else {
10571             if(this.removable && !this.editable && !this.tickable){
10572                 inputblock = {
10573                     cls : 'roo-removable',
10574                     cn :  [
10575                         inputblock,
10576                         {
10577                             tag: 'button',
10578                             html : 'x',
10579                             cls : 'roo-combo-removable-btn close'
10580                         }
10581                     ] 
10582                 };
10583             }
10584         }
10585         
10586         if (this.before || this.after) {
10587             
10588             inputblock = {
10589                 cls : 'input-group',
10590                 cn :  [] 
10591             };
10592             if (this.before) {
10593                 inputblock.cn.push({
10594                     tag :'span',
10595                     cls : 'input-group-addon input-group-prepend input-group-text',
10596                     html : this.before
10597                 });
10598             }
10599             
10600             inputblock.cn.push(input);
10601             
10602             if(this.hasFeedback && !this.allowBlank){
10603                 inputblock.cls += ' has-feedback';
10604                 inputblock.cn.push(feedback);
10605             }
10606             
10607             if (this.after) {
10608                 inputblock.cn.push({
10609                     tag :'span',
10610                     cls : 'input-group-addon input-group-append input-group-text',
10611                     html : this.after
10612                 });
10613             }
10614             
10615         };
10616         
10617       
10618         
10619         var ibwrap = inputblock;
10620         
10621         if(this.multiple){
10622             ibwrap = {
10623                 tag: 'ul',
10624                 cls: 'roo-select2-choices',
10625                 cn:[
10626                     {
10627                         tag: 'li',
10628                         cls: 'roo-select2-search-field',
10629                         cn: [
10630
10631                             inputblock
10632                         ]
10633                     }
10634                 ]
10635             };
10636                 
10637         }
10638         
10639         var combobox = {
10640             cls: 'roo-select2-container input-group',
10641             cn: [
10642                  {
10643                     tag: 'input',
10644                     type : 'hidden',
10645                     cls: 'form-hidden-field'
10646                 },
10647                 ibwrap
10648             ]
10649         };
10650         
10651         if(!this.multiple && this.showToggleBtn){
10652             
10653             var caret = {
10654                         tag: 'span',
10655                         cls: 'caret'
10656              };
10657             if (this.caret != false) {
10658                 caret = {
10659                      tag: 'i',
10660                      cls: 'fa fa-' + this.caret
10661                 };
10662                 
10663             }
10664             
10665             combobox.cn.push({
10666                 tag :'span',
10667                 cls : 'input-group-addon input-group-append input-group-text btn dropdown-toggle',
10668                 cn : [
10669                     Roo.bootstrap.version == 3 ? caret : '',
10670                     {
10671                         tag: 'span',
10672                         cls: 'combobox-clear',
10673                         cn  : [
10674                             {
10675                                 tag : 'i',
10676                                 cls: 'icon-remove'
10677                             }
10678                         ]
10679                     }
10680                 ]
10681
10682             })
10683         }
10684         
10685         if(this.multiple){
10686             combobox.cls += ' roo-select2-container-multi';
10687         }
10688          var indicator = {
10689             tag : 'i',
10690             cls : 'roo-required-indicator ' + (this.indicatorpos == 'right'  ? 'right' : 'left') +'-indicator text-danger fa fa-lg fa-star',
10691             tooltip : 'This field is required'
10692         };
10693         if (Roo.bootstrap.version == 4) {
10694             indicator = {
10695                 tag : 'i',
10696                 style : 'display:none'
10697             };
10698         }
10699         
10700         
10701         if (align ==='left' && this.fieldLabel.length) {
10702             
10703             cfg.cls += ' roo-form-group-label-left'  + (Roo.bootstrap.version == 4 ? ' row' : '');
10704
10705             cfg.cn = [
10706                 indicator,
10707                 {
10708                     tag: 'label',
10709                     'for' :  id,
10710                     cls : 'control-label',
10711                     html : this.fieldLabel
10712
10713                 },
10714                 {
10715                     cls : "", 
10716                     cn: [
10717                         combobox
10718                     ]
10719                 }
10720
10721             ];
10722             
10723             var labelCfg = cfg.cn[1];
10724             var contentCfg = cfg.cn[2];
10725             
10726             if(this.indicatorpos == 'right'){
10727                 cfg.cn = [
10728                     {
10729                         tag: 'label',
10730                         'for' :  id,
10731                         cls : 'control-label',
10732                         cn : [
10733                             {
10734                                 tag : 'span',
10735                                 html : this.fieldLabel
10736                             },
10737                             indicator
10738                         ]
10739                     },
10740                     {
10741                         cls : "", 
10742                         cn: [
10743                             combobox
10744                         ]
10745                     }
10746
10747                 ];
10748                 
10749                 labelCfg = cfg.cn[0];
10750                 contentCfg = cfg.cn[1];
10751             }
10752             
10753             if(this.labelWidth > 12){
10754                 labelCfg.style = "width: " + this.labelWidth + 'px';
10755             }
10756             
10757             if(this.labelWidth < 13 && this.labelmd == 0){
10758                 this.labelmd = this.labelWidth;
10759             }
10760             
10761             if(this.labellg > 0){
10762                 labelCfg.cls += ' col-lg-' + this.labellg;
10763                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
10764             }
10765             
10766             if(this.labelmd > 0){
10767                 labelCfg.cls += ' col-md-' + this.labelmd;
10768                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
10769             }
10770             
10771             if(this.labelsm > 0){
10772                 labelCfg.cls += ' col-sm-' + this.labelsm;
10773                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
10774             }
10775             
10776             if(this.labelxs > 0){
10777                 labelCfg.cls += ' col-xs-' + this.labelxs;
10778                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
10779             }
10780             
10781         } else if ( this.fieldLabel.length) {
10782 //                Roo.log(" label");
10783             cfg.cn = [
10784                 indicator,
10785                {
10786                    tag: 'label',
10787                    //cls : 'input-group-addon',
10788                    html : this.fieldLabel
10789
10790                },
10791
10792                combobox
10793
10794             ];
10795             
10796             if(this.indicatorpos == 'right'){
10797                 
10798                 cfg.cn = [
10799                     {
10800                        tag: 'label',
10801                        cn : [
10802                            {
10803                                tag : 'span',
10804                                html : this.fieldLabel
10805                            },
10806                            indicator
10807                        ]
10808
10809                     },
10810                     combobox
10811
10812                 ];
10813
10814             }
10815
10816         } else {
10817             
10818 //                Roo.log(" no label && no align");
10819                 cfg = combobox
10820                      
10821                 
10822         }
10823         
10824         var settings=this;
10825         ['xs','sm','md','lg'].map(function(size){
10826             if (settings[size]) {
10827                 cfg.cls += ' col-' + size + '-' + settings[size];
10828             }
10829         });
10830         
10831         return cfg;
10832         
10833     },
10834     
10835     
10836     
10837     // private
10838     onResize : function(w, h){
10839 //        Roo.bootstrap.TriggerField.superclass.onResize.apply(this, arguments);
10840 //        if(typeof w == 'number'){
10841 //            var x = w - this.trigger.getWidth();
10842 //            this.inputEl().setWidth(this.adjustWidth('input', x));
10843 //            this.trigger.setStyle('left', x+'px');
10844 //        }
10845     },
10846
10847     // private
10848     adjustSize : Roo.BoxComponent.prototype.adjustSize,
10849
10850     // private
10851     getResizeEl : function(){
10852         return this.inputEl();
10853     },
10854
10855     // private
10856     getPositionEl : function(){
10857         return this.inputEl();
10858     },
10859
10860     // private
10861     alignErrorIcon : function(){
10862         this.errorIcon.alignTo(this.inputEl(), 'tl-tr', [2, 0]);
10863     },
10864
10865     // private
10866     initEvents : function(){
10867         
10868         this.createList();
10869         
10870         Roo.bootstrap.TriggerField.superclass.initEvents.call(this);
10871         //this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
10872         if(!this.multiple && this.showToggleBtn){
10873             this.trigger = this.el.select('span.dropdown-toggle',true).first();
10874             if(this.hideTrigger){
10875                 this.trigger.setDisplayed(false);
10876             }
10877             this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
10878         }
10879         
10880         if(this.multiple){
10881             this.inputEl().on("click", this.onTriggerClick, this, {preventDefault:true});
10882         }
10883         
10884         if(this.removable && !this.editable && !this.tickable){
10885             var close = this.closeTriggerEl();
10886             
10887             if(close){
10888                 close.setVisibilityMode(Roo.Element.DISPLAY).hide();
10889                 close.on('click', this.removeBtnClick, this, close);
10890             }
10891         }
10892         
10893         //this.trigger.addClassOnOver('x-form-trigger-over');
10894         //this.trigger.addClassOnClick('x-form-trigger-click');
10895         
10896         //if(!this.width){
10897         //    this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
10898         //}
10899     },
10900     
10901     closeTriggerEl : function()
10902     {
10903         var close = this.el.select('.roo-combo-removable-btn', true).first();
10904         return close ? close : false;
10905     },
10906     
10907     removeBtnClick : function(e, h, el)
10908     {
10909         e.preventDefault();
10910         
10911         if(this.fireEvent("remove", this) !== false){
10912             this.reset();
10913             this.fireEvent("afterremove", this)
10914         }
10915     },
10916     
10917     createList : function()
10918     {
10919         this.list = Roo.get(document.body).createChild({
10920             tag: Roo.bootstrap.version == 4 ? 'div' : 'ul',
10921             cls: 'typeahead typeahead-long dropdown-menu',
10922             style: 'display:none'
10923         });
10924         
10925         this.list.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';;
10926         
10927     },
10928
10929     // private
10930     initTrigger : function(){
10931        
10932     },
10933
10934     // private
10935     onDestroy : function(){
10936         if(this.trigger){
10937             this.trigger.removeAllListeners();
10938           //  this.trigger.remove();
10939         }
10940         //if(this.wrap){
10941         //    this.wrap.remove();
10942         //}
10943         Roo.bootstrap.TriggerField.superclass.onDestroy.call(this);
10944     },
10945
10946     // private
10947     onFocus : function(){
10948         Roo.bootstrap.TriggerField.superclass.onFocus.call(this);
10949         /*
10950         if(!this.mimicing){
10951             this.wrap.addClass('x-trigger-wrap-focus');
10952             this.mimicing = true;
10953             Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
10954             if(this.monitorTab){
10955                 this.el.on("keydown", this.checkTab, this);
10956             }
10957         }
10958         */
10959     },
10960
10961     // private
10962     checkTab : function(e){
10963         if(e.getKey() == e.TAB){
10964             this.triggerBlur();
10965         }
10966     },
10967
10968     // private
10969     onBlur : function(){
10970         // do nothing
10971     },
10972
10973     // private
10974     mimicBlur : function(e, t){
10975         /*
10976         if(!this.wrap.contains(t) && this.validateBlur()){
10977             this.triggerBlur();
10978         }
10979         */
10980     },
10981
10982     // private
10983     triggerBlur : function(){
10984         this.mimicing = false;
10985         Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
10986         if(this.monitorTab){
10987             this.el.un("keydown", this.checkTab, this);
10988         }
10989         //this.wrap.removeClass('x-trigger-wrap-focus');
10990         Roo.bootstrap.TriggerField.superclass.onBlur.call(this);
10991     },
10992
10993     // private
10994     // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
10995     validateBlur : function(e, t){
10996         return true;
10997     },
10998
10999     // private
11000     onDisable : function(){
11001         this.inputEl().dom.disabled = true;
11002         //Roo.bootstrap.TriggerField.superclass.onDisable.call(this);
11003         //if(this.wrap){
11004         //    this.wrap.addClass('x-item-disabled');
11005         //}
11006     },
11007
11008     // private
11009     onEnable : function(){
11010         this.inputEl().dom.disabled = false;
11011         //Roo.bootstrap.TriggerField.superclass.onEnable.call(this);
11012         //if(this.wrap){
11013         //    this.el.removeClass('x-item-disabled');
11014         //}
11015     },
11016
11017     // private
11018     onShow : function(){
11019         var ae = this.getActionEl();
11020         
11021         if(ae){
11022             ae.dom.style.display = '';
11023             ae.dom.style.visibility = 'visible';
11024         }
11025     },
11026
11027     // private
11028     
11029     onHide : function(){
11030         var ae = this.getActionEl();
11031         ae.dom.style.display = 'none';
11032     },
11033
11034     /**
11035      * The function that should handle the trigger's click event.  This method does nothing by default until overridden
11036      * by an implementing function.
11037      * @method
11038      * @param {EventObject} e
11039      */
11040     onTriggerClick : Roo.emptyFn
11041 });
11042  /*
11043  * Based on:
11044  * Ext JS Library 1.1.1
11045  * Copyright(c) 2006-2007, Ext JS, LLC.
11046  *
11047  * Originally Released Under LGPL - original licence link has changed is not relivant.
11048  *
11049  * Fork - LGPL
11050  * <script type="text/javascript">
11051  */
11052
11053
11054 /**
11055  * @class Roo.data.SortTypes
11056  * @singleton
11057  * Defines the default sorting (casting?) comparison functions used when sorting data.
11058  */
11059 Roo.data.SortTypes = {
11060     /**
11061      * Default sort that does nothing
11062      * @param {Mixed} s The value being converted
11063      * @return {Mixed} The comparison value
11064      */
11065     none : function(s){
11066         return s;
11067     },
11068     
11069     /**
11070      * The regular expression used to strip tags
11071      * @type {RegExp}
11072      * @property
11073      */
11074     stripTagsRE : /<\/?[^>]+>/gi,
11075     
11076     /**
11077      * Strips all HTML tags to sort on text only
11078      * @param {Mixed} s The value being converted
11079      * @return {String} The comparison value
11080      */
11081     asText : function(s){
11082         return String(s).replace(this.stripTagsRE, "");
11083     },
11084     
11085     /**
11086      * Strips all HTML tags to sort on text only - Case insensitive
11087      * @param {Mixed} s The value being converted
11088      * @return {String} The comparison value
11089      */
11090     asUCText : function(s){
11091         return String(s).toUpperCase().replace(this.stripTagsRE, "");
11092     },
11093     
11094     /**
11095      * Case insensitive string
11096      * @param {Mixed} s The value being converted
11097      * @return {String} The comparison value
11098      */
11099     asUCString : function(s) {
11100         return String(s).toUpperCase();
11101     },
11102     
11103     /**
11104      * Date sorting
11105      * @param {Mixed} s The value being converted
11106      * @return {Number} The comparison value
11107      */
11108     asDate : function(s) {
11109         if(!s){
11110             return 0;
11111         }
11112         if(s instanceof Date){
11113             return s.getTime();
11114         }
11115         return Date.parse(String(s));
11116     },
11117     
11118     /**
11119      * Float sorting
11120      * @param {Mixed} s The value being converted
11121      * @return {Float} The comparison value
11122      */
11123     asFloat : function(s) {
11124         var val = parseFloat(String(s).replace(/,/g, ""));
11125         if(isNaN(val)) {
11126             val = 0;
11127         }
11128         return val;
11129     },
11130     
11131     /**
11132      * Integer sorting
11133      * @param {Mixed} s The value being converted
11134      * @return {Number} The comparison value
11135      */
11136     asInt : function(s) {
11137         var val = parseInt(String(s).replace(/,/g, ""));
11138         if(isNaN(val)) {
11139             val = 0;
11140         }
11141         return val;
11142     }
11143 };/*
11144  * Based on:
11145  * Ext JS Library 1.1.1
11146  * Copyright(c) 2006-2007, Ext JS, LLC.
11147  *
11148  * Originally Released Under LGPL - original licence link has changed is not relivant.
11149  *
11150  * Fork - LGPL
11151  * <script type="text/javascript">
11152  */
11153
11154 /**
11155 * @class Roo.data.Record
11156  * Instances of this class encapsulate both record <em>definition</em> information, and record
11157  * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
11158  * to access Records cached in an {@link Roo.data.Store} object.<br>
11159  * <p>
11160  * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
11161  * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
11162  * objects.<br>
11163  * <p>
11164  * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
11165  * @constructor
11166  * This constructor should not be used to create Record objects. Instead, use the constructor generated by
11167  * {@link #create}. The parameters are the same.
11168  * @param {Array} data An associative Array of data values keyed by the field name.
11169  * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
11170  * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
11171  * not specified an integer id is generated.
11172  */
11173 Roo.data.Record = function(data, id){
11174     this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
11175     this.data = data;
11176 };
11177
11178 /**
11179  * Generate a constructor for a specific record layout.
11180  * @param {Array} o An Array of field definition objects which specify field names, and optionally,
11181  * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
11182  * Each field definition object may contain the following properties: <ul>
11183  * <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,
11184  * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
11185  * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
11186  * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
11187  * is being used, then this is a string containing the javascript expression to reference the data relative to 
11188  * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
11189  * to the data item relative to the record element. If the mapping expression is the same as the field name,
11190  * this may be omitted.</p></li>
11191  * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
11192  * <ul><li>auto (Default, implies no conversion)</li>
11193  * <li>string</li>
11194  * <li>int</li>
11195  * <li>float</li>
11196  * <li>boolean</li>
11197  * <li>date</li></ul></p></li>
11198  * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
11199  * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
11200  * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
11201  * by the Reader into an object that will be stored in the Record. It is passed the
11202  * following parameters:<ul>
11203  * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
11204  * </ul></p></li>
11205  * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
11206  * </ul>
11207  * <br>usage:<br><pre><code>
11208 var TopicRecord = Roo.data.Record.create(
11209     {name: 'title', mapping: 'topic_title'},
11210     {name: 'author', mapping: 'username'},
11211     {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
11212     {name: 'lastPost', mapping: 'post_time', type: 'date'},
11213     {name: 'lastPoster', mapping: 'user2'},
11214     {name: 'excerpt', mapping: 'post_text'}
11215 );
11216
11217 var myNewRecord = new TopicRecord({
11218     title: 'Do my job please',
11219     author: 'noobie',
11220     totalPosts: 1,
11221     lastPost: new Date(),
11222     lastPoster: 'Animal',
11223     excerpt: 'No way dude!'
11224 });
11225 myStore.add(myNewRecord);
11226 </code></pre>
11227  * @method create
11228  * @static
11229  */
11230 Roo.data.Record.create = function(o){
11231     var f = function(){
11232         f.superclass.constructor.apply(this, arguments);
11233     };
11234     Roo.extend(f, Roo.data.Record);
11235     var p = f.prototype;
11236     p.fields = new Roo.util.MixedCollection(false, function(field){
11237         return field.name;
11238     });
11239     for(var i = 0, len = o.length; i < len; i++){
11240         p.fields.add(new Roo.data.Field(o[i]));
11241     }
11242     f.getField = function(name){
11243         return p.fields.get(name);  
11244     };
11245     return f;
11246 };
11247
11248 Roo.data.Record.AUTO_ID = 1000;
11249 Roo.data.Record.EDIT = 'edit';
11250 Roo.data.Record.REJECT = 'reject';
11251 Roo.data.Record.COMMIT = 'commit';
11252
11253 Roo.data.Record.prototype = {
11254     /**
11255      * Readonly flag - true if this record has been modified.
11256      * @type Boolean
11257      */
11258     dirty : false,
11259     editing : false,
11260     error: null,
11261     modified: null,
11262
11263     // private
11264     join : function(store){
11265         this.store = store;
11266     },
11267
11268     /**
11269      * Set the named field to the specified value.
11270      * @param {String} name The name of the field to set.
11271      * @param {Object} value The value to set the field to.
11272      */
11273     set : function(name, value){
11274         if(this.data[name] == value){
11275             return;
11276         }
11277         this.dirty = true;
11278         if(!this.modified){
11279             this.modified = {};
11280         }
11281         if(typeof this.modified[name] == 'undefined'){
11282             this.modified[name] = this.data[name];
11283         }
11284         this.data[name] = value;
11285         if(!this.editing && this.store){
11286             this.store.afterEdit(this);
11287         }       
11288     },
11289
11290     /**
11291      * Get the value of the named field.
11292      * @param {String} name The name of the field to get the value of.
11293      * @return {Object} The value of the field.
11294      */
11295     get : function(name){
11296         return this.data[name]; 
11297     },
11298
11299     // private
11300     beginEdit : function(){
11301         this.editing = true;
11302         this.modified = {}; 
11303     },
11304
11305     // private
11306     cancelEdit : function(){
11307         this.editing = false;
11308         delete this.modified;
11309     },
11310
11311     // private
11312     endEdit : function(){
11313         this.editing = false;
11314         if(this.dirty && this.store){
11315             this.store.afterEdit(this);
11316         }
11317     },
11318
11319     /**
11320      * Usually called by the {@link Roo.data.Store} which owns the Record.
11321      * Rejects all changes made to the Record since either creation, or the last commit operation.
11322      * Modified fields are reverted to their original values.
11323      * <p>
11324      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
11325      * of reject operations.
11326      */
11327     reject : function(){
11328         var m = this.modified;
11329         for(var n in m){
11330             if(typeof m[n] != "function"){
11331                 this.data[n] = m[n];
11332             }
11333         }
11334         this.dirty = false;
11335         delete this.modified;
11336         this.editing = false;
11337         if(this.store){
11338             this.store.afterReject(this);
11339         }
11340     },
11341
11342     /**
11343      * Usually called by the {@link Roo.data.Store} which owns the Record.
11344      * Commits all changes made to the Record since either creation, or the last commit operation.
11345      * <p>
11346      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
11347      * of commit operations.
11348      */
11349     commit : function(){
11350         this.dirty = false;
11351         delete this.modified;
11352         this.editing = false;
11353         if(this.store){
11354             this.store.afterCommit(this);
11355         }
11356     },
11357
11358     // private
11359     hasError : function(){
11360         return this.error != null;
11361     },
11362
11363     // private
11364     clearError : function(){
11365         this.error = null;
11366     },
11367
11368     /**
11369      * Creates a copy of this record.
11370      * @param {String} id (optional) A new record id if you don't want to use this record's id
11371      * @return {Record}
11372      */
11373     copy : function(newId) {
11374         return new this.constructor(Roo.apply({}, this.data), newId || this.id);
11375     }
11376 };/*
11377  * Based on:
11378  * Ext JS Library 1.1.1
11379  * Copyright(c) 2006-2007, Ext JS, LLC.
11380  *
11381  * Originally Released Under LGPL - original licence link has changed is not relivant.
11382  *
11383  * Fork - LGPL
11384  * <script type="text/javascript">
11385  */
11386
11387
11388
11389 /**
11390  * @class Roo.data.Store
11391  * @extends Roo.util.Observable
11392  * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
11393  * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
11394  * <p>
11395  * 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
11396  * has no knowledge of the format of the data returned by the Proxy.<br>
11397  * <p>
11398  * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
11399  * instances from the data object. These records are cached and made available through accessor functions.
11400  * @constructor
11401  * Creates a new Store.
11402  * @param {Object} config A config object containing the objects needed for the Store to access data,
11403  * and read the data into Records.
11404  */
11405 Roo.data.Store = function(config){
11406     this.data = new Roo.util.MixedCollection(false);
11407     this.data.getKey = function(o){
11408         return o.id;
11409     };
11410     this.baseParams = {};
11411     // private
11412     this.paramNames = {
11413         "start" : "start",
11414         "limit" : "limit",
11415         "sort" : "sort",
11416         "dir" : "dir",
11417         "multisort" : "_multisort"
11418     };
11419
11420     if(config && config.data){
11421         this.inlineData = config.data;
11422         delete config.data;
11423     }
11424
11425     Roo.apply(this, config);
11426     
11427     if(this.reader){ // reader passed
11428         this.reader = Roo.factory(this.reader, Roo.data);
11429         this.reader.xmodule = this.xmodule || false;
11430         if(!this.recordType){
11431             this.recordType = this.reader.recordType;
11432         }
11433         if(this.reader.onMetaChange){
11434             this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
11435         }
11436     }
11437
11438     if(this.recordType){
11439         this.fields = this.recordType.prototype.fields;
11440     }
11441     this.modified = [];
11442
11443     this.addEvents({
11444         /**
11445          * @event datachanged
11446          * Fires when the data cache has changed, and a widget which is using this Store
11447          * as a Record cache should refresh its view.
11448          * @param {Store} this
11449          */
11450         datachanged : true,
11451         /**
11452          * @event metachange
11453          * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
11454          * @param {Store} this
11455          * @param {Object} meta The JSON metadata
11456          */
11457         metachange : true,
11458         /**
11459          * @event add
11460          * Fires when Records have been added to the Store
11461          * @param {Store} this
11462          * @param {Roo.data.Record[]} records The array of Records added
11463          * @param {Number} index The index at which the record(s) were added
11464          */
11465         add : true,
11466         /**
11467          * @event remove
11468          * Fires when a Record has been removed from the Store
11469          * @param {Store} this
11470          * @param {Roo.data.Record} record The Record that was removed
11471          * @param {Number} index The index at which the record was removed
11472          */
11473         remove : true,
11474         /**
11475          * @event update
11476          * Fires when a Record has been updated
11477          * @param {Store} this
11478          * @param {Roo.data.Record} record The Record that was updated
11479          * @param {String} operation The update operation being performed.  Value may be one of:
11480          * <pre><code>
11481  Roo.data.Record.EDIT
11482  Roo.data.Record.REJECT
11483  Roo.data.Record.COMMIT
11484          * </code></pre>
11485          */
11486         update : true,
11487         /**
11488          * @event clear
11489          * Fires when the data cache has been cleared.
11490          * @param {Store} this
11491          */
11492         clear : true,
11493         /**
11494          * @event beforeload
11495          * Fires before a request is made for a new data object.  If the beforeload handler returns false
11496          * the load action will be canceled.
11497          * @param {Store} this
11498          * @param {Object} options The loading options that were specified (see {@link #load} for details)
11499          */
11500         beforeload : true,
11501         /**
11502          * @event beforeloadadd
11503          * Fires after a new set of Records has been loaded.
11504          * @param {Store} this
11505          * @param {Roo.data.Record[]} records The Records that were loaded
11506          * @param {Object} options The loading options that were specified (see {@link #load} for details)
11507          */
11508         beforeloadadd : true,
11509         /**
11510          * @event load
11511          * Fires after a new set of Records has been loaded, before they are added to the store.
11512          * @param {Store} this
11513          * @param {Roo.data.Record[]} records The Records that were loaded
11514          * @param {Object} options The loading options that were specified (see {@link #load} for details)
11515          * @params {Object} return from reader
11516          */
11517         load : true,
11518         /**
11519          * @event loadexception
11520          * Fires if an exception occurs in the Proxy during loading.
11521          * Called with the signature of the Proxy's "loadexception" event.
11522          * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
11523          * 
11524          * @param {Proxy} 
11525          * @param {Object} return from JsonData.reader() - success, totalRecords, records
11526          * @param {Object} load options 
11527          * @param {Object} jsonData from your request (normally this contains the Exception)
11528          */
11529         loadexception : true
11530     });
11531     
11532     if(this.proxy){
11533         this.proxy = Roo.factory(this.proxy, Roo.data);
11534         this.proxy.xmodule = this.xmodule || false;
11535         this.relayEvents(this.proxy,  ["loadexception"]);
11536     }
11537     this.sortToggle = {};
11538     this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
11539
11540     Roo.data.Store.superclass.constructor.call(this);
11541
11542     if(this.inlineData){
11543         this.loadData(this.inlineData);
11544         delete this.inlineData;
11545     }
11546 };
11547
11548 Roo.extend(Roo.data.Store, Roo.util.Observable, {
11549      /**
11550     * @cfg {boolean} isLocal   flag if data is locally available (and can be always looked up
11551     * without a remote query - used by combo/forms at present.
11552     */
11553     
11554     /**
11555     * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
11556     */
11557     /**
11558     * @cfg {Array} data Inline data to be loaded when the store is initialized.
11559     */
11560     /**
11561     * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
11562     * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
11563     */
11564     /**
11565     * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
11566     * on any HTTP request
11567     */
11568     /**
11569     * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
11570     */
11571     /**
11572     * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
11573     */
11574     multiSort: false,
11575     /**
11576     * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
11577     * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
11578     */
11579     remoteSort : false,
11580
11581     /**
11582     * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
11583      * loaded or when a record is removed. (defaults to false).
11584     */
11585     pruneModifiedRecords : false,
11586
11587     // private
11588     lastOptions : null,
11589
11590     /**
11591      * Add Records to the Store and fires the add event.
11592      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
11593      */
11594     add : function(records){
11595         records = [].concat(records);
11596         for(var i = 0, len = records.length; i < len; i++){
11597             records[i].join(this);
11598         }
11599         var index = this.data.length;
11600         this.data.addAll(records);
11601         this.fireEvent("add", this, records, index);
11602     },
11603
11604     /**
11605      * Remove a Record from the Store and fires the remove event.
11606      * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
11607      */
11608     remove : function(record){
11609         var index = this.data.indexOf(record);
11610         this.data.removeAt(index);
11611  
11612         if(this.pruneModifiedRecords){
11613             this.modified.remove(record);
11614         }
11615         this.fireEvent("remove", this, record, index);
11616     },
11617
11618     /**
11619      * Remove all Records from the Store and fires the clear event.
11620      */
11621     removeAll : function(){
11622         this.data.clear();
11623         if(this.pruneModifiedRecords){
11624             this.modified = [];
11625         }
11626         this.fireEvent("clear", this);
11627     },
11628
11629     /**
11630      * Inserts Records to the Store at the given index and fires the add event.
11631      * @param {Number} index The start index at which to insert the passed Records.
11632      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
11633      */
11634     insert : function(index, records){
11635         records = [].concat(records);
11636         for(var i = 0, len = records.length; i < len; i++){
11637             this.data.insert(index, records[i]);
11638             records[i].join(this);
11639         }
11640         this.fireEvent("add", this, records, index);
11641     },
11642
11643     /**
11644      * Get the index within the cache of the passed Record.
11645      * @param {Roo.data.Record} record The Roo.data.Record object to to find.
11646      * @return {Number} The index of the passed Record. Returns -1 if not found.
11647      */
11648     indexOf : function(record){
11649         return this.data.indexOf(record);
11650     },
11651
11652     /**
11653      * Get the index within the cache of the Record with the passed id.
11654      * @param {String} id The id of the Record to find.
11655      * @return {Number} The index of the Record. Returns -1 if not found.
11656      */
11657     indexOfId : function(id){
11658         return this.data.indexOfKey(id);
11659     },
11660
11661     /**
11662      * Get the Record with the specified id.
11663      * @param {String} id The id of the Record to find.
11664      * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
11665      */
11666     getById : function(id){
11667         return this.data.key(id);
11668     },
11669
11670     /**
11671      * Get the Record at the specified index.
11672      * @param {Number} index The index of the Record to find.
11673      * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
11674      */
11675     getAt : function(index){
11676         return this.data.itemAt(index);
11677     },
11678
11679     /**
11680      * Returns a range of Records between specified indices.
11681      * @param {Number} startIndex (optional) The starting index (defaults to 0)
11682      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
11683      * @return {Roo.data.Record[]} An array of Records
11684      */
11685     getRange : function(start, end){
11686         return this.data.getRange(start, end);
11687     },
11688
11689     // private
11690     storeOptions : function(o){
11691         o = Roo.apply({}, o);
11692         delete o.callback;
11693         delete o.scope;
11694         this.lastOptions = o;
11695     },
11696
11697     /**
11698      * Loads the Record cache from the configured Proxy using the configured Reader.
11699      * <p>
11700      * If using remote paging, then the first load call must specify the <em>start</em>
11701      * and <em>limit</em> properties in the options.params property to establish the initial
11702      * position within the dataset, and the number of Records to cache on each read from the Proxy.
11703      * <p>
11704      * <strong>It is important to note that for remote data sources, loading is asynchronous,
11705      * and this call will return before the new data has been loaded. Perform any post-processing
11706      * in a callback function, or in a "load" event handler.</strong>
11707      * <p>
11708      * @param {Object} options An object containing properties which control loading options:<ul>
11709      * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
11710      * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
11711      * passed the following arguments:<ul>
11712      * <li>r : Roo.data.Record[]</li>
11713      * <li>options: Options object from the load call</li>
11714      * <li>success: Boolean success indicator</li></ul></li>
11715      * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
11716      * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
11717      * </ul>
11718      */
11719     load : function(options){
11720         options = options || {};
11721         if(this.fireEvent("beforeload", this, options) !== false){
11722             this.storeOptions(options);
11723             var p = Roo.apply(options.params || {}, this.baseParams);
11724             // if meta was not loaded from remote source.. try requesting it.
11725             if (!this.reader.metaFromRemote) {
11726                 p._requestMeta = 1;
11727             }
11728             if(this.sortInfo && this.remoteSort){
11729                 var pn = this.paramNames;
11730                 p[pn["sort"]] = this.sortInfo.field;
11731                 p[pn["dir"]] = this.sortInfo.direction;
11732             }
11733             if (this.multiSort) {
11734                 var pn = this.paramNames;
11735                 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
11736             }
11737             
11738             this.proxy.load(p, this.reader, this.loadRecords, this, options);
11739         }
11740     },
11741
11742     /**
11743      * Reloads the Record cache from the configured Proxy using the configured Reader and
11744      * the options from the last load operation performed.
11745      * @param {Object} options (optional) An object containing properties which may override the options
11746      * used in the last load operation. See {@link #load} for details (defaults to null, in which case
11747      * the most recently used options are reused).
11748      */
11749     reload : function(options){
11750         this.load(Roo.applyIf(options||{}, this.lastOptions));
11751     },
11752
11753     // private
11754     // Called as a callback by the Reader during a load operation.
11755     loadRecords : function(o, options, success){
11756         if(!o || success === false){
11757             if(success !== false){
11758                 this.fireEvent("load", this, [], options, o);
11759             }
11760             if(options.callback){
11761                 options.callback.call(options.scope || this, [], options, false);
11762             }
11763             return;
11764         }
11765         // if data returned failure - throw an exception.
11766         if (o.success === false) {
11767             // show a message if no listener is registered.
11768             if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
11769                     Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
11770             }
11771             // loadmask wil be hooked into this..
11772             this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
11773             return;
11774         }
11775         var r = o.records, t = o.totalRecords || r.length;
11776         
11777         this.fireEvent("beforeloadadd", this, r, options, o);
11778         
11779         if(!options || options.add !== true){
11780             if(this.pruneModifiedRecords){
11781                 this.modified = [];
11782             }
11783             for(var i = 0, len = r.length; i < len; i++){
11784                 r[i].join(this);
11785             }
11786             if(this.snapshot){
11787                 this.data = this.snapshot;
11788                 delete this.snapshot;
11789             }
11790             this.data.clear();
11791             this.data.addAll(r);
11792             this.totalLength = t;
11793             this.applySort();
11794             this.fireEvent("datachanged", this);
11795         }else{
11796             this.totalLength = Math.max(t, this.data.length+r.length);
11797             this.add(r);
11798         }
11799         
11800         if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
11801                 
11802             var e = new Roo.data.Record({});
11803
11804             e.set(this.parent.displayField, this.parent.emptyTitle);
11805             e.set(this.parent.valueField, '');
11806
11807             this.insert(0, e);
11808         }
11809             
11810         this.fireEvent("load", this, r, options, o);
11811         if(options.callback){
11812             options.callback.call(options.scope || this, r, options, true);
11813         }
11814     },
11815
11816
11817     /**
11818      * Loads data from a passed data block. A Reader which understands the format of the data
11819      * must have been configured in the constructor.
11820      * @param {Object} data The data block from which to read the Records.  The format of the data expected
11821      * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
11822      * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
11823      */
11824     loadData : function(o, append){
11825         var r = this.reader.readRecords(o);
11826         this.loadRecords(r, {add: append}, true);
11827     },
11828
11829     /**
11830      * Gets the number of cached records.
11831      * <p>
11832      * <em>If using paging, this may not be the total size of the dataset. If the data object
11833      * used by the Reader contains the dataset size, then the getTotalCount() function returns
11834      * the data set size</em>
11835      */
11836     getCount : function(){
11837         return this.data.length || 0;
11838     },
11839
11840     /**
11841      * Gets the total number of records in the dataset as returned by the server.
11842      * <p>
11843      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
11844      * the dataset size</em>
11845      */
11846     getTotalCount : function(){
11847         return this.totalLength || 0;
11848     },
11849
11850     /**
11851      * Returns the sort state of the Store as an object with two properties:
11852      * <pre><code>
11853  field {String} The name of the field by which the Records are sorted
11854  direction {String} The sort order, "ASC" or "DESC"
11855      * </code></pre>
11856      */
11857     getSortState : function(){
11858         return this.sortInfo;
11859     },
11860
11861     // private
11862     applySort : function(){
11863         if(this.sortInfo && !this.remoteSort){
11864             var s = this.sortInfo, f = s.field;
11865             var st = this.fields.get(f).sortType;
11866             var fn = function(r1, r2){
11867                 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
11868                 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
11869             };
11870             this.data.sort(s.direction, fn);
11871             if(this.snapshot && this.snapshot != this.data){
11872                 this.snapshot.sort(s.direction, fn);
11873             }
11874         }
11875     },
11876
11877     /**
11878      * Sets the default sort column and order to be used by the next load operation.
11879      * @param {String} fieldName The name of the field to sort by.
11880      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
11881      */
11882     setDefaultSort : function(field, dir){
11883         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
11884     },
11885
11886     /**
11887      * Sort the Records.
11888      * If remote sorting is used, the sort is performed on the server, and the cache is
11889      * reloaded. If local sorting is used, the cache is sorted internally.
11890      * @param {String} fieldName The name of the field to sort by.
11891      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
11892      */
11893     sort : function(fieldName, dir){
11894         var f = this.fields.get(fieldName);
11895         if(!dir){
11896             this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
11897             
11898             if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
11899                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
11900             }else{
11901                 dir = f.sortDir;
11902             }
11903         }
11904         this.sortToggle[f.name] = dir;
11905         this.sortInfo = {field: f.name, direction: dir};
11906         if(!this.remoteSort){
11907             this.applySort();
11908             this.fireEvent("datachanged", this);
11909         }else{
11910             this.load(this.lastOptions);
11911         }
11912     },
11913
11914     /**
11915      * Calls the specified function for each of the Records in the cache.
11916      * @param {Function} fn The function to call. The Record is passed as the first parameter.
11917      * Returning <em>false</em> aborts and exits the iteration.
11918      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
11919      */
11920     each : function(fn, scope){
11921         this.data.each(fn, scope);
11922     },
11923
11924     /**
11925      * Gets all records modified since the last commit.  Modified records are persisted across load operations
11926      * (e.g., during paging).
11927      * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
11928      */
11929     getModifiedRecords : function(){
11930         return this.modified;
11931     },
11932
11933     // private
11934     createFilterFn : function(property, value, anyMatch){
11935         if(!value.exec){ // not a regex
11936             value = String(value);
11937             if(value.length == 0){
11938                 return false;
11939             }
11940             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
11941         }
11942         return function(r){
11943             return value.test(r.data[property]);
11944         };
11945     },
11946
11947     /**
11948      * Sums the value of <i>property</i> for each record between start and end and returns the result.
11949      * @param {String} property A field on your records
11950      * @param {Number} start The record index to start at (defaults to 0)
11951      * @param {Number} end The last record index to include (defaults to length - 1)
11952      * @return {Number} The sum
11953      */
11954     sum : function(property, start, end){
11955         var rs = this.data.items, v = 0;
11956         start = start || 0;
11957         end = (end || end === 0) ? end : rs.length-1;
11958
11959         for(var i = start; i <= end; i++){
11960             v += (rs[i].data[property] || 0);
11961         }
11962         return v;
11963     },
11964
11965     /**
11966      * Filter the records by a specified property.
11967      * @param {String} field A field on your records
11968      * @param {String/RegExp} value Either a string that the field
11969      * should start with or a RegExp to test against the field
11970      * @param {Boolean} anyMatch True to match any part not just the beginning
11971      */
11972     filter : function(property, value, anyMatch){
11973         var fn = this.createFilterFn(property, value, anyMatch);
11974         return fn ? this.filterBy(fn) : this.clearFilter();
11975     },
11976
11977     /**
11978      * Filter by a function. The specified function will be called with each
11979      * record in this data source. If the function returns true the record is included,
11980      * otherwise it is filtered.
11981      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
11982      * @param {Object} scope (optional) The scope of the function (defaults to this)
11983      */
11984     filterBy : function(fn, scope){
11985         this.snapshot = this.snapshot || this.data;
11986         this.data = this.queryBy(fn, scope||this);
11987         this.fireEvent("datachanged", this);
11988     },
11989
11990     /**
11991      * Query the records by a specified property.
11992      * @param {String} field A field on your records
11993      * @param {String/RegExp} value Either a string that the field
11994      * should start with or a RegExp to test against the field
11995      * @param {Boolean} anyMatch True to match any part not just the beginning
11996      * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
11997      */
11998     query : function(property, value, anyMatch){
11999         var fn = this.createFilterFn(property, value, anyMatch);
12000         return fn ? this.queryBy(fn) : this.data.clone();
12001     },
12002
12003     /**
12004      * Query by a function. The specified function will be called with each
12005      * record in this data source. If the function returns true the record is included
12006      * in the results.
12007      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
12008      * @param {Object} scope (optional) The scope of the function (defaults to this)
12009       @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
12010      **/
12011     queryBy : function(fn, scope){
12012         var data = this.snapshot || this.data;
12013         return data.filterBy(fn, scope||this);
12014     },
12015
12016     /**
12017      * Collects unique values for a particular dataIndex from this store.
12018      * @param {String} dataIndex The property to collect
12019      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
12020      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
12021      * @return {Array} An array of the unique values
12022      **/
12023     collect : function(dataIndex, allowNull, bypassFilter){
12024         var d = (bypassFilter === true && this.snapshot) ?
12025                 this.snapshot.items : this.data.items;
12026         var v, sv, r = [], l = {};
12027         for(var i = 0, len = d.length; i < len; i++){
12028             v = d[i].data[dataIndex];
12029             sv = String(v);
12030             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
12031                 l[sv] = true;
12032                 r[r.length] = v;
12033             }
12034         }
12035         return r;
12036     },
12037
12038     /**
12039      * Revert to a view of the Record cache with no filtering applied.
12040      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
12041      */
12042     clearFilter : function(suppressEvent){
12043         if(this.snapshot && this.snapshot != this.data){
12044             this.data = this.snapshot;
12045             delete this.snapshot;
12046             if(suppressEvent !== true){
12047                 this.fireEvent("datachanged", this);
12048             }
12049         }
12050     },
12051
12052     // private
12053     afterEdit : function(record){
12054         if(this.modified.indexOf(record) == -1){
12055             this.modified.push(record);
12056         }
12057         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
12058     },
12059     
12060     // private
12061     afterReject : function(record){
12062         this.modified.remove(record);
12063         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
12064     },
12065
12066     // private
12067     afterCommit : function(record){
12068         this.modified.remove(record);
12069         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
12070     },
12071
12072     /**
12073      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
12074      * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
12075      */
12076     commitChanges : function(){
12077         var m = this.modified.slice(0);
12078         this.modified = [];
12079         for(var i = 0, len = m.length; i < len; i++){
12080             m[i].commit();
12081         }
12082     },
12083
12084     /**
12085      * Cancel outstanding changes on all changed records.
12086      */
12087     rejectChanges : function(){
12088         var m = this.modified.slice(0);
12089         this.modified = [];
12090         for(var i = 0, len = m.length; i < len; i++){
12091             m[i].reject();
12092         }
12093     },
12094
12095     onMetaChange : function(meta, rtype, o){
12096         this.recordType = rtype;
12097         this.fields = rtype.prototype.fields;
12098         delete this.snapshot;
12099         this.sortInfo = meta.sortInfo || this.sortInfo;
12100         this.modified = [];
12101         this.fireEvent('metachange', this, this.reader.meta);
12102     },
12103     
12104     moveIndex : function(data, type)
12105     {
12106         var index = this.indexOf(data);
12107         
12108         var newIndex = index + type;
12109         
12110         this.remove(data);
12111         
12112         this.insert(newIndex, data);
12113         
12114     }
12115 });/*
12116  * Based on:
12117  * Ext JS Library 1.1.1
12118  * Copyright(c) 2006-2007, Ext JS, LLC.
12119  *
12120  * Originally Released Under LGPL - original licence link has changed is not relivant.
12121  *
12122  * Fork - LGPL
12123  * <script type="text/javascript">
12124  */
12125
12126 /**
12127  * @class Roo.data.SimpleStore
12128  * @extends Roo.data.Store
12129  * Small helper class to make creating Stores from Array data easier.
12130  * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
12131  * @cfg {Array} fields An array of field definition objects, or field name strings.
12132  * @cfg {Array} data The multi-dimensional array of data
12133  * @constructor
12134  * @param {Object} config
12135  */
12136 Roo.data.SimpleStore = function(config){
12137     Roo.data.SimpleStore.superclass.constructor.call(this, {
12138         isLocal : true,
12139         reader: new Roo.data.ArrayReader({
12140                 id: config.id
12141             },
12142             Roo.data.Record.create(config.fields)
12143         ),
12144         proxy : new Roo.data.MemoryProxy(config.data)
12145     });
12146     this.load();
12147 };
12148 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
12149  * Based on:
12150  * Ext JS Library 1.1.1
12151  * Copyright(c) 2006-2007, Ext JS, LLC.
12152  *
12153  * Originally Released Under LGPL - original licence link has changed is not relivant.
12154  *
12155  * Fork - LGPL
12156  * <script type="text/javascript">
12157  */
12158
12159 /**
12160 /**
12161  * @extends Roo.data.Store
12162  * @class Roo.data.JsonStore
12163  * Small helper class to make creating Stores for JSON data easier. <br/>
12164 <pre><code>
12165 var store = new Roo.data.JsonStore({
12166     url: 'get-images.php',
12167     root: 'images',
12168     fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
12169 });
12170 </code></pre>
12171  * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
12172  * JsonReader and HttpProxy (unless inline data is provided).</b>
12173  * @cfg {Array} fields An array of field definition objects, or field name strings.
12174  * @constructor
12175  * @param {Object} config
12176  */
12177 Roo.data.JsonStore = function(c){
12178     Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
12179         proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
12180         reader: new Roo.data.JsonReader(c, c.fields)
12181     }));
12182 };
12183 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
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  
12195 Roo.data.Field = function(config){
12196     if(typeof config == "string"){
12197         config = {name: config};
12198     }
12199     Roo.apply(this, config);
12200     
12201     if(!this.type){
12202         this.type = "auto";
12203     }
12204     
12205     var st = Roo.data.SortTypes;
12206     // named sortTypes are supported, here we look them up
12207     if(typeof this.sortType == "string"){
12208         this.sortType = st[this.sortType];
12209     }
12210     
12211     // set default sortType for strings and dates
12212     if(!this.sortType){
12213         switch(this.type){
12214             case "string":
12215                 this.sortType = st.asUCString;
12216                 break;
12217             case "date":
12218                 this.sortType = st.asDate;
12219                 break;
12220             default:
12221                 this.sortType = st.none;
12222         }
12223     }
12224
12225     // define once
12226     var stripRe = /[\$,%]/g;
12227
12228     // prebuilt conversion function for this field, instead of
12229     // switching every time we're reading a value
12230     if(!this.convert){
12231         var cv, dateFormat = this.dateFormat;
12232         switch(this.type){
12233             case "":
12234             case "auto":
12235             case undefined:
12236                 cv = function(v){ return v; };
12237                 break;
12238             case "string":
12239                 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
12240                 break;
12241             case "int":
12242                 cv = function(v){
12243                     return v !== undefined && v !== null && v !== '' ?
12244                            parseInt(String(v).replace(stripRe, ""), 10) : '';
12245                     };
12246                 break;
12247             case "float":
12248                 cv = function(v){
12249                     return v !== undefined && v !== null && v !== '' ?
12250                            parseFloat(String(v).replace(stripRe, ""), 10) : ''; 
12251                     };
12252                 break;
12253             case "bool":
12254             case "boolean":
12255                 cv = function(v){ return v === true || v === "true" || v == 1; };
12256                 break;
12257             case "date":
12258                 cv = function(v){
12259                     if(!v){
12260                         return '';
12261                     }
12262                     if(v instanceof Date){
12263                         return v;
12264                     }
12265                     if(dateFormat){
12266                         if(dateFormat == "timestamp"){
12267                             return new Date(v*1000);
12268                         }
12269                         return Date.parseDate(v, dateFormat);
12270                     }
12271                     var parsed = Date.parse(v);
12272                     return parsed ? new Date(parsed) : null;
12273                 };
12274              break;
12275             
12276         }
12277         this.convert = cv;
12278     }
12279 };
12280
12281 Roo.data.Field.prototype = {
12282     dateFormat: null,
12283     defaultValue: "",
12284     mapping: null,
12285     sortType : null,
12286     sortDir : "ASC"
12287 };/*
12288  * Based on:
12289  * Ext JS Library 1.1.1
12290  * Copyright(c) 2006-2007, Ext JS, LLC.
12291  *
12292  * Originally Released Under LGPL - original licence link has changed is not relivant.
12293  *
12294  * Fork - LGPL
12295  * <script type="text/javascript">
12296  */
12297  
12298 // Base class for reading structured data from a data source.  This class is intended to be
12299 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
12300
12301 /**
12302  * @class Roo.data.DataReader
12303  * Base class for reading structured data from a data source.  This class is intended to be
12304  * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
12305  */
12306
12307 Roo.data.DataReader = function(meta, recordType){
12308     
12309     this.meta = meta;
12310     
12311     this.recordType = recordType instanceof Array ? 
12312         Roo.data.Record.create(recordType) : recordType;
12313 };
12314
12315 Roo.data.DataReader.prototype = {
12316      /**
12317      * Create an empty record
12318      * @param {Object} data (optional) - overlay some values
12319      * @return {Roo.data.Record} record created.
12320      */
12321     newRow :  function(d) {
12322         var da =  {};
12323         this.recordType.prototype.fields.each(function(c) {
12324             switch( c.type) {
12325                 case 'int' : da[c.name] = 0; break;
12326                 case 'date' : da[c.name] = new Date(); break;
12327                 case 'float' : da[c.name] = 0.0; break;
12328                 case 'boolean' : da[c.name] = false; break;
12329                 default : da[c.name] = ""; break;
12330             }
12331             
12332         });
12333         return new this.recordType(Roo.apply(da, d));
12334     }
12335     
12336 };/*
12337  * Based on:
12338  * Ext JS Library 1.1.1
12339  * Copyright(c) 2006-2007, Ext JS, LLC.
12340  *
12341  * Originally Released Under LGPL - original licence link has changed is not relivant.
12342  *
12343  * Fork - LGPL
12344  * <script type="text/javascript">
12345  */
12346
12347 /**
12348  * @class Roo.data.DataProxy
12349  * @extends Roo.data.Observable
12350  * This class is an abstract base class for implementations which provide retrieval of
12351  * unformatted data objects.<br>
12352  * <p>
12353  * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
12354  * (of the appropriate type which knows how to parse the data object) to provide a block of
12355  * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
12356  * <p>
12357  * Custom implementations must implement the load method as described in
12358  * {@link Roo.data.HttpProxy#load}.
12359  */
12360 Roo.data.DataProxy = function(){
12361     this.addEvents({
12362         /**
12363          * @event beforeload
12364          * Fires before a network request is made to retrieve a data object.
12365          * @param {Object} This DataProxy object.
12366          * @param {Object} params The params parameter to the load function.
12367          */
12368         beforeload : true,
12369         /**
12370          * @event load
12371          * Fires before the load method's callback is called.
12372          * @param {Object} This DataProxy object.
12373          * @param {Object} o The data object.
12374          * @param {Object} arg The callback argument object passed to the load function.
12375          */
12376         load : true,
12377         /**
12378          * @event loadexception
12379          * Fires if an Exception occurs during data retrieval.
12380          * @param {Object} This DataProxy object.
12381          * @param {Object} o The data object.
12382          * @param {Object} arg The callback argument object passed to the load function.
12383          * @param {Object} e The Exception.
12384          */
12385         loadexception : true
12386     });
12387     Roo.data.DataProxy.superclass.constructor.call(this);
12388 };
12389
12390 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
12391
12392     /**
12393      * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
12394      */
12395 /*
12396  * Based on:
12397  * Ext JS Library 1.1.1
12398  * Copyright(c) 2006-2007, Ext JS, LLC.
12399  *
12400  * Originally Released Under LGPL - original licence link has changed is not relivant.
12401  *
12402  * Fork - LGPL
12403  * <script type="text/javascript">
12404  */
12405 /**
12406  * @class Roo.data.MemoryProxy
12407  * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
12408  * to the Reader when its load method is called.
12409  * @constructor
12410  * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
12411  */
12412 Roo.data.MemoryProxy = function(data){
12413     if (data.data) {
12414         data = data.data;
12415     }
12416     Roo.data.MemoryProxy.superclass.constructor.call(this);
12417     this.data = data;
12418 };
12419
12420 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
12421     
12422     /**
12423      * Load data from the requested source (in this case an in-memory
12424      * data object passed to the constructor), read the data object into
12425      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
12426      * process that block using the passed callback.
12427      * @param {Object} params This parameter is not used by the MemoryProxy class.
12428      * @param {Roo.data.DataReader} reader The Reader object which converts the data
12429      * object into a block of Roo.data.Records.
12430      * @param {Function} callback The function into which to pass the block of Roo.data.records.
12431      * The function must be passed <ul>
12432      * <li>The Record block object</li>
12433      * <li>The "arg" argument from the load function</li>
12434      * <li>A boolean success indicator</li>
12435      * </ul>
12436      * @param {Object} scope The scope in which to call the callback
12437      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
12438      */
12439     load : function(params, reader, callback, scope, arg){
12440         params = params || {};
12441         var result;
12442         try {
12443             result = reader.readRecords(params.data ? params.data :this.data);
12444         }catch(e){
12445             this.fireEvent("loadexception", this, arg, null, e);
12446             callback.call(scope, null, arg, false);
12447             return;
12448         }
12449         callback.call(scope, result, arg, true);
12450     },
12451     
12452     // private
12453     update : function(params, records){
12454         
12455     }
12456 });/*
12457  * Based on:
12458  * Ext JS Library 1.1.1
12459  * Copyright(c) 2006-2007, Ext JS, LLC.
12460  *
12461  * Originally Released Under LGPL - original licence link has changed is not relivant.
12462  *
12463  * Fork - LGPL
12464  * <script type="text/javascript">
12465  */
12466 /**
12467  * @class Roo.data.HttpProxy
12468  * @extends Roo.data.DataProxy
12469  * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
12470  * configured to reference a certain URL.<br><br>
12471  * <p>
12472  * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
12473  * from which the running page was served.<br><br>
12474  * <p>
12475  * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
12476  * <p>
12477  * Be aware that to enable the browser to parse an XML document, the server must set
12478  * the Content-Type header in the HTTP response to "text/xml".
12479  * @constructor
12480  * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
12481  * an {@link Roo.data.Connection} object.  If a Connection config is passed, the singleton {@link Roo.Ajax} object
12482  * will be used to make the request.
12483  */
12484 Roo.data.HttpProxy = function(conn){
12485     Roo.data.HttpProxy.superclass.constructor.call(this);
12486     // is conn a conn config or a real conn?
12487     this.conn = conn;
12488     this.useAjax = !conn || !conn.events;
12489   
12490 };
12491
12492 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
12493     // thse are take from connection...
12494     
12495     /**
12496      * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
12497      */
12498     /**
12499      * @cfg {Object} extraParams (Optional) An object containing properties which are used as
12500      * extra parameters to each request made by this object. (defaults to undefined)
12501      */
12502     /**
12503      * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
12504      *  to each request made by this object. (defaults to undefined)
12505      */
12506     /**
12507      * @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
12508      */
12509     /**
12510      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12511      */
12512      /**
12513      * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
12514      * @type Boolean
12515      */
12516   
12517
12518     /**
12519      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12520      * @type Boolean
12521      */
12522     /**
12523      * Return the {@link Roo.data.Connection} object being used by this Proxy.
12524      * @return {Connection} The Connection object. This object may be used to subscribe to events on
12525      * a finer-grained basis than the DataProxy events.
12526      */
12527     getConnection : function(){
12528         return this.useAjax ? Roo.Ajax : this.conn;
12529     },
12530
12531     /**
12532      * Load data from the configured {@link Roo.data.Connection}, read the data object into
12533      * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
12534      * process that block using the passed callback.
12535      * @param {Object} params An object containing properties which are to be used as HTTP parameters
12536      * for the request to the remote server.
12537      * @param {Roo.data.DataReader} reader The Reader object which converts the data
12538      * object into a block of Roo.data.Records.
12539      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
12540      * The function must be passed <ul>
12541      * <li>The Record block object</li>
12542      * <li>The "arg" argument from the load function</li>
12543      * <li>A boolean success indicator</li>
12544      * </ul>
12545      * @param {Object} scope The scope in which to call the callback
12546      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
12547      */
12548     load : function(params, reader, callback, scope, arg){
12549         if(this.fireEvent("beforeload", this, params) !== false){
12550             var  o = {
12551                 params : params || {},
12552                 request: {
12553                     callback : callback,
12554                     scope : scope,
12555                     arg : arg
12556                 },
12557                 reader: reader,
12558                 callback : this.loadResponse,
12559                 scope: this
12560             };
12561             if(this.useAjax){
12562                 Roo.applyIf(o, this.conn);
12563                 if(this.activeRequest){
12564                     Roo.Ajax.abort(this.activeRequest);
12565                 }
12566                 this.activeRequest = Roo.Ajax.request(o);
12567             }else{
12568                 this.conn.request(o);
12569             }
12570         }else{
12571             callback.call(scope||this, null, arg, false);
12572         }
12573     },
12574
12575     // private
12576     loadResponse : function(o, success, response){
12577         delete this.activeRequest;
12578         if(!success){
12579             this.fireEvent("loadexception", this, o, response);
12580             o.request.callback.call(o.request.scope, null, o.request.arg, false);
12581             return;
12582         }
12583         var result;
12584         try {
12585             result = o.reader.read(response);
12586         }catch(e){
12587             this.fireEvent("loadexception", this, o, response, e);
12588             o.request.callback.call(o.request.scope, null, o.request.arg, false);
12589             return;
12590         }
12591         
12592         this.fireEvent("load", this, o, o.request.arg);
12593         o.request.callback.call(o.request.scope, result, o.request.arg, true);
12594     },
12595
12596     // private
12597     update : function(dataSet){
12598
12599     },
12600
12601     // private
12602     updateResponse : function(dataSet){
12603
12604     }
12605 });/*
12606  * Based on:
12607  * Ext JS Library 1.1.1
12608  * Copyright(c) 2006-2007, Ext JS, LLC.
12609  *
12610  * Originally Released Under LGPL - original licence link has changed is not relivant.
12611  *
12612  * Fork - LGPL
12613  * <script type="text/javascript">
12614  */
12615
12616 /**
12617  * @class Roo.data.ScriptTagProxy
12618  * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
12619  * other than the originating domain of the running page.<br><br>
12620  * <p>
12621  * <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
12622  * of the running page, you must use this class, rather than DataProxy.</em><br><br>
12623  * <p>
12624  * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
12625  * source code that is used as the source inside a &lt;script> tag.<br><br>
12626  * <p>
12627  * In order for the browser to process the returned data, the server must wrap the data object
12628  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
12629  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
12630  * depending on whether the callback name was passed:
12631  * <p>
12632  * <pre><code>
12633 boolean scriptTag = false;
12634 String cb = request.getParameter("callback");
12635 if (cb != null) {
12636     scriptTag = true;
12637     response.setContentType("text/javascript");
12638 } else {
12639     response.setContentType("application/x-json");
12640 }
12641 Writer out = response.getWriter();
12642 if (scriptTag) {
12643     out.write(cb + "(");
12644 }
12645 out.print(dataBlock.toJsonString());
12646 if (scriptTag) {
12647     out.write(");");
12648 }
12649 </pre></code>
12650  *
12651  * @constructor
12652  * @param {Object} config A configuration object.
12653  */
12654 Roo.data.ScriptTagProxy = function(config){
12655     Roo.data.ScriptTagProxy.superclass.constructor.call(this);
12656     Roo.apply(this, config);
12657     this.head = document.getElementsByTagName("head")[0];
12658 };
12659
12660 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
12661
12662 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
12663     /**
12664      * @cfg {String} url The URL from which to request the data object.
12665      */
12666     /**
12667      * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
12668      */
12669     timeout : 30000,
12670     /**
12671      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
12672      * the server the name of the callback function set up by the load call to process the returned data object.
12673      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
12674      * javascript output which calls this named function passing the data object as its only parameter.
12675      */
12676     callbackParam : "callback",
12677     /**
12678      *  @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
12679      * name to the request.
12680      */
12681     nocache : true,
12682
12683     /**
12684      * Load data from the configured URL, read the data object into
12685      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
12686      * process that block using the passed callback.
12687      * @param {Object} params An object containing properties which are to be used as HTTP parameters
12688      * for the request to the remote server.
12689      * @param {Roo.data.DataReader} reader The Reader object which converts the data
12690      * object into a block of Roo.data.Records.
12691      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
12692      * The function must be passed <ul>
12693      * <li>The Record block object</li>
12694      * <li>The "arg" argument from the load function</li>
12695      * <li>A boolean success indicator</li>
12696      * </ul>
12697      * @param {Object} scope The scope in which to call the callback
12698      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
12699      */
12700     load : function(params, reader, callback, scope, arg){
12701         if(this.fireEvent("beforeload", this, params) !== false){
12702
12703             var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
12704
12705             var url = this.url;
12706             url += (url.indexOf("?") != -1 ? "&" : "?") + p;
12707             if(this.nocache){
12708                 url += "&_dc=" + (new Date().getTime());
12709             }
12710             var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
12711             var trans = {
12712                 id : transId,
12713                 cb : "stcCallback"+transId,
12714                 scriptId : "stcScript"+transId,
12715                 params : params,
12716                 arg : arg,
12717                 url : url,
12718                 callback : callback,
12719                 scope : scope,
12720                 reader : reader
12721             };
12722             var conn = this;
12723
12724             window[trans.cb] = function(o){
12725                 conn.handleResponse(o, trans);
12726             };
12727
12728             url += String.format("&{0}={1}", this.callbackParam, trans.cb);
12729
12730             if(this.autoAbort !== false){
12731                 this.abort();
12732             }
12733
12734             trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
12735
12736             var script = document.createElement("script");
12737             script.setAttribute("src", url);
12738             script.setAttribute("type", "text/javascript");
12739             script.setAttribute("id", trans.scriptId);
12740             this.head.appendChild(script);
12741
12742             this.trans = trans;
12743         }else{
12744             callback.call(scope||this, null, arg, false);
12745         }
12746     },
12747
12748     // private
12749     isLoading : function(){
12750         return this.trans ? true : false;
12751     },
12752
12753     /**
12754      * Abort the current server request.
12755      */
12756     abort : function(){
12757         if(this.isLoading()){
12758             this.destroyTrans(this.trans);
12759         }
12760     },
12761
12762     // private
12763     destroyTrans : function(trans, isLoaded){
12764         this.head.removeChild(document.getElementById(trans.scriptId));
12765         clearTimeout(trans.timeoutId);
12766         if(isLoaded){
12767             window[trans.cb] = undefined;
12768             try{
12769                 delete window[trans.cb];
12770             }catch(e){}
12771         }else{
12772             // if hasn't been loaded, wait for load to remove it to prevent script error
12773             window[trans.cb] = function(){
12774                 window[trans.cb] = undefined;
12775                 try{
12776                     delete window[trans.cb];
12777                 }catch(e){}
12778             };
12779         }
12780     },
12781
12782     // private
12783     handleResponse : function(o, trans){
12784         this.trans = false;
12785         this.destroyTrans(trans, true);
12786         var result;
12787         try {
12788             result = trans.reader.readRecords(o);
12789         }catch(e){
12790             this.fireEvent("loadexception", this, o, trans.arg, e);
12791             trans.callback.call(trans.scope||window, null, trans.arg, false);
12792             return;
12793         }
12794         this.fireEvent("load", this, o, trans.arg);
12795         trans.callback.call(trans.scope||window, result, trans.arg, true);
12796     },
12797
12798     // private
12799     handleFailure : function(trans){
12800         this.trans = false;
12801         this.destroyTrans(trans, false);
12802         this.fireEvent("loadexception", this, null, trans.arg);
12803         trans.callback.call(trans.scope||window, null, trans.arg, false);
12804     }
12805 });/*
12806  * Based on:
12807  * Ext JS Library 1.1.1
12808  * Copyright(c) 2006-2007, Ext JS, LLC.
12809  *
12810  * Originally Released Under LGPL - original licence link has changed is not relivant.
12811  *
12812  * Fork - LGPL
12813  * <script type="text/javascript">
12814  */
12815
12816 /**
12817  * @class Roo.data.JsonReader
12818  * @extends Roo.data.DataReader
12819  * Data reader class to create an Array of Roo.data.Record objects from a JSON response
12820  * based on mappings in a provided Roo.data.Record constructor.
12821  * 
12822  * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
12823  * in the reply previously. 
12824  * 
12825  * <p>
12826  * Example code:
12827  * <pre><code>
12828 var RecordDef = Roo.data.Record.create([
12829     {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
12830     {name: 'occupation'}                 // This field will use "occupation" as the mapping.
12831 ]);
12832 var myReader = new Roo.data.JsonReader({
12833     totalProperty: "results",    // The property which contains the total dataset size (optional)
12834     root: "rows",                // The property which contains an Array of row objects
12835     id: "id"                     // The property within each row object that provides an ID for the record (optional)
12836 }, RecordDef);
12837 </code></pre>
12838  * <p>
12839  * This would consume a JSON file like this:
12840  * <pre><code>
12841 { 'results': 2, 'rows': [
12842     { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
12843     { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
12844 }
12845 </code></pre>
12846  * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
12847  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
12848  * paged from the remote server.
12849  * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
12850  * @cfg {String} root name of the property which contains the Array of row objects.
12851  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
12852  * @cfg {Array} fields Array of field definition objects
12853  * @constructor
12854  * Create a new JsonReader
12855  * @param {Object} meta Metadata configuration options
12856  * @param {Object} recordType Either an Array of field definition objects,
12857  * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
12858  */
12859 Roo.data.JsonReader = function(meta, recordType){
12860     
12861     meta = meta || {};
12862     // set some defaults:
12863     Roo.applyIf(meta, {
12864         totalProperty: 'total',
12865         successProperty : 'success',
12866         root : 'data',
12867         id : 'id'
12868     });
12869     
12870     Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
12871 };
12872 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
12873     
12874     /**
12875      * @prop {Boolean} metaFromRemote  - if the meta data was loaded from the remote source.
12876      * Used by Store query builder to append _requestMeta to params.
12877      * 
12878      */
12879     metaFromRemote : false,
12880     /**
12881      * This method is only used by a DataProxy which has retrieved data from a remote server.
12882      * @param {Object} response The XHR object which contains the JSON data in its responseText.
12883      * @return {Object} data A data block which is used by an Roo.data.Store object as
12884      * a cache of Roo.data.Records.
12885      */
12886     read : function(response){
12887         var json = response.responseText;
12888        
12889         var o = /* eval:var:o */ eval("("+json+")");
12890         if(!o) {
12891             throw {message: "JsonReader.read: Json object not found"};
12892         }
12893         
12894         if(o.metaData){
12895             
12896             delete this.ef;
12897             this.metaFromRemote = true;
12898             this.meta = o.metaData;
12899             this.recordType = Roo.data.Record.create(o.metaData.fields);
12900             this.onMetaChange(this.meta, this.recordType, o);
12901         }
12902         return this.readRecords(o);
12903     },
12904
12905     // private function a store will implement
12906     onMetaChange : function(meta, recordType, o){
12907
12908     },
12909
12910     /**
12911          * @ignore
12912          */
12913     simpleAccess: function(obj, subsc) {
12914         return obj[subsc];
12915     },
12916
12917         /**
12918          * @ignore
12919          */
12920     getJsonAccessor: function(){
12921         var re = /[\[\.]/;
12922         return function(expr) {
12923             try {
12924                 return(re.test(expr))
12925                     ? new Function("obj", "return obj." + expr)
12926                     : function(obj){
12927                         return obj[expr];
12928                     };
12929             } catch(e){}
12930             return Roo.emptyFn;
12931         };
12932     }(),
12933
12934     /**
12935      * Create a data block containing Roo.data.Records from an XML document.
12936      * @param {Object} o An object which contains an Array of row objects in the property specified
12937      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
12938      * which contains the total size of the dataset.
12939      * @return {Object} data A data block which is used by an Roo.data.Store object as
12940      * a cache of Roo.data.Records.
12941      */
12942     readRecords : function(o){
12943         /**
12944          * After any data loads, the raw JSON data is available for further custom processing.
12945          * @type Object
12946          */
12947         this.o = o;
12948         var s = this.meta, Record = this.recordType,
12949             f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
12950
12951 //      Generate extraction functions for the totalProperty, the root, the id, and for each field
12952         if (!this.ef) {
12953             if(s.totalProperty) {
12954                     this.getTotal = this.getJsonAccessor(s.totalProperty);
12955                 }
12956                 if(s.successProperty) {
12957                     this.getSuccess = this.getJsonAccessor(s.successProperty);
12958                 }
12959                 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
12960                 if (s.id) {
12961                         var g = this.getJsonAccessor(s.id);
12962                         this.getId = function(rec) {
12963                                 var r = g(rec);  
12964                                 return (r === undefined || r === "") ? null : r;
12965                         };
12966                 } else {
12967                         this.getId = function(){return null;};
12968                 }
12969             this.ef = [];
12970             for(var jj = 0; jj < fl; jj++){
12971                 f = fi[jj];
12972                 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
12973                 this.ef[jj] = this.getJsonAccessor(map);
12974             }
12975         }
12976
12977         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
12978         if(s.totalProperty){
12979             var vt = parseInt(this.getTotal(o), 10);
12980             if(!isNaN(vt)){
12981                 totalRecords = vt;
12982             }
12983         }
12984         if(s.successProperty){
12985             var vs = this.getSuccess(o);
12986             if(vs === false || vs === 'false'){
12987                 success = false;
12988             }
12989         }
12990         var records = [];
12991         for(var i = 0; i < c; i++){
12992                 var n = root[i];
12993             var values = {};
12994             var id = this.getId(n);
12995             for(var j = 0; j < fl; j++){
12996                 f = fi[j];
12997             var v = this.ef[j](n);
12998             if (!f.convert) {
12999                 Roo.log('missing convert for ' + f.name);
13000                 Roo.log(f);
13001                 continue;
13002             }
13003             values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
13004             }
13005             var record = new Record(values, id);
13006             record.json = n;
13007             records[i] = record;
13008         }
13009         return {
13010             raw : o,
13011             success : success,
13012             records : records,
13013             totalRecords : totalRecords
13014         };
13015     }
13016 });/*
13017  * Based on:
13018  * Ext JS Library 1.1.1
13019  * Copyright(c) 2006-2007, Ext JS, LLC.
13020  *
13021  * Originally Released Under LGPL - original licence link has changed is not relivant.
13022  *
13023  * Fork - LGPL
13024  * <script type="text/javascript">
13025  */
13026
13027 /**
13028  * @class Roo.data.ArrayReader
13029  * @extends Roo.data.DataReader
13030  * Data reader class to create an Array of Roo.data.Record objects from an Array.
13031  * Each element of that Array represents a row of data fields. The
13032  * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
13033  * of the field definition if it exists, or the field's ordinal position in the definition.<br>
13034  * <p>
13035  * Example code:.
13036  * <pre><code>
13037 var RecordDef = Roo.data.Record.create([
13038     {name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
13039     {name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.
13040 ]);
13041 var myReader = new Roo.data.ArrayReader({
13042     id: 0                     // The subscript within row Array that provides an ID for the Record (optional)
13043 }, RecordDef);
13044 </code></pre>
13045  * <p>
13046  * This would consume an Array like this:
13047  * <pre><code>
13048 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
13049   </code></pre>
13050  
13051  * @constructor
13052  * Create a new JsonReader
13053  * @param {Object} meta Metadata configuration options.
13054  * @param {Object|Array} recordType Either an Array of field definition objects
13055  * 
13056  * @cfg {Array} fields Array of field definition objects
13057  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
13058  * as specified to {@link Roo.data.Record#create},
13059  * or an {@link Roo.data.Record} object
13060  *
13061  * 
13062  * created using {@link Roo.data.Record#create}.
13063  */
13064 Roo.data.ArrayReader = function(meta, recordType){
13065     
13066      
13067     Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
13068 };
13069
13070 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
13071     /**
13072      * Create a data block containing Roo.data.Records from an XML document.
13073      * @param {Object} o An Array of row objects which represents the dataset.
13074      * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
13075      * a cache of Roo.data.Records.
13076      */
13077     readRecords : function(o){
13078         var sid = this.meta ? this.meta.id : null;
13079         var recordType = this.recordType, fields = recordType.prototype.fields;
13080         var records = [];
13081         var root = o;
13082             for(var i = 0; i < root.length; i++){
13083                     var n = root[i];
13084                 var values = {};
13085                 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
13086                 for(var j = 0, jlen = fields.length; j < jlen; j++){
13087                 var f = fields.items[j];
13088                 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
13089                 var v = n[k] !== undefined ? n[k] : f.defaultValue;
13090                 v = f.convert(v);
13091                 values[f.name] = v;
13092             }
13093                 var record = new recordType(values, id);
13094                 record.json = n;
13095                 records[records.length] = record;
13096             }
13097             return {
13098                 records : records,
13099                 totalRecords : records.length
13100             };
13101     }
13102 });/*
13103  * - LGPL
13104  * * 
13105  */
13106
13107 /**
13108  * @class Roo.bootstrap.ComboBox
13109  * @extends Roo.bootstrap.TriggerField
13110  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
13111  * @cfg {Boolean} append (true|false) default false
13112  * @cfg {Boolean} autoFocus (true|false) auto focus the first item, default true
13113  * @cfg {Boolean} tickable ComboBox with tickable selections (true|false), default false
13114  * @cfg {Boolean} triggerList trigger show the list or not (true|false) default true
13115  * @cfg {Boolean} showToggleBtn show toggle button or not (true|false) default true
13116  * @cfg {String} btnPosition set the position of the trigger button (left | right) default right
13117  * @cfg {Boolean} animate default true
13118  * @cfg {Boolean} emptyResultText only for touch device
13119  * @cfg {String} triggerText multiple combobox trigger button text default 'Select'
13120  * @cfg {String} emptyTitle default ''
13121  * @constructor
13122  * Create a new ComboBox.
13123  * @param {Object} config Configuration options
13124  */
13125 Roo.bootstrap.ComboBox = function(config){
13126     Roo.bootstrap.ComboBox.superclass.constructor.call(this, config);
13127     this.addEvents({
13128         /**
13129          * @event expand
13130          * Fires when the dropdown list is expanded
13131         * @param {Roo.bootstrap.ComboBox} combo This combo box
13132         */
13133         'expand' : true,
13134         /**
13135          * @event collapse
13136          * Fires when the dropdown list is collapsed
13137         * @param {Roo.bootstrap.ComboBox} combo This combo box
13138         */
13139         'collapse' : true,
13140         /**
13141          * @event beforeselect
13142          * Fires before a list item is selected. Return false to cancel the selection.
13143         * @param {Roo.bootstrap.ComboBox} combo This combo box
13144         * @param {Roo.data.Record} record The data record returned from the underlying store
13145         * @param {Number} index The index of the selected item in the dropdown list
13146         */
13147         'beforeselect' : true,
13148         /**
13149          * @event select
13150          * Fires when a list item is selected
13151         * @param {Roo.bootstrap.ComboBox} combo This combo box
13152         * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
13153         * @param {Number} index The index of the selected item in the dropdown list
13154         */
13155         'select' : true,
13156         /**
13157          * @event beforequery
13158          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
13159          * The event object passed has these properties:
13160         * @param {Roo.bootstrap.ComboBox} combo This combo box
13161         * @param {String} query The query
13162         * @param {Boolean} forceAll true to force "all" query
13163         * @param {Boolean} cancel true to cancel the query
13164         * @param {Object} e The query event object
13165         */
13166         'beforequery': true,
13167          /**
13168          * @event add
13169          * Fires when the 'add' icon is pressed (add a listener to enable add button)
13170         * @param {Roo.bootstrap.ComboBox} combo This combo box
13171         */
13172         'add' : true,
13173         /**
13174          * @event edit
13175          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
13176         * @param {Roo.bootstrap.ComboBox} combo This combo box
13177         * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
13178         */
13179         'edit' : true,
13180         /**
13181          * @event remove
13182          * Fires when the remove value from the combobox array
13183         * @param {Roo.bootstrap.ComboBox} combo This combo box
13184         */
13185         'remove' : true,
13186         /**
13187          * @event afterremove
13188          * Fires when the remove value from the combobox array
13189         * @param {Roo.bootstrap.ComboBox} combo This combo box
13190         */
13191         'afterremove' : true,
13192         /**
13193          * @event specialfilter
13194          * Fires when specialfilter
13195             * @param {Roo.bootstrap.ComboBox} combo This combo box
13196             */
13197         'specialfilter' : true,
13198         /**
13199          * @event tick
13200          * Fires when tick the element
13201             * @param {Roo.bootstrap.ComboBox} combo This combo box
13202             */
13203         'tick' : true,
13204         /**
13205          * @event touchviewdisplay
13206          * Fires when touch view require special display (default is using displayField)
13207             * @param {Roo.bootstrap.ComboBox} combo This combo box
13208             * @param {Object} cfg set html .
13209             */
13210         'touchviewdisplay' : true
13211         
13212     });
13213     
13214     this.item = [];
13215     this.tickItems = [];
13216     
13217     this.selectedIndex = -1;
13218     if(this.mode == 'local'){
13219         if(config.queryDelay === undefined){
13220             this.queryDelay = 10;
13221         }
13222         if(config.minChars === undefined){
13223             this.minChars = 0;
13224         }
13225     }
13226 };
13227
13228 Roo.extend(Roo.bootstrap.ComboBox, Roo.bootstrap.TriggerField, {
13229      
13230     /**
13231      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
13232      * rendering into an Roo.Editor, defaults to false)
13233      */
13234     /**
13235      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
13236      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
13237      */
13238     /**
13239      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
13240      */
13241     /**
13242      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
13243      * the dropdown list (defaults to undefined, with no header element)
13244      */
13245
13246      /**
13247      * @cfg {String/Roo.Template} tpl The template to use to render the output
13248      */
13249      
13250      /**
13251      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
13252      */
13253     listWidth: undefined,
13254     /**
13255      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
13256      * mode = 'remote' or 'text' if mode = 'local')
13257      */
13258     displayField: undefined,
13259     
13260     /**
13261      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
13262      * mode = 'remote' or 'value' if mode = 'local'). 
13263      * Note: use of a valueField requires the user make a selection
13264      * in order for a value to be mapped.
13265      */
13266     valueField: undefined,
13267     /**
13268      * @cfg {String} modalTitle The title of the dialog that pops up on mobile views.
13269      */
13270     modalTitle : '',
13271     
13272     /**
13273      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
13274      * field's data value (defaults to the underlying DOM element's name)
13275      */
13276     hiddenName: undefined,
13277     /**
13278      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
13279      */
13280     listClass: '',
13281     /**
13282      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
13283      */
13284     selectedClass: 'active',
13285     
13286     /**
13287      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
13288      */
13289     shadow:'sides',
13290     /**
13291      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
13292      * anchor positions (defaults to 'tl-bl')
13293      */
13294     listAlign: 'tl-bl?',
13295     /**
13296      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
13297      */
13298     maxHeight: 300,
13299     /**
13300      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
13301      * query specified by the allQuery config option (defaults to 'query')
13302      */
13303     triggerAction: 'query',
13304     /**
13305      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
13306      * (defaults to 4, does not apply if editable = false)
13307      */
13308     minChars : 4,
13309     /**
13310      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
13311      * delay (typeAheadDelay) if it matches a known value (defaults to false)
13312      */
13313     typeAhead: false,
13314     /**
13315      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
13316      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
13317      */
13318     queryDelay: 500,
13319     /**
13320      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
13321      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
13322      */
13323     pageSize: 0,
13324     /**
13325      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
13326      * when editable = true (defaults to false)
13327      */
13328     selectOnFocus:false,
13329     /**
13330      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
13331      */
13332     queryParam: 'query',
13333     /**
13334      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
13335      * when mode = 'remote' (defaults to 'Loading...')
13336      */
13337     loadingText: 'Loading...',
13338     /**
13339      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
13340      */
13341     resizable: false,
13342     /**
13343      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
13344      */
13345     handleHeight : 8,
13346     /**
13347      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
13348      * traditional select (defaults to true)
13349      */
13350     editable: true,
13351     /**
13352      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
13353      */
13354     allQuery: '',
13355     /**
13356      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
13357      */
13358     mode: 'remote',
13359     /**
13360      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
13361      * listWidth has a higher value)
13362      */
13363     minListWidth : 70,
13364     /**
13365      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
13366      * allow the user to set arbitrary text into the field (defaults to false)
13367      */
13368     forceSelection:false,
13369     /**
13370      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
13371      * if typeAhead = true (defaults to 250)
13372      */
13373     typeAheadDelay : 250,
13374     /**
13375      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
13376      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
13377      */
13378     valueNotFoundText : undefined,
13379     /**
13380      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
13381      */
13382     blockFocus : false,
13383     
13384     /**
13385      * @cfg {Boolean} disableClear Disable showing of clear button.
13386      */
13387     disableClear : false,
13388     /**
13389      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
13390      */
13391     alwaysQuery : false,
13392     
13393     /**
13394      * @cfg {Boolean} multiple  (true|false) ComboBobArray, default false
13395      */
13396     multiple : false,
13397     
13398     /**
13399      * @cfg {String} invalidClass DEPRICATED - uses BS4 is-valid now
13400      */
13401     invalidClass : "has-warning",
13402     
13403     /**
13404      * @cfg {String} validClass DEPRICATED - uses BS4 is-valid now
13405      */
13406     validClass : "has-success",
13407     
13408     /**
13409      * @cfg {Boolean} specialFilter (true|false) special filter default false
13410      */
13411     specialFilter : false,
13412     
13413     /**
13414      * @cfg {Boolean} mobileTouchView (true|false) show mobile touch view when using a mobile default true
13415      */
13416     mobileTouchView : true,
13417     
13418     /**
13419      * @cfg {Boolean} useNativeIOS (true|false) render it as classic select for ios, not support dynamic load data (default false)
13420      */
13421     useNativeIOS : false,
13422     
13423     /**
13424      * @cfg {Boolean} mobile_restrict_height (true|false) restrict height for touch view
13425      */
13426     mobile_restrict_height : false,
13427     
13428     ios_options : false,
13429     
13430     //private
13431     addicon : false,
13432     editicon: false,
13433     
13434     page: 0,
13435     hasQuery: false,
13436     append: false,
13437     loadNext: false,
13438     autoFocus : true,
13439     tickable : false,
13440     btnPosition : 'right',
13441     triggerList : true,
13442     showToggleBtn : true,
13443     animate : true,
13444     emptyResultText: 'Empty',
13445     triggerText : 'Select',
13446     emptyTitle : '',
13447     
13448     // element that contains real text value.. (when hidden is used..)
13449     
13450     getAutoCreate : function()
13451     {   
13452         var cfg = false;
13453         //render
13454         /*
13455          * Render classic select for iso
13456          */
13457         
13458         if(Roo.isIOS && this.useNativeIOS){
13459             cfg = this.getAutoCreateNativeIOS();
13460             return cfg;
13461         }
13462         
13463         /*
13464          * Touch Devices
13465          */
13466         
13467         if(Roo.isTouch && this.mobileTouchView){
13468             cfg = this.getAutoCreateTouchView();
13469             return cfg;;
13470         }
13471         
13472         /*
13473          *  Normal ComboBox
13474          */
13475         if(!this.tickable){
13476             cfg = Roo.bootstrap.ComboBox.superclass.getAutoCreate.call(this);
13477             return cfg;
13478         }
13479         
13480         /*
13481          *  ComboBox with tickable selections
13482          */
13483              
13484         var align = this.labelAlign || this.parentLabelAlign();
13485         
13486         cfg = {
13487             cls : 'form-group roo-combobox-tickable' //input-group
13488         };
13489         
13490         var btn_text_select = '';
13491         var btn_text_done = '';
13492         var btn_text_cancel = '';
13493         
13494         if (this.btn_text_show) {
13495             btn_text_select = 'Select';
13496             btn_text_done = 'Done';
13497             btn_text_cancel = 'Cancel'; 
13498         }
13499         
13500         var buttons = {
13501             tag : 'div',
13502             cls : 'tickable-buttons',
13503             cn : [
13504                 {
13505                     tag : 'button',
13506                     type : 'button',
13507                     cls : 'btn btn-link btn-edit pull-' + this.btnPosition,
13508                     //html : this.triggerText
13509                     html: btn_text_select
13510                 },
13511                 {
13512                     tag : 'button',
13513                     type : 'button',
13514                     name : 'ok',
13515                     cls : 'btn btn-link btn-ok pull-' + this.btnPosition,
13516                     //html : 'Done'
13517                     html: btn_text_done
13518                 },
13519                 {
13520                     tag : 'button',
13521                     type : 'button',
13522                     name : 'cancel',
13523                     cls : 'btn btn-link btn-cancel pull-' + this.btnPosition,
13524                     //html : 'Cancel'
13525                     html: btn_text_cancel
13526                 }
13527             ]
13528         };
13529         
13530         if(this.editable){
13531             buttons.cn.unshift({
13532                 tag: 'input',
13533                 cls: 'roo-select2-search-field-input'
13534             });
13535         }
13536         
13537         var _this = this;
13538         
13539         Roo.each(buttons.cn, function(c){
13540             if (_this.size) {
13541                 c.cls += ' btn-' + _this.size;
13542             }
13543
13544             if (_this.disabled) {
13545                 c.disabled = true;
13546             }
13547         });
13548         
13549         var box = {
13550             tag: 'div',
13551             style : 'display: contents',
13552             cn: [
13553                 {
13554                     tag: 'input',
13555                     type : 'hidden',
13556                     cls: 'form-hidden-field'
13557                 },
13558                 {
13559                     tag: 'ul',
13560                     cls: 'roo-select2-choices',
13561                     cn:[
13562                         {
13563                             tag: 'li',
13564                             cls: 'roo-select2-search-field',
13565                             cn: [
13566                                 buttons
13567                             ]
13568                         }
13569                     ]
13570                 }
13571             ]
13572         };
13573         
13574         var combobox = {
13575             cls: 'roo-select2-container input-group roo-select2-container-multi',
13576             cn: [
13577                 
13578                 box
13579 //                {
13580 //                    tag: 'ul',
13581 //                    cls: 'typeahead typeahead-long dropdown-menu',
13582 //                    style: 'display:none; max-height:' + this.maxHeight + 'px;'
13583 //                }
13584             ]
13585         };
13586         
13587         if(this.hasFeedback && !this.allowBlank){
13588             
13589             var feedback = {
13590                 tag: 'span',
13591                 cls: 'glyphicon form-control-feedback'
13592             };
13593
13594             combobox.cn.push(feedback);
13595         }
13596         
13597         var indicator = {
13598             tag : 'i',
13599             cls : 'roo-required-indicator ' + (this.indicatorpos == 'right'  ? 'right' : 'left') +'-indicator text-danger fa fa-lg fa-star',
13600             tooltip : 'This field is required'
13601         };
13602         if (Roo.bootstrap.version == 4) {
13603             indicator = {
13604                 tag : 'i',
13605                 style : 'display:none'
13606             };
13607         }
13608         if (align ==='left' && this.fieldLabel.length) {
13609             
13610             cfg.cls += ' roo-form-group-label-left'  + (Roo.bootstrap.version == 4 ? ' row' : '');
13611             
13612             cfg.cn = [
13613                 indicator,
13614                 {
13615                     tag: 'label',
13616                     'for' :  id,
13617                     cls : 'control-label col-form-label',
13618                     html : this.fieldLabel
13619
13620                 },
13621                 {
13622                     cls : "", 
13623                     cn: [
13624                         combobox
13625                     ]
13626                 }
13627
13628             ];
13629             
13630             var labelCfg = cfg.cn[1];
13631             var contentCfg = cfg.cn[2];
13632             
13633
13634             if(this.indicatorpos == 'right'){
13635                 
13636                 cfg.cn = [
13637                     {
13638                         tag: 'label',
13639                         'for' :  id,
13640                         cls : 'control-label col-form-label',
13641                         cn : [
13642                             {
13643                                 tag : 'span',
13644                                 html : this.fieldLabel
13645                             },
13646                             indicator
13647                         ]
13648                     },
13649                     {
13650                         cls : "",
13651                         cn: [
13652                             combobox
13653                         ]
13654                     }
13655
13656                 ];
13657                 
13658                 
13659                 
13660                 labelCfg = cfg.cn[0];
13661                 contentCfg = cfg.cn[1];
13662             
13663             }
13664             
13665             if(this.labelWidth > 12){
13666                 labelCfg.style = "width: " + this.labelWidth + 'px';
13667             }
13668             
13669             if(this.labelWidth < 13 && this.labelmd == 0){
13670                 this.labelmd = this.labelWidth;
13671             }
13672             
13673             if(this.labellg > 0){
13674                 labelCfg.cls += ' col-lg-' + this.labellg;
13675                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
13676             }
13677             
13678             if(this.labelmd > 0){
13679                 labelCfg.cls += ' col-md-' + this.labelmd;
13680                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
13681             }
13682             
13683             if(this.labelsm > 0){
13684                 labelCfg.cls += ' col-sm-' + this.labelsm;
13685                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
13686             }
13687             
13688             if(this.labelxs > 0){
13689                 labelCfg.cls += ' col-xs-' + this.labelxs;
13690                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
13691             }
13692                 
13693                 
13694         } else if ( this.fieldLabel.length) {
13695 //                Roo.log(" label");
13696                  cfg.cn = [
13697                    indicator,
13698                     {
13699                         tag: 'label',
13700                         //cls : 'input-group-addon',
13701                         html : this.fieldLabel
13702                     },
13703                     combobox
13704                 ];
13705                 
13706                 if(this.indicatorpos == 'right'){
13707                     cfg.cn = [
13708                         {
13709                             tag: 'label',
13710                             //cls : 'input-group-addon',
13711                             html : this.fieldLabel
13712                         },
13713                         indicator,
13714                         combobox
13715                     ];
13716                     
13717                 }
13718
13719         } else {
13720             
13721 //                Roo.log(" no label && no align");
13722                 cfg = combobox
13723                      
13724                 
13725         }
13726          
13727         var settings=this;
13728         ['xs','sm','md','lg'].map(function(size){
13729             if (settings[size]) {
13730                 cfg.cls += ' col-' + size + '-' + settings[size];
13731             }
13732         });
13733         
13734         return cfg;
13735         
13736     },
13737     
13738     _initEventsCalled : false,
13739     
13740     // private
13741     initEvents: function()
13742     {   
13743         if (this._initEventsCalled) { // as we call render... prevent looping...
13744             return;
13745         }
13746         this._initEventsCalled = true;
13747         
13748         if (!this.store) {
13749             throw "can not find store for combo";
13750         }
13751         
13752         this.indicator = this.indicatorEl();
13753         
13754         this.store = Roo.factory(this.store, Roo.data);
13755         this.store.parent = this;
13756         
13757         // if we are building from html. then this element is so complex, that we can not really
13758         // use the rendered HTML.
13759         // so we have to trash and replace the previous code.
13760         if (Roo.XComponent.build_from_html) {
13761             // remove this element....
13762             var e = this.el.dom, k=0;
13763             while (e ) { e = e.previousSibling;  ++k;}
13764
13765             this.el.remove();
13766             
13767             this.el=false;
13768             this.rendered = false;
13769             
13770             this.render(this.parent().getChildContainer(true), k);
13771         }
13772         
13773         if(Roo.isIOS && this.useNativeIOS){
13774             this.initIOSView();
13775             return;
13776         }
13777         
13778         /*
13779          * Touch Devices
13780          */
13781         
13782         if(Roo.isTouch && this.mobileTouchView){
13783             this.initTouchView();
13784             return;
13785         }
13786         
13787         if(this.tickable){
13788             this.initTickableEvents();
13789             return;
13790         }
13791         
13792         Roo.bootstrap.ComboBox.superclass.initEvents.call(this);
13793         
13794         if(this.hiddenName){
13795             
13796             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
13797             
13798             this.hiddenField.dom.value =
13799                 this.hiddenValue !== undefined ? this.hiddenValue :
13800                 this.value !== undefined ? this.value : '';
13801
13802             // prevent input submission
13803             this.el.dom.removeAttribute('name');
13804             this.hiddenField.dom.setAttribute('name', this.hiddenName);
13805              
13806              
13807         }
13808         //if(Roo.isGecko){
13809         //    this.el.dom.setAttribute('autocomplete', 'off');
13810         //}
13811         
13812         var cls = 'x-combo-list';
13813         
13814         //this.list = new Roo.Layer({
13815         //    shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
13816         //});
13817         
13818         var _this = this;
13819         
13820         (function(){
13821             var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
13822             _this.list.setWidth(lw);
13823         }).defer(100);
13824         
13825         this.list.on('mouseover', this.onViewOver, this);
13826         this.list.on('mousemove', this.onViewMove, this);
13827         this.list.on('scroll', this.onViewScroll, this);
13828         
13829         /*
13830         this.list.swallowEvent('mousewheel');
13831         this.assetHeight = 0;
13832
13833         if(this.title){
13834             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
13835             this.assetHeight += this.header.getHeight();
13836         }
13837
13838         this.innerList = this.list.createChild({cls:cls+'-inner'});
13839         this.innerList.on('mouseover', this.onViewOver, this);
13840         this.innerList.on('mousemove', this.onViewMove, this);
13841         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
13842         
13843         if(this.allowBlank && !this.pageSize && !this.disableClear){
13844             this.footer = this.list.createChild({cls:cls+'-ft'});
13845             this.pageTb = new Roo.Toolbar(this.footer);
13846            
13847         }
13848         if(this.pageSize){
13849             this.footer = this.list.createChild({cls:cls+'-ft'});
13850             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
13851                     {pageSize: this.pageSize});
13852             
13853         }
13854         
13855         if (this.pageTb && this.allowBlank && !this.disableClear) {
13856             var _this = this;
13857             this.pageTb.add(new Roo.Toolbar.Fill(), {
13858                 cls: 'x-btn-icon x-btn-clear',
13859                 text: '&#160;',
13860                 handler: function()
13861                 {
13862                     _this.collapse();
13863                     _this.clearValue();
13864                     _this.onSelect(false, -1);
13865                 }
13866             });
13867         }
13868         if (this.footer) {
13869             this.assetHeight += this.footer.getHeight();
13870         }
13871         */
13872             
13873         if(!this.tpl){
13874             this.tpl = Roo.bootstrap.version == 4 ?
13875                 '<a class="dropdown-item" href="#">{' + this.displayField + '}</a>' :  // 4 does not need <li> and it get's really confisued.
13876                 '<li><a class="dropdown-item" href="#">{' + this.displayField + '}</a></li>';
13877         }
13878
13879         this.view = new Roo.View(this.list, this.tpl, {
13880             singleSelect:true, store: this.store, selectedClass: this.selectedClass
13881         });
13882         //this.view.wrapEl.setDisplayed(false);
13883         this.view.on('click', this.onViewClick, this);
13884         
13885         
13886         this.store.on('beforeload', this.onBeforeLoad, this);
13887         this.store.on('load', this.onLoad, this);
13888         this.store.on('loadexception', this.onLoadException, this);
13889         /*
13890         if(this.resizable){
13891             this.resizer = new Roo.Resizable(this.list,  {
13892                pinned:true, handles:'se'
13893             });
13894             this.resizer.on('resize', function(r, w, h){
13895                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
13896                 this.listWidth = w;
13897                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
13898                 this.restrictHeight();
13899             }, this);
13900             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
13901         }
13902         */
13903         if(!this.editable){
13904             this.editable = true;
13905             this.setEditable(false);
13906         }
13907         
13908         /*
13909         
13910         if (typeof(this.events.add.listeners) != 'undefined') {
13911             
13912             this.addicon = this.wrap.createChild(
13913                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
13914        
13915             this.addicon.on('click', function(e) {
13916                 this.fireEvent('add', this);
13917             }, this);
13918         }
13919         if (typeof(this.events.edit.listeners) != 'undefined') {
13920             
13921             this.editicon = this.wrap.createChild(
13922                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
13923             if (this.addicon) {
13924                 this.editicon.setStyle('margin-left', '40px');
13925             }
13926             this.editicon.on('click', function(e) {
13927                 
13928                 // we fire even  if inothing is selected..
13929                 this.fireEvent('edit', this, this.lastData );
13930                 
13931             }, this);
13932         }
13933         */
13934         
13935         this.keyNav = new Roo.KeyNav(this.inputEl(), {
13936             "up" : function(e){
13937                 this.inKeyMode = true;
13938                 this.selectPrev();
13939             },
13940
13941             "down" : function(e){
13942                 if(!this.isExpanded()){
13943                     this.onTriggerClick();
13944                 }else{
13945                     this.inKeyMode = true;
13946                     this.selectNext();
13947                 }
13948             },
13949
13950             "enter" : function(e){
13951 //                this.onViewClick();
13952                 //return true;
13953                 this.collapse();
13954                 
13955                 if(this.fireEvent("specialkey", this, e)){
13956                     this.onViewClick(false);
13957                 }
13958                 
13959                 return true;
13960             },
13961
13962             "esc" : function(e){
13963                 this.collapse();
13964             },
13965
13966             "tab" : function(e){
13967                 this.collapse();
13968                 
13969                 if(this.fireEvent("specialkey", this, e)){
13970                     this.onViewClick(false);
13971                 }
13972                 
13973                 return true;
13974             },
13975
13976             scope : this,
13977
13978             doRelay : function(foo, bar, hname){
13979                 if(hname == 'down' || this.scope.isExpanded()){
13980                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
13981                 }
13982                 return true;
13983             },
13984
13985             forceKeyDown: true
13986         });
13987         
13988         
13989         this.queryDelay = Math.max(this.queryDelay || 10,
13990                 this.mode == 'local' ? 10 : 250);
13991         
13992         
13993         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
13994         
13995         if(this.typeAhead){
13996             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
13997         }
13998         if(this.editable !== false){
13999             this.inputEl().on("keyup", this.onKeyUp, this);
14000         }
14001         if(this.forceSelection){
14002             this.inputEl().on('blur', this.doForce, this);
14003         }
14004         
14005         if(this.multiple){
14006             this.choices = this.el.select('ul.roo-select2-choices', true).first();
14007             this.searchField = this.el.select('ul li.roo-select2-search-field', true).first();
14008         }
14009     },
14010     
14011     initTickableEvents: function()
14012     {   
14013         this.createList();
14014         
14015         if(this.hiddenName){
14016             
14017             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
14018             
14019             this.hiddenField.dom.value =
14020                 this.hiddenValue !== undefined ? this.hiddenValue :
14021                 this.value !== undefined ? this.value : '';
14022
14023             // prevent input submission
14024             this.el.dom.removeAttribute('name');
14025             this.hiddenField.dom.setAttribute('name', this.hiddenName);
14026              
14027              
14028         }
14029         
14030 //        this.list = this.el.select('ul.dropdown-menu',true).first();
14031         
14032         this.choices = this.el.select('ul.roo-select2-choices', true).first();
14033         this.searchField = this.el.select('ul li.roo-select2-search-field', true).first();
14034         if(this.triggerList){
14035             this.searchField.on("click", this.onSearchFieldClick, this, {preventDefault:true});
14036         }
14037          
14038         this.trigger = this.el.select('.tickable-buttons > .btn-edit', true).first();
14039         this.trigger.on("click", this.onTickableTriggerClick, this, {preventDefault:true});
14040         
14041         this.okBtn = this.el.select('.tickable-buttons > .btn-ok', true).first();
14042         this.cancelBtn = this.el.select('.tickable-buttons > .btn-cancel', true).first();
14043         
14044         this.okBtn.on('click', this.onTickableFooterButtonClick, this, this.okBtn);
14045         this.cancelBtn.on('click', this.onTickableFooterButtonClick, this, this.cancelBtn);
14046         
14047         this.trigger.setVisibilityMode(Roo.Element.DISPLAY);
14048         this.okBtn.setVisibilityMode(Roo.Element.DISPLAY);
14049         this.cancelBtn.setVisibilityMode(Roo.Element.DISPLAY);
14050         
14051         this.okBtn.hide();
14052         this.cancelBtn.hide();
14053         
14054         var _this = this;
14055         
14056         (function(){
14057             var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
14058             _this.list.setWidth(lw);
14059         }).defer(100);
14060         
14061         this.list.on('mouseover', this.onViewOver, this);
14062         this.list.on('mousemove', this.onViewMove, this);
14063         
14064         this.list.on('scroll', this.onViewScroll, this);
14065         
14066         if(!this.tpl){
14067             this.tpl = '<li class="roo-select2-result"><div class="checkbox"><input id="{roo-id}"' + 
14068                 'type="checkbox" {roo-data-checked}><label for="{roo-id}"><b>{' + this.displayField + '}</b></label></div></li>';
14069         }
14070
14071         this.view = new Roo.View(this.list, this.tpl, {
14072             singleSelect:true,
14073             tickable:true,
14074             parent:this,
14075             store: this.store,
14076             selectedClass: this.selectedClass
14077         });
14078         
14079         //this.view.wrapEl.setDisplayed(false);
14080         this.view.on('click', this.onViewClick, this);
14081         
14082         
14083         
14084         this.store.on('beforeload', this.onBeforeLoad, this);
14085         this.store.on('load', this.onLoad, this);
14086         this.store.on('loadexception', this.onLoadException, this);
14087         
14088         if(this.editable){
14089             this.keyNav = new Roo.KeyNav(this.tickableInputEl(), {
14090                 "up" : function(e){
14091                     this.inKeyMode = true;
14092                     this.selectPrev();
14093                 },
14094
14095                 "down" : function(e){
14096                     this.inKeyMode = true;
14097                     this.selectNext();
14098                 },
14099
14100                 "enter" : function(e){
14101                     if(this.fireEvent("specialkey", this, e)){
14102                         this.onViewClick(false);
14103                     }
14104                     
14105                     return true;
14106                 },
14107
14108                 "esc" : function(e){
14109                     this.onTickableFooterButtonClick(e, false, false);
14110                 },
14111
14112                 "tab" : function(e){
14113                     this.fireEvent("specialkey", this, e);
14114                     
14115                     this.onTickableFooterButtonClick(e, false, false);
14116                     
14117                     return true;
14118                 },
14119
14120                 scope : this,
14121
14122                 doRelay : function(e, fn, key){
14123                     if(this.scope.isExpanded()){
14124                        return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
14125                     }
14126                     return true;
14127                 },
14128
14129                 forceKeyDown: true
14130             });
14131         }
14132         
14133         this.queryDelay = Math.max(this.queryDelay || 10,
14134                 this.mode == 'local' ? 10 : 250);
14135         
14136         
14137         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
14138         
14139         if(this.typeAhead){
14140             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
14141         }
14142         
14143         if(this.editable !== false){
14144             this.tickableInputEl().on("keyup", this.onKeyUp, this);
14145         }
14146         
14147         this.indicator = this.indicatorEl();
14148         
14149         if(this.indicator){
14150             this.indicator.setVisibilityMode(Roo.Element.DISPLAY);
14151             this.indicator.hide();
14152         }
14153         
14154     },
14155
14156     onDestroy : function(){
14157         if(this.view){
14158             this.view.setStore(null);
14159             this.view.el.removeAllListeners();
14160             this.view.el.remove();
14161             this.view.purgeListeners();
14162         }
14163         if(this.list){
14164             this.list.dom.innerHTML  = '';
14165         }
14166         
14167         if(this.store){
14168             this.store.un('beforeload', this.onBeforeLoad, this);
14169             this.store.un('load', this.onLoad, this);
14170             this.store.un('loadexception', this.onLoadException, this);
14171         }
14172         Roo.bootstrap.ComboBox.superclass.onDestroy.call(this);
14173     },
14174
14175     // private
14176     fireKey : function(e){
14177         if(e.isNavKeyPress() && !this.list.isVisible()){
14178             this.fireEvent("specialkey", this, e);
14179         }
14180     },
14181
14182     // private
14183     onResize: function(w, h){
14184 //        Roo.bootstrap.ComboBox.superclass.onResize.apply(this, arguments);
14185 //        
14186 //        if(typeof w != 'number'){
14187 //            // we do not handle it!?!?
14188 //            return;
14189 //        }
14190 //        var tw = this.trigger.getWidth();
14191 //       // tw += this.addicon ? this.addicon.getWidth() : 0;
14192 //       // tw += this.editicon ? this.editicon.getWidth() : 0;
14193 //        var x = w - tw;
14194 //        this.inputEl().setWidth( this.adjustWidth('input', x));
14195 //            
14196 //        //this.trigger.setStyle('left', x+'px');
14197 //        
14198 //        if(this.list && this.listWidth === undefined){
14199 //            var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
14200 //            this.list.setWidth(lw);
14201 //            this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
14202 //        }
14203         
14204     
14205         
14206     },
14207
14208     /**
14209      * Allow or prevent the user from directly editing the field text.  If false is passed,
14210      * the user will only be able to select from the items defined in the dropdown list.  This method
14211      * is the runtime equivalent of setting the 'editable' config option at config time.
14212      * @param {Boolean} value True to allow the user to directly edit the field text
14213      */
14214     setEditable : function(value){
14215         if(value == this.editable){
14216             return;
14217         }
14218         this.editable = value;
14219         if(!value){
14220             this.inputEl().dom.setAttribute('readOnly', true);
14221             this.inputEl().on('mousedown', this.onTriggerClick,  this);
14222             this.inputEl().addClass('x-combo-noedit');
14223         }else{
14224             this.inputEl().dom.setAttribute('readOnly', false);
14225             this.inputEl().un('mousedown', this.onTriggerClick,  this);
14226             this.inputEl().removeClass('x-combo-noedit');
14227         }
14228     },
14229
14230     // private
14231     
14232     onBeforeLoad : function(combo,opts){
14233         if(!this.hasFocus){
14234             return;
14235         }
14236          if (!opts.add) {
14237             this.list.dom.innerHTML = '<li class="loading-indicator">'+(this.loadingText||'loading')+'</li>' ;
14238          }
14239         this.restrictHeight();
14240         this.selectedIndex = -1;
14241     },
14242
14243     // private
14244     onLoad : function(){
14245         
14246         this.hasQuery = false;
14247         
14248         if(!this.hasFocus){
14249             return;
14250         }
14251         
14252         if(typeof(this.loading) !== 'undefined' && this.loading !== null){
14253             this.loading.hide();
14254         }
14255         
14256         if(this.store.getCount() > 0){
14257             
14258             this.expand();
14259             this.restrictHeight();
14260             if(this.lastQuery == this.allQuery){
14261                 if(this.editable && !this.tickable){
14262                     this.inputEl().dom.select();
14263                 }
14264                 
14265                 if(
14266                     !this.selectByValue(this.value, true) &&
14267                     this.autoFocus && 
14268                     (
14269                         !this.store.lastOptions ||
14270                         typeof(this.store.lastOptions.add) == 'undefined' || 
14271                         this.store.lastOptions.add != true
14272                     )
14273                 ){
14274                     this.select(0, true);
14275                 }
14276             }else{
14277                 if(this.autoFocus){
14278                     this.selectNext();
14279                 }
14280                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
14281                     this.taTask.delay(this.typeAheadDelay);
14282                 }
14283             }
14284         }else{
14285             this.onEmptyResults();
14286         }
14287         
14288         //this.el.focus();
14289     },
14290     // private
14291     onLoadException : function()
14292     {
14293         this.hasQuery = false;
14294         
14295         if(typeof(this.loading) !== 'undefined' && this.loading !== null){
14296             this.loading.hide();
14297         }
14298         
14299         if(this.tickable && this.editable){
14300             return;
14301         }
14302         
14303         this.collapse();
14304         // only causes errors at present
14305         //Roo.log(this.store.reader.jsonData);
14306         //if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
14307             // fixme
14308             //Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
14309         //}
14310         
14311         
14312     },
14313     // private
14314     onTypeAhead : function(){
14315         if(this.store.getCount() > 0){
14316             var r = this.store.getAt(0);
14317             var newValue = r.data[this.displayField];
14318             var len = newValue.length;
14319             var selStart = this.getRawValue().length;
14320             
14321             if(selStart != len){
14322                 this.setRawValue(newValue);
14323                 this.selectText(selStart, newValue.length);
14324             }
14325         }
14326     },
14327
14328     // private
14329     onSelect : function(record, index){
14330         
14331         if(this.fireEvent('beforeselect', this, record, index) !== false){
14332         
14333             this.setFromData(index > -1 ? record.data : false);
14334             
14335             this.collapse();
14336             this.fireEvent('select', this, record, index);
14337         }
14338     },
14339
14340     /**
14341      * Returns the currently selected field value or empty string if no value is set.
14342      * @return {String} value The selected value
14343      */
14344     getValue : function()
14345     {
14346         if(Roo.isIOS && this.useNativeIOS){
14347             return this.ios_options[this.inputEl().dom.selectedIndex].data[this.valueField];
14348         }
14349         
14350         if(this.multiple){
14351             return (this.hiddenField) ? this.hiddenField.dom.value : this.value;
14352         }
14353         
14354         if(this.valueField){
14355             return typeof this.value != 'undefined' ? this.value : '';
14356         }else{
14357             return Roo.bootstrap.ComboBox.superclass.getValue.call(this);
14358         }
14359     },
14360     
14361     getRawValue : function()
14362     {
14363         if(Roo.isIOS && this.useNativeIOS){
14364             return this.ios_options[this.inputEl().dom.selectedIndex].data[this.displayField];
14365         }
14366         
14367         var v = this.inputEl().getValue();
14368         
14369         return v;
14370     },
14371
14372     /**
14373      * Clears any text/value currently set in the field
14374      */
14375     clearValue : function(){
14376         
14377         if(this.hiddenField){
14378             this.hiddenField.dom.value = '';
14379         }
14380         this.value = '';
14381         this.setRawValue('');
14382         this.lastSelectionText = '';
14383         this.lastData = false;
14384         
14385         var close = this.closeTriggerEl();
14386         
14387         if(close){
14388             close.hide();
14389         }
14390         
14391         this.validate();
14392         
14393     },
14394
14395     /**
14396      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
14397      * will be displayed in the field.  If the value does not match the data value of an existing item,
14398      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
14399      * Otherwise the field will be blank (although the value will still be set).
14400      * @param {String} value The value to match
14401      */
14402     setValue : function(v)
14403     {
14404         if(Roo.isIOS && this.useNativeIOS){
14405             this.setIOSValue(v);
14406             return;
14407         }
14408         
14409         if(this.multiple){
14410             this.syncValue();
14411             return;
14412         }
14413         
14414         var text = v;
14415         if(this.valueField){
14416             var r = this.findRecord(this.valueField, v);
14417             if(r){
14418                 text = r.data[this.displayField];
14419             }else if(this.valueNotFoundText !== undefined){
14420                 text = this.valueNotFoundText;
14421             }
14422         }
14423         this.lastSelectionText = text;
14424         if(this.hiddenField){
14425             this.hiddenField.dom.value = v;
14426         }
14427         Roo.bootstrap.ComboBox.superclass.setValue.call(this, text);
14428         this.value = v;
14429         
14430         var close = this.closeTriggerEl();
14431         
14432         if(close){
14433             (v && (v.length || v * 1 > 0)) ? close.show() : close.hide();
14434         }
14435         
14436         this.validate();
14437     },
14438     /**
14439      * @property {Object} the last set data for the element
14440      */
14441     
14442     lastData : false,
14443     /**
14444      * Sets the value of the field based on a object which is related to the record format for the store.
14445      * @param {Object} value the value to set as. or false on reset?
14446      */
14447     setFromData : function(o){
14448         
14449         if(this.multiple){
14450             this.addItem(o);
14451             return;
14452         }
14453             
14454         var dv = ''; // display value
14455         var vv = ''; // value value..
14456         this.lastData = o;
14457         if (this.displayField) {
14458             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
14459         } else {
14460             // this is an error condition!!!
14461             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
14462         }
14463         
14464         if(this.valueField){
14465             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
14466         }
14467         
14468         var close = this.closeTriggerEl();
14469         
14470         if(close){
14471             if(dv.length || vv * 1 > 0){
14472                 close.show() ;
14473                 this.blockFocus=true;
14474             } else {
14475                 close.hide();
14476             }             
14477         }
14478         
14479         if(this.hiddenField){
14480             this.hiddenField.dom.value = vv;
14481             
14482             this.lastSelectionText = dv;
14483             Roo.bootstrap.ComboBox.superclass.setValue.call(this, dv);
14484             this.value = vv;
14485             return;
14486         }
14487         // no hidden field.. - we store the value in 'value', but still display
14488         // display field!!!!
14489         this.lastSelectionText = dv;
14490         Roo.bootstrap.ComboBox.superclass.setValue.call(this, dv);
14491         this.value = vv;
14492         
14493         
14494         
14495     },
14496     // private
14497     reset : function(){
14498         // overridden so that last data is reset..
14499         
14500         if(this.multiple){
14501             this.clearItem();
14502             return;
14503         }
14504         
14505         this.setValue(this.originalValue);
14506         //this.clearInvalid();
14507         this.lastData = false;
14508         if (this.view) {
14509             this.view.clearSelections();
14510         }
14511         
14512         this.validate();
14513     },
14514     // private
14515     findRecord : function(prop, value){
14516         var record;
14517         if(this.store.getCount() > 0){
14518             this.store.each(function(r){
14519                 if(r.data[prop] == value){
14520                     record = r;
14521                     return false;
14522                 }
14523                 return true;
14524             });
14525         }
14526         return record;
14527     },
14528     
14529     getName: function()
14530     {
14531         // returns hidden if it's set..
14532         if (!this.rendered) {return ''};
14533         return !this.hiddenName && this.inputEl().dom.name  ? this.inputEl().dom.name : (this.hiddenName || '');
14534         
14535     },
14536     // private
14537     onViewMove : function(e, t){
14538         this.inKeyMode = false;
14539     },
14540
14541     // private
14542     onViewOver : function(e, t){
14543         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
14544             return;
14545         }
14546         var item = this.view.findItemFromChild(t);
14547         
14548         if(item){
14549             var index = this.view.indexOf(item);
14550             this.select(index, false);
14551         }
14552     },
14553
14554     // private
14555     onViewClick : function(view, doFocus, el, e)
14556     {
14557         var index = this.view.getSelectedIndexes()[0];
14558         
14559         var r = this.store.getAt(index);
14560         
14561         if(this.tickable){
14562             
14563             if(typeof(e) != 'undefined' && e.getTarget().nodeName.toLowerCase() != 'input'){
14564                 return;
14565             }
14566             
14567             var rm = false;
14568             var _this = this;
14569             
14570             Roo.each(this.tickItems, function(v,k){
14571                 
14572                 if(typeof(v) != 'undefined' && v[_this.valueField] == r.data[_this.valueField]){
14573                     Roo.log(v);
14574                     _this.tickItems.splice(k, 1);
14575                     
14576                     if(typeof(e) == 'undefined' && view == false){
14577                         Roo.get(_this.view.getNodes(index, index)[0]).select('input', true).first().dom.checked = false;
14578                     }
14579                     
14580                     rm = true;
14581                     return;
14582                 }
14583             });
14584             
14585             if(rm){
14586                 return;
14587             }
14588             
14589             if(this.fireEvent('tick', this, r, index, Roo.get(_this.view.getNodes(index, index)[0]).select('input', true).first().dom.checked) !== false){
14590                 this.tickItems.push(r.data);
14591             }
14592             
14593             if(typeof(e) == 'undefined' && view == false){
14594                 Roo.get(_this.view.getNodes(index, index)[0]).select('input', true).first().dom.checked = true;
14595             }
14596                     
14597             return;
14598         }
14599         
14600         if(r){
14601             this.onSelect(r, index);
14602         }
14603         if(doFocus !== false && !this.blockFocus){
14604             this.inputEl().focus();
14605         }
14606     },
14607
14608     // private
14609     restrictHeight : function(){
14610         //this.innerList.dom.style.height = '';
14611         //var inner = this.innerList.dom;
14612         //var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
14613         //this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
14614         //this.list.beginUpdate();
14615         //this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
14616         this.list.alignTo(this.inputEl(), this.listAlign);
14617         this.list.alignTo(this.inputEl(), this.listAlign);
14618         //this.list.endUpdate();
14619     },
14620
14621     // private
14622     onEmptyResults : function(){
14623         
14624         if(this.tickable && this.editable){
14625             this.hasFocus = false;
14626             this.restrictHeight();
14627             return;
14628         }
14629         
14630         this.collapse();
14631     },
14632
14633     /**
14634      * Returns true if the dropdown list is expanded, else false.
14635      */
14636     isExpanded : function(){
14637         return this.list.isVisible();
14638     },
14639
14640     /**
14641      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
14642      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
14643      * @param {String} value The data value of the item to select
14644      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
14645      * selected item if it is not currently in view (defaults to true)
14646      * @return {Boolean} True if the value matched an item in the list, else false
14647      */
14648     selectByValue : function(v, scrollIntoView){
14649         if(v !== undefined && v !== null){
14650             var r = this.findRecord(this.valueField || this.displayField, v);
14651             if(r){
14652                 this.select(this.store.indexOf(r), scrollIntoView);
14653                 return true;
14654             }
14655         }
14656         return false;
14657     },
14658
14659     /**
14660      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
14661      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
14662      * @param {Number} index The zero-based index of the list item to select
14663      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
14664      * selected item if it is not currently in view (defaults to true)
14665      */
14666     select : function(index, scrollIntoView){
14667         this.selectedIndex = index;
14668         this.view.select(index);
14669         if(scrollIntoView !== false){
14670             var el = this.view.getNode(index);
14671             /*
14672              * el && !this.multiple && !this.tickable // not sure why we disable multiple before..
14673              */
14674             if(el){
14675                 this.list.scrollChildIntoView(el, false);
14676             }
14677         }
14678     },
14679
14680     // private
14681     selectNext : function(){
14682         var ct = this.store.getCount();
14683         if(ct > 0){
14684             if(this.selectedIndex == -1){
14685                 this.select(0);
14686             }else if(this.selectedIndex < ct-1){
14687                 this.select(this.selectedIndex+1);
14688             }
14689         }
14690     },
14691
14692     // private
14693     selectPrev : function(){
14694         var ct = this.store.getCount();
14695         if(ct > 0){
14696             if(this.selectedIndex == -1){
14697                 this.select(0);
14698             }else if(this.selectedIndex != 0){
14699                 this.select(this.selectedIndex-1);
14700             }
14701         }
14702     },
14703
14704     // private
14705     onKeyUp : function(e){
14706         if(this.editable !== false && !e.isSpecialKey()){
14707             this.lastKey = e.getKey();
14708             this.dqTask.delay(this.queryDelay);
14709         }
14710     },
14711
14712     // private
14713     validateBlur : function(){
14714         return !this.list || !this.list.isVisible();   
14715     },
14716
14717     // private
14718     initQuery : function(){
14719         
14720         var v = this.getRawValue();
14721         
14722         if(this.tickable && this.editable){
14723             v = this.tickableInputEl().getValue();
14724         }
14725         
14726         this.doQuery(v);
14727     },
14728
14729     // private
14730     doForce : function(){
14731         if(this.inputEl().dom.value.length > 0){
14732             this.inputEl().dom.value =
14733                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
14734              
14735         }
14736     },
14737
14738     /**
14739      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
14740      * query allowing the query action to be canceled if needed.
14741      * @param {String} query The SQL query to execute
14742      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
14743      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
14744      * saved in the current store (defaults to false)
14745      */
14746     doQuery : function(q, forceAll){
14747         
14748         if(q === undefined || q === null){
14749             q = '';
14750         }
14751         var qe = {
14752             query: q,
14753             forceAll: forceAll,
14754             combo: this,
14755             cancel:false
14756         };
14757         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
14758             return false;
14759         }
14760         q = qe.query;
14761         
14762         forceAll = qe.forceAll;
14763         if(forceAll === true || (q.length >= this.minChars)){
14764             
14765             this.hasQuery = true;
14766             
14767             if(this.lastQuery != q || this.alwaysQuery){
14768                 this.lastQuery = q;
14769                 if(this.mode == 'local'){
14770                     this.selectedIndex = -1;
14771                     if(forceAll){
14772                         this.store.clearFilter();
14773                     }else{
14774                         
14775                         if(this.specialFilter){
14776                             this.fireEvent('specialfilter', this);
14777                             this.onLoad();
14778                             return;
14779                         }
14780                         
14781                         this.store.filter(this.displayField, q);
14782                     }
14783                     
14784                     this.store.fireEvent("datachanged", this.store);
14785                     
14786                     this.onLoad();
14787                     
14788                     
14789                 }else{
14790                     
14791                     this.store.baseParams[this.queryParam] = q;
14792                     
14793                     var options = {params : this.getParams(q)};
14794                     
14795                     if(this.loadNext){
14796                         options.add = true;
14797                         options.params.start = this.page * this.pageSize;
14798                     }
14799                     
14800                     this.store.load(options);
14801                     
14802                     /*
14803                      *  this code will make the page width larger, at the beginning, the list not align correctly, 
14804                      *  we should expand the list on onLoad
14805                      *  so command out it
14806                      */
14807 //                    this.expand();
14808                 }
14809             }else{
14810                 this.selectedIndex = -1;
14811                 this.onLoad();   
14812             }
14813         }
14814         
14815         this.loadNext = false;
14816     },
14817     
14818     // private
14819     getParams : function(q){
14820         var p = {};
14821         //p[this.queryParam] = q;
14822         
14823         if(this.pageSize){
14824             p.start = 0;
14825             p.limit = this.pageSize;
14826         }
14827         return p;
14828     },
14829
14830     /**
14831      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
14832      */
14833     collapse : function(){
14834         if(!this.isExpanded()){
14835             return;
14836         }
14837         
14838         this.list.hide();
14839         
14840         this.hasFocus = false;
14841         
14842         if(this.tickable){
14843             this.okBtn.hide();
14844             this.cancelBtn.hide();
14845             this.trigger.show();
14846             
14847             if(this.editable){
14848                 this.tickableInputEl().dom.value = '';
14849                 this.tickableInputEl().blur();
14850             }
14851             
14852         }
14853         
14854         Roo.get(document).un('mousedown', this.collapseIf, this);
14855         Roo.get(document).un('mousewheel', this.collapseIf, this);
14856         if (!this.editable) {
14857             Roo.get(document).un('keydown', this.listKeyPress, this);
14858         }
14859         this.fireEvent('collapse', this);
14860         
14861         this.validate();
14862     },
14863
14864     // private
14865     collapseIf : function(e){
14866         var in_combo  = e.within(this.el);
14867         var in_list =  e.within(this.list);
14868         var is_list = (Roo.get(e.getTarget()).id == this.list.id) ? true : false;
14869         
14870         if (in_combo || in_list || is_list) {
14871             //e.stopPropagation();
14872             return;
14873         }
14874         
14875         if(this.tickable){
14876             this.onTickableFooterButtonClick(e, false, false);
14877         }
14878
14879         this.collapse();
14880         
14881     },
14882
14883     /**
14884      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
14885      */
14886     expand : function(){
14887        
14888         if(this.isExpanded() || !this.hasFocus){
14889             return;
14890         }
14891         
14892         var lw = this.listWidth || Math.max(this.inputEl().getWidth(), this.minListWidth);
14893         this.list.setWidth(lw);
14894         
14895         Roo.log('expand');
14896         
14897         this.list.show();
14898         
14899         this.restrictHeight();
14900         
14901         if(this.tickable){
14902             
14903             this.tickItems = Roo.apply([], this.item);
14904             
14905             this.okBtn.show();
14906             this.cancelBtn.show();
14907             this.trigger.hide();
14908             
14909             if(this.editable){
14910                 this.tickableInputEl().focus();
14911             }
14912             
14913         }
14914         
14915         Roo.get(document).on('mousedown', this.collapseIf, this);
14916         Roo.get(document).on('mousewheel', this.collapseIf, this);
14917         if (!this.editable) {
14918             Roo.get(document).on('keydown', this.listKeyPress, this);
14919         }
14920         
14921         this.fireEvent('expand', this);
14922     },
14923
14924     // private
14925     // Implements the default empty TriggerField.onTriggerClick function
14926     onTriggerClick : function(e)
14927     {
14928         Roo.log('trigger click');
14929         
14930         if(this.disabled || !this.triggerList){
14931             return;
14932         }
14933         
14934         this.page = 0;
14935         this.loadNext = false;
14936         
14937         if(this.isExpanded()){
14938             this.collapse();
14939             if (!this.blockFocus) {
14940                 this.inputEl().focus();
14941             }
14942             
14943         }else {
14944             this.hasFocus = true;
14945             if(this.triggerAction == 'all') {
14946                 this.doQuery(this.allQuery, true);
14947             } else {
14948                 this.doQuery(this.getRawValue());
14949             }
14950             if (!this.blockFocus) {
14951                 this.inputEl().focus();
14952             }
14953         }
14954     },
14955     
14956     onTickableTriggerClick : function(e)
14957     {
14958         if(this.disabled){
14959             return;
14960         }
14961         
14962         this.page = 0;
14963         this.loadNext = false;
14964         this.hasFocus = true;
14965         
14966         if(this.triggerAction == 'all') {
14967             this.doQuery(this.allQuery, true);
14968         } else {
14969             this.doQuery(this.getRawValue());
14970         }
14971     },
14972     
14973     onSearchFieldClick : function(e)
14974     {
14975         if(this.hasFocus && !this.disabled && e.getTarget().nodeName.toLowerCase() != 'button'){
14976             this.onTickableFooterButtonClick(e, false, false);
14977             return;
14978         }
14979         
14980         if(this.hasFocus || this.disabled || e.getTarget().nodeName.toLowerCase() == 'button'){
14981             return;
14982         }
14983         
14984         this.page = 0;
14985         this.loadNext = false;
14986         this.hasFocus = true;
14987         
14988         if(this.triggerAction == 'all') {
14989             this.doQuery(this.allQuery, true);
14990         } else {
14991             this.doQuery(this.getRawValue());
14992         }
14993     },
14994     
14995     listKeyPress : function(e)
14996     {
14997         //Roo.log('listkeypress');
14998         // scroll to first matching element based on key pres..
14999         if (e.isSpecialKey()) {
15000             return false;
15001         }
15002         var k = String.fromCharCode(e.getKey()).toUpperCase();
15003         //Roo.log(k);
15004         var match  = false;
15005         var csel = this.view.getSelectedNodes();
15006         var cselitem = false;
15007         if (csel.length) {
15008             var ix = this.view.indexOf(csel[0]);
15009             cselitem  = this.store.getAt(ix);
15010             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
15011                 cselitem = false;
15012             }
15013             
15014         }
15015         
15016         this.store.each(function(v) { 
15017             if (cselitem) {
15018                 // start at existing selection.
15019                 if (cselitem.id == v.id) {
15020                     cselitem = false;
15021                 }
15022                 return true;
15023             }
15024                 
15025             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
15026                 match = this.store.indexOf(v);
15027                 return false;
15028             }
15029             return true;
15030         }, this);
15031         
15032         if (match === false) {
15033             return true; // no more action?
15034         }
15035         // scroll to?
15036         this.view.select(match);
15037         var sn = Roo.get(this.view.getSelectedNodes()[0]);
15038         sn.scrollIntoView(sn.dom.parentNode, false);
15039     },
15040     
15041     onViewScroll : function(e, t){
15042         
15043         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){
15044             return;
15045         }
15046         
15047         this.hasQuery = true;
15048         
15049         this.loading = this.list.select('.loading', true).first();
15050         
15051         if(this.loading === null){
15052             this.list.createChild({
15053                 tag: 'div',
15054                 cls: 'loading roo-select2-more-results roo-select2-active',
15055                 html: 'Loading more results...'
15056             });
15057             
15058             this.loading = this.list.select('.loading', true).first();
15059             
15060             this.loading.setVisibilityMode(Roo.Element.DISPLAY);
15061             
15062             this.loading.hide();
15063         }
15064         
15065         this.loading.show();
15066         
15067         var _combo = this;
15068         
15069         this.page++;
15070         this.loadNext = true;
15071         
15072         (function() { _combo.doQuery(_combo.allQuery, true); }).defer(500);
15073         
15074         return;
15075     },
15076     
15077     addItem : function(o)
15078     {   
15079         var dv = ''; // display value
15080         
15081         if (this.displayField) {
15082             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
15083         } else {
15084             // this is an error condition!!!
15085             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
15086         }
15087         
15088         if(!dv.length){
15089             return;
15090         }
15091         
15092         var choice = this.choices.createChild({
15093             tag: 'li',
15094             cls: 'roo-select2-search-choice',
15095             cn: [
15096                 {
15097                     tag: 'div',
15098                     html: dv
15099                 },
15100                 {
15101                     tag: 'a',
15102                     href: '#',
15103                     cls: 'roo-select2-search-choice-close fa fa-times',
15104                     tabindex: '-1'
15105                 }
15106             ]
15107             
15108         }, this.searchField);
15109         
15110         var close = choice.select('a.roo-select2-search-choice-close', true).first();
15111         
15112         close.on('click', this.onRemoveItem, this, { item : choice, data : o} );
15113         
15114         this.item.push(o);
15115         
15116         this.lastData = o;
15117         
15118         this.syncValue();
15119         
15120         this.inputEl().dom.value = '';
15121         
15122         this.validate();
15123     },
15124     
15125     onRemoveItem : function(e, _self, o)
15126     {
15127         e.preventDefault();
15128         
15129         this.lastItem = Roo.apply([], this.item);
15130         
15131         var index = this.item.indexOf(o.data) * 1;
15132         
15133         if( index < 0){
15134             Roo.log('not this item?!');
15135             return;
15136         }
15137         
15138         this.item.splice(index, 1);
15139         o.item.remove();
15140         
15141         this.syncValue();
15142         
15143         this.fireEvent('remove', this, e);
15144         
15145         this.validate();
15146         
15147     },
15148     
15149     syncValue : function()
15150     {
15151         if(!this.item.length){
15152             this.clearValue();
15153             return;
15154         }
15155             
15156         var value = [];
15157         var _this = this;
15158         Roo.each(this.item, function(i){
15159             if(_this.valueField){
15160                 value.push(i[_this.valueField]);
15161                 return;
15162             }
15163
15164             value.push(i);
15165         });
15166
15167         this.value = value.join(',');
15168
15169         if(this.hiddenField){
15170             this.hiddenField.dom.value = this.value;
15171         }
15172         
15173         this.store.fireEvent("datachanged", this.store);
15174         
15175         this.validate();
15176     },
15177     
15178     clearItem : function()
15179     {
15180         if(!this.multiple){
15181             return;
15182         }
15183         
15184         this.item = [];
15185         
15186         Roo.each(this.choices.select('>li.roo-select2-search-choice', true).elements, function(c){
15187            c.remove();
15188         });
15189         
15190         this.syncValue();
15191         
15192         this.validate();
15193         
15194         if(this.tickable && !Roo.isTouch){
15195             this.view.refresh();
15196         }
15197     },
15198     
15199     inputEl: function ()
15200     {
15201         if(Roo.isIOS && this.useNativeIOS){
15202             return this.el.select('select.roo-ios-select', true).first();
15203         }
15204         
15205         if(Roo.isTouch && this.mobileTouchView){
15206             return this.el.select('input.form-control',true).first();
15207         }
15208         
15209         if(this.tickable){
15210             return this.searchField;
15211         }
15212         
15213         return this.el.select('input.form-control',true).first();
15214     },
15215     
15216     onTickableFooterButtonClick : function(e, btn, el)
15217     {
15218         e.preventDefault();
15219         
15220         this.lastItem = Roo.apply([], this.item);
15221         
15222         if(btn && btn.name == 'cancel'){
15223             this.tickItems = Roo.apply([], this.item);
15224             this.collapse();
15225             return;
15226         }
15227         
15228         this.clearItem();
15229         
15230         var _this = this;
15231         
15232         Roo.each(this.tickItems, function(o){
15233             _this.addItem(o);
15234         });
15235         
15236         this.collapse();
15237         
15238     },
15239     
15240     validate : function()
15241     {
15242         if(this.getVisibilityEl().hasClass('hidden')){
15243             return true;
15244         }
15245         
15246         var v = this.getRawValue();
15247         
15248         if(this.multiple){
15249             v = this.getValue();
15250         }
15251         
15252         if(this.disabled || this.allowBlank || v.length){
15253             this.markValid();
15254             return true;
15255         }
15256         
15257         this.markInvalid();
15258         return false;
15259     },
15260     
15261     tickableInputEl : function()
15262     {
15263         if(!this.tickable || !this.editable){
15264             return this.inputEl();
15265         }
15266         
15267         return this.inputEl().select('.roo-select2-search-field-input', true).first();
15268     },
15269     
15270     
15271     getAutoCreateTouchView : function()
15272     {
15273         var id = Roo.id();
15274         
15275         var cfg = {
15276             cls: 'form-group' //input-group
15277         };
15278         
15279         var input =  {
15280             tag: 'input',
15281             id : id,
15282             type : this.inputType,
15283             cls : 'form-control x-combo-noedit',
15284             autocomplete: 'new-password',
15285             placeholder : this.placeholder || '',
15286             readonly : true
15287         };
15288         
15289         if (this.name) {
15290             input.name = this.name;
15291         }
15292         
15293         if (this.size) {
15294             input.cls += ' input-' + this.size;
15295         }
15296         
15297         if (this.disabled) {
15298             input.disabled = true;
15299         }
15300         
15301         var inputblock = {
15302             cls : '',
15303             cn : [
15304                 input
15305             ]
15306         };
15307         
15308         if(this.before){
15309             inputblock.cls += ' input-group';
15310             
15311             inputblock.cn.unshift({
15312                 tag :'span',
15313                 cls : 'input-group-addon input-group-prepend input-group-text',
15314                 html : this.before
15315             });
15316         }
15317         
15318         if(this.removable && !this.multiple){
15319             inputblock.cls += ' roo-removable';
15320             
15321             inputblock.cn.push({
15322                 tag: 'button',
15323                 html : 'x',
15324                 cls : 'roo-combo-removable-btn close'
15325             });
15326         }
15327
15328         if(this.hasFeedback && !this.allowBlank){
15329             
15330             inputblock.cls += ' has-feedback';
15331             
15332             inputblock.cn.push({
15333                 tag: 'span',
15334                 cls: 'glyphicon form-control-feedback'
15335             });
15336             
15337         }
15338         
15339         if (this.after) {
15340             
15341             inputblock.cls += (this.before) ? '' : ' input-group';
15342             
15343             inputblock.cn.push({
15344                 tag :'span',
15345                 cls : 'input-group-addon input-group-append input-group-text',
15346                 html : this.after
15347             });
15348         }
15349
15350         
15351         var ibwrap = inputblock;
15352         
15353         if(this.multiple){
15354             ibwrap = {
15355                 tag: 'ul',
15356                 cls: 'roo-select2-choices',
15357                 cn:[
15358                     {
15359                         tag: 'li',
15360                         cls: 'roo-select2-search-field',
15361                         cn: [
15362
15363                             inputblock
15364                         ]
15365                     }
15366                 ]
15367             };
15368         
15369             
15370         }
15371         
15372         var combobox = {
15373             cls: 'roo-select2-container input-group roo-touchview-combobox ',
15374             cn: [
15375                 {
15376                     tag: 'input',
15377                     type : 'hidden',
15378                     cls: 'form-hidden-field'
15379                 },
15380                 ibwrap
15381             ]
15382         };
15383         
15384         if(!this.multiple && this.showToggleBtn){
15385             
15386             var caret = {
15387                 cls: 'caret'
15388             };
15389             
15390             if (this.caret != false) {
15391                 caret = {
15392                      tag: 'i',
15393                      cls: 'fa fa-' + this.caret
15394                 };
15395                 
15396             }
15397             
15398             combobox.cn.push({
15399                 tag :'span',
15400                 cls : 'input-group-addon input-group-append input-group-text btn dropdown-toggle',
15401                 cn : [
15402                     Roo.bootstrap.version == 3 ? caret : '',
15403                     {
15404                         tag: 'span',
15405                         cls: 'combobox-clear',
15406                         cn  : [
15407                             {
15408                                 tag : 'i',
15409                                 cls: 'icon-remove'
15410                             }
15411                         ]
15412                     }
15413                 ]
15414
15415             })
15416         }
15417         
15418         if(this.multiple){
15419             combobox.cls += ' roo-select2-container-multi';
15420         }
15421         
15422         var align = this.labelAlign || this.parentLabelAlign();
15423         
15424         if (align ==='left' && this.fieldLabel.length) {
15425
15426             cfg.cn = [
15427                 {
15428                    tag : 'i',
15429                    cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
15430                    tooltip : 'This field is required'
15431                 },
15432                 {
15433                     tag: 'label',
15434                     cls : 'control-label col-form-label',
15435                     html : this.fieldLabel
15436
15437                 },
15438                 {
15439                     cls : '', 
15440                     cn: [
15441                         combobox
15442                     ]
15443                 }
15444             ];
15445             
15446             var labelCfg = cfg.cn[1];
15447             var contentCfg = cfg.cn[2];
15448             
15449
15450             if(this.indicatorpos == 'right'){
15451                 cfg.cn = [
15452                     {
15453                         tag: 'label',
15454                         'for' :  id,
15455                         cls : 'control-label col-form-label',
15456                         cn : [
15457                             {
15458                                 tag : 'span',
15459                                 html : this.fieldLabel
15460                             },
15461                             {
15462                                 tag : 'i',
15463                                 cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
15464                                 tooltip : 'This field is required'
15465                             }
15466                         ]
15467                     },
15468                     {
15469                         cls : "",
15470                         cn: [
15471                             combobox
15472                         ]
15473                     }
15474
15475                 ];
15476                 
15477                 labelCfg = cfg.cn[0];
15478                 contentCfg = cfg.cn[1];
15479             }
15480             
15481            
15482             
15483             if(this.labelWidth > 12){
15484                 labelCfg.style = "width: " + this.labelWidth + 'px';
15485             }
15486             
15487             if(this.labelWidth < 13 && this.labelmd == 0){
15488                 this.labelmd = this.labelWidth;
15489             }
15490             
15491             if(this.labellg > 0){
15492                 labelCfg.cls += ' col-lg-' + this.labellg;
15493                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
15494             }
15495             
15496             if(this.labelmd > 0){
15497                 labelCfg.cls += ' col-md-' + this.labelmd;
15498                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
15499             }
15500             
15501             if(this.labelsm > 0){
15502                 labelCfg.cls += ' col-sm-' + this.labelsm;
15503                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
15504             }
15505             
15506             if(this.labelxs > 0){
15507                 labelCfg.cls += ' col-xs-' + this.labelxs;
15508                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
15509             }
15510                 
15511                 
15512         } else if ( this.fieldLabel.length) {
15513             cfg.cn = [
15514                 {
15515                    tag : 'i',
15516                    cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
15517                    tooltip : 'This field is required'
15518                 },
15519                 {
15520                     tag: 'label',
15521                     cls : 'control-label',
15522                     html : this.fieldLabel
15523
15524                 },
15525                 {
15526                     cls : '', 
15527                     cn: [
15528                         combobox
15529                     ]
15530                 }
15531             ];
15532             
15533             if(this.indicatorpos == 'right'){
15534                 cfg.cn = [
15535                     {
15536                         tag: 'label',
15537                         cls : 'control-label',
15538                         html : this.fieldLabel,
15539                         cn : [
15540                             {
15541                                tag : 'i',
15542                                cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
15543                                tooltip : 'This field is required'
15544                             }
15545                         ]
15546                     },
15547                     {
15548                         cls : '', 
15549                         cn: [
15550                             combobox
15551                         ]
15552                     }
15553                 ];
15554             }
15555         } else {
15556             cfg.cn = combobox;    
15557         }
15558         
15559         
15560         var settings = this;
15561         
15562         ['xs','sm','md','lg'].map(function(size){
15563             if (settings[size]) {
15564                 cfg.cls += ' col-' + size + '-' + settings[size];
15565             }
15566         });
15567         
15568         return cfg;
15569     },
15570     
15571     initTouchView : function()
15572     {
15573         this.renderTouchView();
15574         
15575         this.touchViewEl.on('scroll', function(){
15576             this.el.dom.scrollTop = 0;
15577         }, this);
15578         
15579         this.originalValue = this.getValue();
15580         
15581         this.triggerEl = this.el.select('span.dropdown-toggle',true).first();
15582         
15583         this.inputEl().on("click", this.showTouchView, this);
15584         if (this.triggerEl) {
15585             this.triggerEl.on("click", this.showTouchView, this);
15586         }
15587         
15588         
15589         this.touchViewFooterEl.select('.roo-touch-view-cancel', true).first().on('click', this.hideTouchView, this);
15590         this.touchViewFooterEl.select('.roo-touch-view-ok', true).first().on('click', this.setTouchViewValue, this);
15591         
15592         this.maskEl = new Roo.LoadMask(this.touchViewEl, { store : this.store, msgCls: 'roo-el-mask-msg' });
15593         
15594         this.store.on('beforeload', this.onTouchViewBeforeLoad, this);
15595         this.store.on('load', this.onTouchViewLoad, this);
15596         this.store.on('loadexception', this.onTouchViewLoadException, this);
15597         
15598         if(this.hiddenName){
15599             
15600             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
15601             
15602             this.hiddenField.dom.value =
15603                 this.hiddenValue !== undefined ? this.hiddenValue :
15604                 this.value !== undefined ? this.value : '';
15605         
15606             this.el.dom.removeAttribute('name');
15607             this.hiddenField.dom.setAttribute('name', this.hiddenName);
15608         }
15609         
15610         if(this.multiple){
15611             this.choices = this.el.select('ul.roo-select2-choices', true).first();
15612             this.searchField = this.el.select('ul li.roo-select2-search-field', true).first();
15613         }
15614         
15615         if(this.removable && !this.multiple){
15616             var close = this.closeTriggerEl();
15617             if(close){
15618                 close.setVisibilityMode(Roo.Element.DISPLAY).hide();
15619                 close.on('click', this.removeBtnClick, this, close);
15620             }
15621         }
15622         /*
15623          * fix the bug in Safari iOS8
15624          */
15625         this.inputEl().on("focus", function(e){
15626             document.activeElement.blur();
15627         }, this);
15628         
15629         this._touchViewMask = Roo.DomHelper.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
15630         
15631         return;
15632         
15633         
15634     },
15635     
15636     renderTouchView : function()
15637     {
15638         this.touchViewEl = Roo.get(document.body).createChild(Roo.bootstrap.ComboBox.touchViewTemplate);
15639         this.touchViewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
15640         
15641         this.touchViewHeaderEl = this.touchViewEl.select('.modal-header', true).first();
15642         this.touchViewHeaderEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
15643         
15644         this.touchViewBodyEl = this.touchViewEl.select('.modal-body', true).first();
15645         this.touchViewBodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
15646         this.touchViewBodyEl.setStyle('overflow', 'auto');
15647         
15648         this.touchViewListGroup = this.touchViewBodyEl.select('.list-group', true).first();
15649         this.touchViewListGroup.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
15650         
15651         this.touchViewFooterEl = this.touchViewEl.select('.modal-footer', true).first();
15652         this.touchViewFooterEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
15653         
15654     },
15655     
15656     showTouchView : function()
15657     {
15658         if(this.disabled){
15659             return;
15660         }
15661         
15662         this.touchViewHeaderEl.hide();
15663
15664         if(this.modalTitle.length){
15665             this.touchViewHeaderEl.dom.innerHTML = this.modalTitle;
15666             this.touchViewHeaderEl.show();
15667         }
15668
15669         this.touchViewEl.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
15670         this.touchViewEl.show();
15671
15672         this.touchViewEl.select('.modal-dialog', true).first().setStyle({ margin : '0px', width : '100%'});
15673         
15674         //this.touchViewEl.select('.modal-dialog > .modal-content', true).first().setSize(
15675         //        Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
15676
15677         var bodyHeight = Roo.lib.Dom.getViewHeight() - this.touchViewFooterEl.getHeight() + this.touchViewBodyEl.getPadding('tb');
15678
15679         if(this.modalTitle.length){
15680             bodyHeight = bodyHeight - this.touchViewHeaderEl.getHeight();
15681         }
15682         
15683         this.touchViewBodyEl.setHeight(bodyHeight);
15684
15685         if(this.animate){
15686             var _this = this;
15687             (function(){ _this.touchViewEl.addClass('in'); }).defer(50);
15688         }else{
15689             this.touchViewEl.addClass('in');
15690         }
15691         
15692         if(this._touchViewMask){
15693             Roo.get(document.body).addClass("x-body-masked");
15694             this._touchViewMask.setSize(Roo.lib.Dom.getViewWidth(true),   Roo.lib.Dom.getViewHeight(true));
15695             this._touchViewMask.setStyle('z-index', 10000);
15696             this._touchViewMask.addClass('show');
15697         }
15698         
15699         this.doTouchViewQuery();
15700         
15701     },
15702     
15703     hideTouchView : function()
15704     {
15705         this.touchViewEl.removeClass('in');
15706
15707         if(this.animate){
15708             var _this = this;
15709             (function(){ _this.touchViewEl.setStyle('display', 'none'); }).defer(150);
15710         }else{
15711             this.touchViewEl.setStyle('display', 'none');
15712         }
15713         
15714         if(this._touchViewMask){
15715             this._touchViewMask.removeClass('show');
15716             Roo.get(document.body).removeClass("x-body-masked");
15717         }
15718     },
15719     
15720     setTouchViewValue : function()
15721     {
15722         if(this.multiple){
15723             this.clearItem();
15724         
15725             var _this = this;
15726
15727             Roo.each(this.tickItems, function(o){
15728                 this.addItem(o);
15729             }, this);
15730         }
15731         
15732         this.hideTouchView();
15733     },
15734     
15735     doTouchViewQuery : function()
15736     {
15737         var qe = {
15738             query: '',
15739             forceAll: true,
15740             combo: this,
15741             cancel:false
15742         };
15743         
15744         if(this.fireEvent('beforequery', qe) ===false || qe.cancel){
15745             return false;
15746         }
15747         
15748         if(!this.alwaysQuery || this.mode == 'local'){
15749             this.onTouchViewLoad();
15750             return;
15751         }
15752         
15753         this.store.load();
15754     },
15755     
15756     onTouchViewBeforeLoad : function(combo,opts)
15757     {
15758         return;
15759     },
15760
15761     // private
15762     onTouchViewLoad : function()
15763     {
15764         if(this.store.getCount() < 1){
15765             this.onTouchViewEmptyResults();
15766             return;
15767         }
15768         
15769         this.clearTouchView();
15770         
15771         var rawValue = this.getRawValue();
15772         
15773         var template = (this.multiple) ? Roo.bootstrap.ComboBox.listItemCheckbox : Roo.bootstrap.ComboBox.listItemRadio;
15774         
15775         this.tickItems = [];
15776         
15777         this.store.data.each(function(d, rowIndex){
15778             var row = this.touchViewListGroup.createChild(template);
15779             
15780             if(typeof(d.data.cls) != 'undefined' && d.data.cls.length){
15781                 row.addClass(d.data.cls);
15782             }
15783             
15784             if(this.displayField && typeof(d.data[this.displayField]) != 'undefined'){
15785                 var cfg = {
15786                     data : d.data,
15787                     html : d.data[this.displayField]
15788                 };
15789                 
15790                 if(this.fireEvent('touchviewdisplay', this, cfg) !== false){
15791                     row.select('.roo-combobox-list-group-item-value', true).first().dom.innerHTML = cfg.html;
15792                 }
15793             }
15794             row.removeClass('selected');
15795             if(!this.multiple && this.valueField &&
15796                     typeof(d.data[this.valueField]) != 'undefined' && d.data[this.valueField] == this.getValue())
15797             {
15798                 // radio buttons..
15799                 row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
15800                 row.addClass('selected');
15801             }
15802             
15803             if(this.multiple && this.valueField &&
15804                     typeof(d.data[this.valueField]) != 'undefined' && this.getValue().indexOf(d.data[this.valueField]) != -1)
15805             {
15806                 
15807                 // checkboxes...
15808                 row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
15809                 this.tickItems.push(d.data);
15810             }
15811             
15812             row.on('click', this.onTouchViewClick, this, {row : row, rowIndex : rowIndex});
15813             
15814         }, this);
15815         
15816         var firstChecked = this.touchViewListGroup.select('.list-group-item > .roo-combobox-list-group-item-box > input:checked', true).first();
15817         
15818         var bodyHeight = Roo.lib.Dom.getViewHeight() - this.touchViewFooterEl.getHeight() + this.touchViewBodyEl.getPadding('tb');
15819
15820         if(this.modalTitle.length){
15821             bodyHeight = bodyHeight - this.touchViewHeaderEl.getHeight();
15822         }
15823
15824         var listHeight = this.touchViewListGroup.getHeight() + this.touchViewBodyEl.getPadding('tb') * 2;
15825         
15826         if(this.mobile_restrict_height && listHeight < bodyHeight){
15827             this.touchViewBodyEl.setHeight(listHeight);
15828         }
15829         
15830         var _this = this;
15831         
15832         if(firstChecked && listHeight > bodyHeight){
15833             (function() { firstChecked.findParent('li').scrollIntoView(_this.touchViewListGroup.dom); }).defer(500);
15834         }
15835         
15836     },
15837     
15838     onTouchViewLoadException : function()
15839     {
15840         this.hideTouchView();
15841     },
15842     
15843     onTouchViewEmptyResults : function()
15844     {
15845         this.clearTouchView();
15846         
15847         this.touchViewListGroup.createChild(Roo.bootstrap.ComboBox.emptyResult);
15848         
15849         this.touchViewListGroup.select('.roo-combobox-touch-view-empty-result', true).first().dom.innerHTML = this.emptyResultText;
15850         
15851     },
15852     
15853     clearTouchView : function()
15854     {
15855         this.touchViewListGroup.dom.innerHTML = '';
15856     },
15857     
15858     onTouchViewClick : function(e, el, o)
15859     {
15860         e.preventDefault();
15861         
15862         var row = o.row;
15863         var rowIndex = o.rowIndex;
15864         
15865         var r = this.store.getAt(rowIndex);
15866         
15867         if(this.fireEvent('beforeselect', this, r, rowIndex) !== false){
15868             
15869             if(!this.multiple){
15870                 Roo.each(this.touchViewListGroup.select('.list-group-item > .roo-combobox-list-group-item-box > input:checked', true).elements, function(c){
15871                     c.dom.removeAttribute('checked');
15872                 }, this);
15873
15874                 row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
15875
15876                 this.setFromData(r.data);
15877
15878                 var close = this.closeTriggerEl();
15879
15880                 if(close){
15881                     close.show();
15882                 }
15883
15884                 this.hideTouchView();
15885
15886                 this.fireEvent('select', this, r, rowIndex);
15887
15888                 return;
15889             }
15890
15891             if(this.valueField && typeof(r.data[this.valueField]) != 'undefined' && this.getValue().indexOf(r.data[this.valueField]) != -1){
15892                 row.select('.roo-combobox-list-group-item-box > input', true).first().dom.removeAttribute('checked');
15893                 this.tickItems.splice(this.tickItems.indexOf(r.data), 1);
15894                 return;
15895             }
15896
15897             row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
15898             this.addItem(r.data);
15899             this.tickItems.push(r.data);
15900         }
15901     },
15902     
15903     getAutoCreateNativeIOS : function()
15904     {
15905         var cfg = {
15906             cls: 'form-group' //input-group,
15907         };
15908         
15909         var combobox =  {
15910             tag: 'select',
15911             cls : 'roo-ios-select'
15912         };
15913         
15914         if (this.name) {
15915             combobox.name = this.name;
15916         }
15917         
15918         if (this.disabled) {
15919             combobox.disabled = true;
15920         }
15921         
15922         var settings = this;
15923         
15924         ['xs','sm','md','lg'].map(function(size){
15925             if (settings[size]) {
15926                 cfg.cls += ' col-' + size + '-' + settings[size];
15927             }
15928         });
15929         
15930         cfg.cn = combobox;
15931         
15932         return cfg;
15933         
15934     },
15935     
15936     initIOSView : function()
15937     {
15938         this.store.on('load', this.onIOSViewLoad, this);
15939         
15940         return;
15941     },
15942     
15943     onIOSViewLoad : function()
15944     {
15945         if(this.store.getCount() < 1){
15946             return;
15947         }
15948         
15949         this.clearIOSView();
15950         
15951         if(this.allowBlank) {
15952             
15953             var default_text = '-- SELECT --';
15954             
15955             if(this.placeholder.length){
15956                 default_text = this.placeholder;
15957             }
15958             
15959             if(this.emptyTitle.length){
15960                 default_text += ' - ' + this.emptyTitle + ' -';
15961             }
15962             
15963             var opt = this.inputEl().createChild({
15964                 tag: 'option',
15965                 value : 0,
15966                 html : default_text
15967             });
15968             
15969             var o = {};
15970             o[this.valueField] = 0;
15971             o[this.displayField] = default_text;
15972             
15973             this.ios_options.push({
15974                 data : o,
15975                 el : opt
15976             });
15977             
15978         }
15979         
15980         this.store.data.each(function(d, rowIndex){
15981             
15982             var html = '';
15983             
15984             if(this.displayField && typeof(d.data[this.displayField]) != 'undefined'){
15985                 html = d.data[this.displayField];
15986             }
15987             
15988             var value = '';
15989             
15990             if(this.valueField && typeof(d.data[this.valueField]) != 'undefined'){
15991                 value = d.data[this.valueField];
15992             }
15993             
15994             var option = {
15995                 tag: 'option',
15996                 value : value,
15997                 html : html
15998             };
15999             
16000             if(this.value == d.data[this.valueField]){
16001                 option['selected'] = true;
16002             }
16003             
16004             var opt = this.inputEl().createChild(option);
16005             
16006             this.ios_options.push({
16007                 data : d.data,
16008                 el : opt
16009             });
16010             
16011         }, this);
16012         
16013         this.inputEl().on('change', function(){
16014            this.fireEvent('select', this);
16015         }, this);
16016         
16017     },
16018     
16019     clearIOSView: function()
16020     {
16021         this.inputEl().dom.innerHTML = '';
16022         
16023         this.ios_options = [];
16024     },
16025     
16026     setIOSValue: function(v)
16027     {
16028         this.value = v;
16029         
16030         if(!this.ios_options){
16031             return;
16032         }
16033         
16034         Roo.each(this.ios_options, function(opts){
16035            
16036            opts.el.dom.removeAttribute('selected');
16037            
16038            if(opts.data[this.valueField] != v){
16039                return;
16040            }
16041            
16042            opts.el.dom.setAttribute('selected', true);
16043            
16044         }, this);
16045     }
16046
16047     /** 
16048     * @cfg {Boolean} grow 
16049     * @hide 
16050     */
16051     /** 
16052     * @cfg {Number} growMin 
16053     * @hide 
16054     */
16055     /** 
16056     * @cfg {Number} growMax 
16057     * @hide 
16058     */
16059     /**
16060      * @hide
16061      * @method autoSize
16062      */
16063 });
16064
16065 Roo.apply(Roo.bootstrap.ComboBox,  {
16066     
16067     header : {
16068         tag: 'div',
16069         cls: 'modal-header',
16070         cn: [
16071             {
16072                 tag: 'h4',
16073                 cls: 'modal-title'
16074             }
16075         ]
16076     },
16077     
16078     body : {
16079         tag: 'div',
16080         cls: 'modal-body',
16081         cn: [
16082             {
16083                 tag: 'ul',
16084                 cls: 'list-group'
16085             }
16086         ]
16087     },
16088     
16089     listItemRadio : {
16090         tag: 'li',
16091         cls: 'list-group-item',
16092         cn: [
16093             {
16094                 tag: 'span',
16095                 cls: 'roo-combobox-list-group-item-value'
16096             },
16097             {
16098                 tag: 'div',
16099                 cls: 'roo-combobox-list-group-item-box pull-xs-right radio-inline radio radio-info',
16100                 cn: [
16101                     {
16102                         tag: 'input',
16103                         type: 'radio'
16104                     },
16105                     {
16106                         tag: 'label'
16107                     }
16108                 ]
16109             }
16110         ]
16111     },
16112     
16113     listItemCheckbox : {
16114         tag: 'li',
16115         cls: 'list-group-item',
16116         cn: [
16117             {
16118                 tag: 'span',
16119                 cls: 'roo-combobox-list-group-item-value'
16120             },
16121             {
16122                 tag: 'div',
16123                 cls: 'roo-combobox-list-group-item-box pull-xs-right checkbox-inline checkbox checkbox-info',
16124                 cn: [
16125                     {
16126                         tag: 'input',
16127                         type: 'checkbox'
16128                     },
16129                     {
16130                         tag: 'label'
16131                     }
16132                 ]
16133             }
16134         ]
16135     },
16136     
16137     emptyResult : {
16138         tag: 'div',
16139         cls: 'alert alert-danger roo-combobox-touch-view-empty-result'
16140     },
16141     
16142     footer : {
16143         tag: 'div',
16144         cls: 'modal-footer',
16145         cn: [
16146             {
16147                 tag: 'div',
16148                 cls: 'row',
16149                 cn: [
16150                     {
16151                         tag: 'div',
16152                         cls: 'col-xs-6 text-left',
16153                         cn: {
16154                             tag: 'button',
16155                             cls: 'btn btn-danger roo-touch-view-cancel',
16156                             html: 'Cancel'
16157                         }
16158                     },
16159                     {
16160                         tag: 'div',
16161                         cls: 'col-xs-6 text-right',
16162                         cn: {
16163                             tag: 'button',
16164                             cls: 'btn btn-success roo-touch-view-ok',
16165                             html: 'OK'
16166                         }
16167                     }
16168                 ]
16169             }
16170         ]
16171         
16172     }
16173 });
16174
16175 Roo.apply(Roo.bootstrap.ComboBox,  {
16176     
16177     touchViewTemplate : {
16178         tag: 'div',
16179         cls: 'modal fade roo-combobox-touch-view',
16180         cn: [
16181             {
16182                 tag: 'div',
16183                 cls: 'modal-dialog',
16184                 style : 'position:fixed', // we have to fix position....
16185                 cn: [
16186                     {
16187                         tag: 'div',
16188                         cls: 'modal-content',
16189                         cn: [
16190                             Roo.bootstrap.ComboBox.header,
16191                             Roo.bootstrap.ComboBox.body,
16192                             Roo.bootstrap.ComboBox.footer
16193                         ]
16194                     }
16195                 ]
16196             }
16197         ]
16198     }
16199 });/*
16200  * Based on:
16201  * Ext JS Library 1.1.1
16202  * Copyright(c) 2006-2007, Ext JS, LLC.
16203  *
16204  * Originally Released Under LGPL - original licence link has changed is not relivant.
16205  *
16206  * Fork - LGPL
16207  * <script type="text/javascript">
16208  */
16209
16210 /**
16211  * @class Roo.View
16212  * @extends Roo.util.Observable
16213  * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template. 
16214  * This class also supports single and multi selection modes. <br>
16215  * Create a data model bound view:
16216  <pre><code>
16217  var store = new Roo.data.Store(...);
16218
16219  var view = new Roo.View({
16220     el : "my-element",
16221     tpl : '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // auto create template
16222  
16223     singleSelect: true,
16224     selectedClass: "ydataview-selected",
16225     store: store
16226  });
16227
16228  // listen for node click?
16229  view.on("click", function(vw, index, node, e){
16230  alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
16231  });
16232
16233  // load XML data
16234  dataModel.load("foobar.xml");
16235  </code></pre>
16236  For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
16237  * <br><br>
16238  * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
16239  * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
16240  * 
16241  * Note: old style constructor is still suported (container, template, config)
16242  * 
16243  * @constructor
16244  * Create a new View
16245  * @param {Object} config The config object
16246  * 
16247  */
16248 Roo.View = function(config, depreciated_tpl, depreciated_config){
16249     
16250     this.parent = false;
16251     
16252     if (typeof(depreciated_tpl) == 'undefined') {
16253         // new way.. - universal constructor.
16254         Roo.apply(this, config);
16255         this.el  = Roo.get(this.el);
16256     } else {
16257         // old format..
16258         this.el  = Roo.get(config);
16259         this.tpl = depreciated_tpl;
16260         Roo.apply(this, depreciated_config);
16261     }
16262     this.wrapEl  = this.el.wrap().wrap();
16263     ///this.el = this.wrapEla.appendChild(document.createElement("div"));
16264     
16265     
16266     if(typeof(this.tpl) == "string"){
16267         this.tpl = new Roo.Template(this.tpl);
16268     } else {
16269         // support xtype ctors..
16270         this.tpl = new Roo.factory(this.tpl, Roo);
16271     }
16272     
16273     
16274     this.tpl.compile();
16275     
16276     /** @private */
16277     this.addEvents({
16278         /**
16279          * @event beforeclick
16280          * Fires before a click is processed. Returns false to cancel the default action.
16281          * @param {Roo.View} this
16282          * @param {Number} index The index of the target node
16283          * @param {HTMLElement} node The target node
16284          * @param {Roo.EventObject} e The raw event object
16285          */
16286             "beforeclick" : true,
16287         /**
16288          * @event click
16289          * Fires when a template node is clicked.
16290          * @param {Roo.View} this
16291          * @param {Number} index The index of the target node
16292          * @param {HTMLElement} node The target node
16293          * @param {Roo.EventObject} e The raw event object
16294          */
16295             "click" : true,
16296         /**
16297          * @event dblclick
16298          * Fires when a template node is double clicked.
16299          * @param {Roo.View} this
16300          * @param {Number} index The index of the target node
16301          * @param {HTMLElement} node The target node
16302          * @param {Roo.EventObject} e The raw event object
16303          */
16304             "dblclick" : true,
16305         /**
16306          * @event contextmenu
16307          * Fires when a template node is right clicked.
16308          * @param {Roo.View} this
16309          * @param {Number} index The index of the target node
16310          * @param {HTMLElement} node The target node
16311          * @param {Roo.EventObject} e The raw event object
16312          */
16313             "contextmenu" : true,
16314         /**
16315          * @event selectionchange
16316          * Fires when the selected nodes change.
16317          * @param {Roo.View} this
16318          * @param {Array} selections Array of the selected nodes
16319          */
16320             "selectionchange" : true,
16321     
16322         /**
16323          * @event beforeselect
16324          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
16325          * @param {Roo.View} this
16326          * @param {HTMLElement} node The node to be selected
16327          * @param {Array} selections Array of currently selected nodes
16328          */
16329             "beforeselect" : true,
16330         /**
16331          * @event preparedata
16332          * Fires on every row to render, to allow you to change the data.
16333          * @param {Roo.View} this
16334          * @param {Object} data to be rendered (change this)
16335          */
16336           "preparedata" : true
16337           
16338           
16339         });
16340
16341
16342
16343     this.el.on({
16344         "click": this.onClick,
16345         "dblclick": this.onDblClick,
16346         "contextmenu": this.onContextMenu,
16347         scope:this
16348     });
16349
16350     this.selections = [];
16351     this.nodes = [];
16352     this.cmp = new Roo.CompositeElementLite([]);
16353     if(this.store){
16354         this.store = Roo.factory(this.store, Roo.data);
16355         this.setStore(this.store, true);
16356     }
16357     
16358     if ( this.footer && this.footer.xtype) {
16359            
16360          var fctr = this.wrapEl.appendChild(document.createElement("div"));
16361         
16362         this.footer.dataSource = this.store;
16363         this.footer.container = fctr;
16364         this.footer = Roo.factory(this.footer, Roo);
16365         fctr.insertFirst(this.el);
16366         
16367         // this is a bit insane - as the paging toolbar seems to detach the el..
16368 //        dom.parentNode.parentNode.parentNode
16369          // they get detached?
16370     }
16371     
16372     
16373     Roo.View.superclass.constructor.call(this);
16374     
16375     
16376 };
16377
16378 Roo.extend(Roo.View, Roo.util.Observable, {
16379     
16380      /**
16381      * @cfg {Roo.data.Store} store Data store to load data from.
16382      */
16383     store : false,
16384     
16385     /**
16386      * @cfg {String|Roo.Element} el The container element.
16387      */
16388     el : '',
16389     
16390     /**
16391      * @cfg {String|Roo.Template} tpl The template used by this View 
16392      */
16393     tpl : false,
16394     /**
16395      * @cfg {String} dataName the named area of the template to use as the data area
16396      *                          Works with domtemplates roo-name="name"
16397      */
16398     dataName: false,
16399     /**
16400      * @cfg {String} selectedClass The css class to add to selected nodes
16401      */
16402     selectedClass : "x-view-selected",
16403      /**
16404      * @cfg {String} emptyText The empty text to show when nothing is loaded.
16405      */
16406     emptyText : "",
16407     
16408     /**
16409      * @cfg {String} text to display on mask (default Loading)
16410      */
16411     mask : false,
16412     /**
16413      * @cfg {Boolean} multiSelect Allow multiple selection
16414      */
16415     multiSelect : false,
16416     /**
16417      * @cfg {Boolean} singleSelect Allow single selection
16418      */
16419     singleSelect:  false,
16420     
16421     /**
16422      * @cfg {Boolean} toggleSelect - selecting 
16423      */
16424     toggleSelect : false,
16425     
16426     /**
16427      * @cfg {Boolean} tickable - selecting 
16428      */
16429     tickable : false,
16430     
16431     /**
16432      * Returns the element this view is bound to.
16433      * @return {Roo.Element}
16434      */
16435     getEl : function(){
16436         return this.wrapEl;
16437     },
16438     
16439     
16440
16441     /**
16442      * Refreshes the view. - called by datachanged on the store. - do not call directly.
16443      */
16444     refresh : function(){
16445         //Roo.log('refresh');
16446         var t = this.tpl;
16447         
16448         // if we are using something like 'domtemplate', then
16449         // the what gets used is:
16450         // t.applySubtemplate(NAME, data, wrapping data..)
16451         // the outer template then get' applied with
16452         //     the store 'extra data'
16453         // and the body get's added to the
16454         //      roo-name="data" node?
16455         //      <span class='roo-tpl-{name}'></span> ?????
16456         
16457         
16458         
16459         this.clearSelections();
16460         this.el.update("");
16461         var html = [];
16462         var records = this.store.getRange();
16463         if(records.length < 1) {
16464             
16465             // is this valid??  = should it render a template??
16466             
16467             this.el.update(this.emptyText);
16468             return;
16469         }
16470         var el = this.el;
16471         if (this.dataName) {
16472             this.el.update(t.apply(this.store.meta)); //????
16473             el = this.el.child('.roo-tpl-' + this.dataName);
16474         }
16475         
16476         for(var i = 0, len = records.length; i < len; i++){
16477             var data = this.prepareData(records[i].data, i, records[i]);
16478             this.fireEvent("preparedata", this, data, i, records[i]);
16479             
16480             var d = Roo.apply({}, data);
16481             
16482             if(this.tickable){
16483                 Roo.apply(d, {'roo-id' : Roo.id()});
16484                 
16485                 var _this = this;
16486             
16487                 Roo.each(this.parent.item, function(item){
16488                     if(item[_this.parent.valueField] != data[_this.parent.valueField]){
16489                         return;
16490                     }
16491                     Roo.apply(d, {'roo-data-checked' : 'checked'});
16492                 });
16493             }
16494             
16495             html[html.length] = Roo.util.Format.trim(
16496                 this.dataName ?
16497                     t.applySubtemplate(this.dataName, d, this.store.meta) :
16498                     t.apply(d)
16499             );
16500         }
16501         
16502         
16503         
16504         el.update(html.join(""));
16505         this.nodes = el.dom.childNodes;
16506         this.updateIndexes(0);
16507     },
16508     
16509
16510     /**
16511      * Function to override to reformat the data that is sent to
16512      * the template for each node.
16513      * DEPRICATED - use the preparedata event handler.
16514      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
16515      * a JSON object for an UpdateManager bound view).
16516      */
16517     prepareData : function(data, index, record)
16518     {
16519         this.fireEvent("preparedata", this, data, index, record);
16520         return data;
16521     },
16522
16523     onUpdate : function(ds, record){
16524         // Roo.log('on update');   
16525         this.clearSelections();
16526         var index = this.store.indexOf(record);
16527         var n = this.nodes[index];
16528         this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
16529         n.parentNode.removeChild(n);
16530         this.updateIndexes(index, index);
16531     },
16532
16533     
16534     
16535 // --------- FIXME     
16536     onAdd : function(ds, records, index)
16537     {
16538         //Roo.log(['on Add', ds, records, index] );        
16539         this.clearSelections();
16540         if(this.nodes.length == 0){
16541             this.refresh();
16542             return;
16543         }
16544         var n = this.nodes[index];
16545         for(var i = 0, len = records.length; i < len; i++){
16546             var d = this.prepareData(records[i].data, i, records[i]);
16547             if(n){
16548                 this.tpl.insertBefore(n, d);
16549             }else{
16550                 
16551                 this.tpl.append(this.el, d);
16552             }
16553         }
16554         this.updateIndexes(index);
16555     },
16556
16557     onRemove : function(ds, record, index){
16558        // Roo.log('onRemove');
16559         this.clearSelections();
16560         var el = this.dataName  ?
16561             this.el.child('.roo-tpl-' + this.dataName) :
16562             this.el; 
16563         
16564         el.dom.removeChild(this.nodes[index]);
16565         this.updateIndexes(index);
16566     },
16567
16568     /**
16569      * Refresh an individual node.
16570      * @param {Number} index
16571      */
16572     refreshNode : function(index){
16573         this.onUpdate(this.store, this.store.getAt(index));
16574     },
16575
16576     updateIndexes : function(startIndex, endIndex){
16577         var ns = this.nodes;
16578         startIndex = startIndex || 0;
16579         endIndex = endIndex || ns.length - 1;
16580         for(var i = startIndex; i <= endIndex; i++){
16581             ns[i].nodeIndex = i;
16582         }
16583     },
16584
16585     /**
16586      * Changes the data store this view uses and refresh the view.
16587      * @param {Store} store
16588      */
16589     setStore : function(store, initial){
16590         if(!initial && this.store){
16591             this.store.un("datachanged", this.refresh);
16592             this.store.un("add", this.onAdd);
16593             this.store.un("remove", this.onRemove);
16594             this.store.un("update", this.onUpdate);
16595             this.store.un("clear", this.refresh);
16596             this.store.un("beforeload", this.onBeforeLoad);
16597             this.store.un("load", this.onLoad);
16598             this.store.un("loadexception", this.onLoad);
16599         }
16600         if(store){
16601           
16602             store.on("datachanged", this.refresh, this);
16603             store.on("add", this.onAdd, this);
16604             store.on("remove", this.onRemove, this);
16605             store.on("update", this.onUpdate, this);
16606             store.on("clear", this.refresh, this);
16607             store.on("beforeload", this.onBeforeLoad, this);
16608             store.on("load", this.onLoad, this);
16609             store.on("loadexception", this.onLoad, this);
16610         }
16611         
16612         if(store){
16613             this.refresh();
16614         }
16615     },
16616     /**
16617      * onbeforeLoad - masks the loading area.
16618      *
16619      */
16620     onBeforeLoad : function(store,opts)
16621     {
16622          //Roo.log('onBeforeLoad');   
16623         if (!opts.add) {
16624             this.el.update("");
16625         }
16626         this.el.mask(this.mask ? this.mask : "Loading" ); 
16627     },
16628     onLoad : function ()
16629     {
16630         this.el.unmask();
16631     },
16632     
16633
16634     /**
16635      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
16636      * @param {HTMLElement} node
16637      * @return {HTMLElement} The template node
16638      */
16639     findItemFromChild : function(node){
16640         var el = this.dataName  ?
16641             this.el.child('.roo-tpl-' + this.dataName,true) :
16642             this.el.dom; 
16643         
16644         if(!node || node.parentNode == el){
16645                     return node;
16646             }
16647             var p = node.parentNode;
16648             while(p && p != el){
16649             if(p.parentNode == el){
16650                 return p;
16651             }
16652             p = p.parentNode;
16653         }
16654             return null;
16655     },
16656
16657     /** @ignore */
16658     onClick : function(e){
16659         var item = this.findItemFromChild(e.getTarget());
16660         if(item){
16661             var index = this.indexOf(item);
16662             if(this.onItemClick(item, index, e) !== false){
16663                 this.fireEvent("click", this, index, item, e);
16664             }
16665         }else{
16666             this.clearSelections();
16667         }
16668     },
16669
16670     /** @ignore */
16671     onContextMenu : function(e){
16672         var item = this.findItemFromChild(e.getTarget());
16673         if(item){
16674             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
16675         }
16676     },
16677
16678     /** @ignore */
16679     onDblClick : function(e){
16680         var item = this.findItemFromChild(e.getTarget());
16681         if(item){
16682             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
16683         }
16684     },
16685
16686     onItemClick : function(item, index, e)
16687     {
16688         if(this.fireEvent("beforeclick", this, index, item, e) === false){
16689             return false;
16690         }
16691         if (this.toggleSelect) {
16692             var m = this.isSelected(item) ? 'unselect' : 'select';
16693             //Roo.log(m);
16694             var _t = this;
16695             _t[m](item, true, false);
16696             return true;
16697         }
16698         if(this.multiSelect || this.singleSelect){
16699             if(this.multiSelect && e.shiftKey && this.lastSelection){
16700                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
16701             }else{
16702                 this.select(item, this.multiSelect && e.ctrlKey);
16703                 this.lastSelection = item;
16704             }
16705             
16706             if(!this.tickable){
16707                 e.preventDefault();
16708             }
16709             
16710         }
16711         return true;
16712     },
16713
16714     /**
16715      * Get the number of selected nodes.
16716      * @return {Number}
16717      */
16718     getSelectionCount : function(){
16719         return this.selections.length;
16720     },
16721
16722     /**
16723      * Get the currently selected nodes.
16724      * @return {Array} An array of HTMLElements
16725      */
16726     getSelectedNodes : function(){
16727         return this.selections;
16728     },
16729
16730     /**
16731      * Get the indexes of the selected nodes.
16732      * @return {Array}
16733      */
16734     getSelectedIndexes : function(){
16735         var indexes = [], s = this.selections;
16736         for(var i = 0, len = s.length; i < len; i++){
16737             indexes.push(s[i].nodeIndex);
16738         }
16739         return indexes;
16740     },
16741
16742     /**
16743      * Clear all selections
16744      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
16745      */
16746     clearSelections : function(suppressEvent){
16747         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
16748             this.cmp.elements = this.selections;
16749             this.cmp.removeClass(this.selectedClass);
16750             this.selections = [];
16751             if(!suppressEvent){
16752                 this.fireEvent("selectionchange", this, this.selections);
16753             }
16754         }
16755     },
16756
16757     /**
16758      * Returns true if the passed node is selected
16759      * @param {HTMLElement/Number} node The node or node index
16760      * @return {Boolean}
16761      */
16762     isSelected : function(node){
16763         var s = this.selections;
16764         if(s.length < 1){
16765             return false;
16766         }
16767         node = this.getNode(node);
16768         return s.indexOf(node) !== -1;
16769     },
16770
16771     /**
16772      * Selects nodes.
16773      * @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
16774      * @param {Boolean} keepExisting (optional) true to keep existing selections
16775      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
16776      */
16777     select : function(nodeInfo, keepExisting, suppressEvent){
16778         if(nodeInfo instanceof Array){
16779             if(!keepExisting){
16780                 this.clearSelections(true);
16781             }
16782             for(var i = 0, len = nodeInfo.length; i < len; i++){
16783                 this.select(nodeInfo[i], true, true);
16784             }
16785             return;
16786         } 
16787         var node = this.getNode(nodeInfo);
16788         if(!node || this.isSelected(node)){
16789             return; // already selected.
16790         }
16791         if(!keepExisting){
16792             this.clearSelections(true);
16793         }
16794         
16795         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
16796             Roo.fly(node).addClass(this.selectedClass);
16797             this.selections.push(node);
16798             if(!suppressEvent){
16799                 this.fireEvent("selectionchange", this, this.selections);
16800             }
16801         }
16802         
16803         
16804     },
16805       /**
16806      * Unselects nodes.
16807      * @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
16808      * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
16809      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
16810      */
16811     unselect : function(nodeInfo, keepExisting, suppressEvent)
16812     {
16813         if(nodeInfo instanceof Array){
16814             Roo.each(this.selections, function(s) {
16815                 this.unselect(s, nodeInfo);
16816             }, this);
16817             return;
16818         }
16819         var node = this.getNode(nodeInfo);
16820         if(!node || !this.isSelected(node)){
16821             //Roo.log("not selected");
16822             return; // not selected.
16823         }
16824         // fireevent???
16825         var ns = [];
16826         Roo.each(this.selections, function(s) {
16827             if (s == node ) {
16828                 Roo.fly(node).removeClass(this.selectedClass);
16829
16830                 return;
16831             }
16832             ns.push(s);
16833         },this);
16834         
16835         this.selections= ns;
16836         this.fireEvent("selectionchange", this, this.selections);
16837     },
16838
16839     /**
16840      * Gets a template node.
16841      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
16842      * @return {HTMLElement} The node or null if it wasn't found
16843      */
16844     getNode : function(nodeInfo){
16845         if(typeof nodeInfo == "string"){
16846             return document.getElementById(nodeInfo);
16847         }else if(typeof nodeInfo == "number"){
16848             return this.nodes[nodeInfo];
16849         }
16850         return nodeInfo;
16851     },
16852
16853     /**
16854      * Gets a range template nodes.
16855      * @param {Number} startIndex
16856      * @param {Number} endIndex
16857      * @return {Array} An array of nodes
16858      */
16859     getNodes : function(start, end){
16860         var ns = this.nodes;
16861         start = start || 0;
16862         end = typeof end == "undefined" ? ns.length - 1 : end;
16863         var nodes = [];
16864         if(start <= end){
16865             for(var i = start; i <= end; i++){
16866                 nodes.push(ns[i]);
16867             }
16868         } else{
16869             for(var i = start; i >= end; i--){
16870                 nodes.push(ns[i]);
16871             }
16872         }
16873         return nodes;
16874     },
16875
16876     /**
16877      * Finds the index of the passed node
16878      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
16879      * @return {Number} The index of the node or -1
16880      */
16881     indexOf : function(node){
16882         node = this.getNode(node);
16883         if(typeof node.nodeIndex == "number"){
16884             return node.nodeIndex;
16885         }
16886         var ns = this.nodes;
16887         for(var i = 0, len = ns.length; i < len; i++){
16888             if(ns[i] == node){
16889                 return i;
16890             }
16891         }
16892         return -1;
16893     }
16894 });
16895 /*
16896  * - LGPL
16897  *
16898  * based on jquery fullcalendar
16899  * 
16900  */
16901
16902 Roo.bootstrap = Roo.bootstrap || {};
16903 /**
16904  * @class Roo.bootstrap.Calendar
16905  * @extends Roo.bootstrap.Component
16906  * Bootstrap Calendar class
16907  * @cfg {Boolean} loadMask (true|false) default false
16908  * @cfg {Object} header generate the user specific header of the calendar, default false
16909
16910  * @constructor
16911  * Create a new Container
16912  * @param {Object} config The config object
16913  */
16914
16915
16916
16917 Roo.bootstrap.Calendar = function(config){
16918     Roo.bootstrap.Calendar.superclass.constructor.call(this, config);
16919      this.addEvents({
16920         /**
16921              * @event select
16922              * Fires when a date is selected
16923              * @param {DatePicker} this
16924              * @param {Date} date The selected date
16925              */
16926         'select': true,
16927         /**
16928              * @event monthchange
16929              * Fires when the displayed month changes 
16930              * @param {DatePicker} this
16931              * @param {Date} date The selected month
16932              */
16933         'monthchange': true,
16934         /**
16935              * @event evententer
16936              * Fires when mouse over an event
16937              * @param {Calendar} this
16938              * @param {event} Event
16939              */
16940         'evententer': true,
16941         /**
16942              * @event eventleave
16943              * Fires when the mouse leaves an
16944              * @param {Calendar} this
16945              * @param {event}
16946              */
16947         'eventleave': true,
16948         /**
16949              * @event eventclick
16950              * Fires when the mouse click an
16951              * @param {Calendar} this
16952              * @param {event}
16953              */
16954         'eventclick': true
16955         
16956     });
16957
16958 };
16959
16960 Roo.extend(Roo.bootstrap.Calendar, Roo.bootstrap.Component,  {
16961     
16962      /**
16963      * @cfg {Number} startDay
16964      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
16965      */
16966     startDay : 0,
16967     
16968     loadMask : false,
16969     
16970     header : false,
16971       
16972     getAutoCreate : function(){
16973         
16974         
16975         var fc_button = function(name, corner, style, content ) {
16976             return Roo.apply({},{
16977                 tag : 'span',
16978                 cls : 'fc-button fc-button-'+name+' fc-state-default ' + 
16979                          (corner.length ?
16980                             'fc-corner-' + corner.split(' ').join(' fc-corner-') :
16981                             ''
16982                         ),
16983                 html : '<SPAN class="fc-text-'+style+ '">'+content +'</SPAN>',
16984                 unselectable: 'on'
16985             });
16986         };
16987         
16988         var header = {};
16989         
16990         if(!this.header){
16991             header = {
16992                 tag : 'table',
16993                 cls : 'fc-header',
16994                 style : 'width:100%',
16995                 cn : [
16996                     {
16997                         tag: 'tr',
16998                         cn : [
16999                             {
17000                                 tag : 'td',
17001                                 cls : 'fc-header-left',
17002                                 cn : [
17003                                     fc_button('prev', 'left', 'arrow', '&#8249;' ),
17004                                     fc_button('next', 'right', 'arrow', '&#8250;' ),
17005                                     { tag: 'span', cls: 'fc-header-space' },
17006                                     fc_button('today', 'left right', '', 'today' )  // neds state disabled..
17007
17008
17009                                 ]
17010                             },
17011
17012                             {
17013                                 tag : 'td',
17014                                 cls : 'fc-header-center',
17015                                 cn : [
17016                                     {
17017                                         tag: 'span',
17018                                         cls: 'fc-header-title',
17019                                         cn : {
17020                                             tag: 'H2',
17021                                             html : 'month / year'
17022                                         }
17023                                     }
17024
17025                                 ]
17026                             },
17027                             {
17028                                 tag : 'td',
17029                                 cls : 'fc-header-right',
17030                                 cn : [
17031                               /*      fc_button('month', 'left', '', 'month' ),
17032                                     fc_button('week', '', '', 'week' ),
17033                                     fc_button('day', 'right', '', 'day' )
17034                                 */    
17035
17036                                 ]
17037                             }
17038
17039                         ]
17040                     }
17041                 ]
17042             };
17043         }
17044         
17045         header = this.header;
17046         
17047        
17048         var cal_heads = function() {
17049             var ret = [];
17050             // fixme - handle this.
17051             
17052             for (var i =0; i < Date.dayNames.length; i++) {
17053                 var d = Date.dayNames[i];
17054                 ret.push({
17055                     tag: 'th',
17056                     cls : 'fc-day-header fc-' + d.substring(0,3).toLowerCase() + ' fc-widget-header',
17057                     html : d.substring(0,3)
17058                 });
17059                 
17060             }
17061             ret[0].cls += ' fc-first';
17062             ret[6].cls += ' fc-last';
17063             return ret;
17064         };
17065         var cal_cell = function(n) {
17066             return  {
17067                 tag: 'td',
17068                 cls : 'fc-day fc-'+n + ' fc-widget-content', ///fc-other-month fc-past
17069                 cn : [
17070                     {
17071                         cn : [
17072                             {
17073                                 cls: 'fc-day-number',
17074                                 html: 'D'
17075                             },
17076                             {
17077                                 cls: 'fc-day-content',
17078                              
17079                                 cn : [
17080                                      {
17081                                         style: 'position: relative;' // height: 17px;
17082                                     }
17083                                 ]
17084                             }
17085                             
17086                             
17087                         ]
17088                     }
17089                 ]
17090                 
17091             }
17092         };
17093         var cal_rows = function() {
17094             
17095             var ret = [];
17096             for (var r = 0; r < 6; r++) {
17097                 var row= {
17098                     tag : 'tr',
17099                     cls : 'fc-week',
17100                     cn : []
17101                 };
17102                 
17103                 for (var i =0; i < Date.dayNames.length; i++) {
17104                     var d = Date.dayNames[i];
17105                     row.cn.push(cal_cell(d.substring(0,3).toLowerCase()));
17106
17107                 }
17108                 row.cn[0].cls+=' fc-first';
17109                 row.cn[0].cn[0].style = 'min-height:90px';
17110                 row.cn[6].cls+=' fc-last';
17111                 ret.push(row);
17112                 
17113             }
17114             ret[0].cls += ' fc-first';
17115             ret[4].cls += ' fc-prev-last';
17116             ret[5].cls += ' fc-last';
17117             return ret;
17118             
17119         };
17120         
17121         var cal_table = {
17122             tag: 'table',
17123             cls: 'fc-border-separate',
17124             style : 'width:100%',
17125             cellspacing  : 0,
17126             cn : [
17127                 { 
17128                     tag: 'thead',
17129                     cn : [
17130                         { 
17131                             tag: 'tr',
17132                             cls : 'fc-first fc-last',
17133                             cn : cal_heads()
17134                         }
17135                     ]
17136                 },
17137                 { 
17138                     tag: 'tbody',
17139                     cn : cal_rows()
17140                 }
17141                   
17142             ]
17143         };
17144          
17145          var cfg = {
17146             cls : 'fc fc-ltr',
17147             cn : [
17148                 header,
17149                 {
17150                     cls : 'fc-content',
17151                     style : "position: relative;",
17152                     cn : [
17153                         {
17154                             cls : 'fc-view fc-view-month fc-grid',
17155                             style : 'position: relative',
17156                             unselectable : 'on',
17157                             cn : [
17158                                 {
17159                                     cls : 'fc-event-container',
17160                                     style : 'position:absolute;z-index:8;top:0;left:0;'
17161                                 },
17162                                 cal_table
17163                             ]
17164                         }
17165                     ]
17166     
17167                 }
17168            ] 
17169             
17170         };
17171         
17172          
17173         
17174         return cfg;
17175     },
17176     
17177     
17178     initEvents : function()
17179     {
17180         if(!this.store){
17181             throw "can not find store for calendar";
17182         }
17183         
17184         var mark = {
17185             tag: "div",
17186             cls:"x-dlg-mask",
17187             style: "text-align:center",
17188             cn: [
17189                 {
17190                     tag: "div",
17191                     style: "background-color:white;width:50%;margin:250 auto",
17192                     cn: [
17193                         {
17194                             tag: "img",
17195                             src: Roo.rootURL + '/images/ux/lightbox/loading.gif' 
17196                         },
17197                         {
17198                             tag: "span",
17199                             html: "Loading"
17200                         }
17201                         
17202                     ]
17203                 }
17204             ]
17205         };
17206         this.maskEl = Roo.DomHelper.append(this.el.select('.fc-content', true).first(), mark, true);
17207         
17208         var size = this.el.select('.fc-content', true).first().getSize();
17209         this.maskEl.setSize(size.width, size.height);
17210         this.maskEl.enableDisplayMode("block");
17211         if(!this.loadMask){
17212             this.maskEl.hide();
17213         }
17214         
17215         this.store = Roo.factory(this.store, Roo.data);
17216         this.store.on('load', this.onLoad, this);
17217         this.store.on('beforeload', this.onBeforeLoad, this);
17218         
17219         this.resize();
17220         
17221         this.cells = this.el.select('.fc-day',true);
17222         //Roo.log(this.cells);
17223         this.textNodes = this.el.query('.fc-day-number');
17224         this.cells.addClassOnOver('fc-state-hover');
17225         
17226         this.el.select('.fc-button-prev',true).on('click', this.showPrevMonth, this);
17227         this.el.select('.fc-button-next',true).on('click', this.showNextMonth, this);
17228         this.el.select('.fc-button-today',true).on('click', this.showToday, this);
17229         this.el.select('.fc-button',true).addClassOnOver('fc-state-hover');
17230         
17231         this.on('monthchange', this.onMonthChange, this);
17232         
17233         this.update(new Date().clearTime());
17234     },
17235     
17236     resize : function() {
17237         var sz  = this.el.getSize();
17238         
17239         this.el.select('.fc-day-header',true).setWidth(sz.width / 7);
17240         this.el.select('.fc-day-content div',true).setHeight(34);
17241     },
17242     
17243     
17244     // private
17245     showPrevMonth : function(e){
17246         this.update(this.activeDate.add("mo", -1));
17247     },
17248     showToday : function(e){
17249         this.update(new Date().clearTime());
17250     },
17251     // private
17252     showNextMonth : function(e){
17253         this.update(this.activeDate.add("mo", 1));
17254     },
17255
17256     // private
17257     showPrevYear : function(){
17258         this.update(this.activeDate.add("y", -1));
17259     },
17260
17261     // private
17262     showNextYear : function(){
17263         this.update(this.activeDate.add("y", 1));
17264     },
17265
17266     
17267    // private
17268     update : function(date)
17269     {
17270         var vd = this.activeDate;
17271         this.activeDate = date;
17272 //        if(vd && this.el){
17273 //            var t = date.getTime();
17274 //            if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
17275 //                Roo.log('using add remove');
17276 //                
17277 //                this.fireEvent('monthchange', this, date);
17278 //                
17279 //                this.cells.removeClass("fc-state-highlight");
17280 //                this.cells.each(function(c){
17281 //                   if(c.dateValue == t){
17282 //                       c.addClass("fc-state-highlight");
17283 //                       setTimeout(function(){
17284 //                            try{c.dom.firstChild.focus();}catch(e){}
17285 //                       }, 50);
17286 //                       return false;
17287 //                   }
17288 //                   return true;
17289 //                });
17290 //                return;
17291 //            }
17292 //        }
17293         
17294         var days = date.getDaysInMonth();
17295         
17296         var firstOfMonth = date.getFirstDateOfMonth();
17297         var startingPos = firstOfMonth.getDay()-this.startDay;
17298         
17299         if(startingPos < this.startDay){
17300             startingPos += 7;
17301         }
17302         
17303         var pm = date.add(Date.MONTH, -1);
17304         var prevStart = pm.getDaysInMonth()-startingPos;
17305 //        
17306         this.cells = this.el.select('.fc-day',true);
17307         this.textNodes = this.el.query('.fc-day-number');
17308         this.cells.addClassOnOver('fc-state-hover');
17309         
17310         var cells = this.cells.elements;
17311         var textEls = this.textNodes;
17312         
17313         Roo.each(cells, function(cell){
17314             cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
17315         });
17316         
17317         days += startingPos;
17318
17319         // convert everything to numbers so it's fast
17320         var day = 86400000;
17321         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
17322         //Roo.log(d);
17323         //Roo.log(pm);
17324         //Roo.log(prevStart);
17325         
17326         var today = new Date().clearTime().getTime();
17327         var sel = date.clearTime().getTime();
17328         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
17329         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
17330         var ddMatch = this.disabledDatesRE;
17331         var ddText = this.disabledDatesText;
17332         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
17333         var ddaysText = this.disabledDaysText;
17334         var format = this.format;
17335         
17336         var setCellClass = function(cal, cell){
17337             cell.row = 0;
17338             cell.events = [];
17339             cell.more = [];
17340             //Roo.log('set Cell Class');
17341             cell.title = "";
17342             var t = d.getTime();
17343             
17344             //Roo.log(d);
17345             
17346             cell.dateValue = t;
17347             if(t == today){
17348                 cell.className += " fc-today";
17349                 cell.className += " fc-state-highlight";
17350                 cell.title = cal.todayText;
17351             }
17352             if(t == sel){
17353                 // disable highlight in other month..
17354                 //cell.className += " fc-state-highlight";
17355                 
17356             }
17357             // disabling
17358             if(t < min) {
17359                 cell.className = " fc-state-disabled";
17360                 cell.title = cal.minText;
17361                 return;
17362             }
17363             if(t > max) {
17364                 cell.className = " fc-state-disabled";
17365                 cell.title = cal.maxText;
17366                 return;
17367             }
17368             if(ddays){
17369                 if(ddays.indexOf(d.getDay()) != -1){
17370                     cell.title = ddaysText;
17371                     cell.className = " fc-state-disabled";
17372                 }
17373             }
17374             if(ddMatch && format){
17375                 var fvalue = d.dateFormat(format);
17376                 if(ddMatch.test(fvalue)){
17377                     cell.title = ddText.replace("%0", fvalue);
17378                     cell.className = " fc-state-disabled";
17379                 }
17380             }
17381             
17382             if (!cell.initialClassName) {
17383                 cell.initialClassName = cell.dom.className;
17384             }
17385             
17386             cell.dom.className = cell.initialClassName  + ' ' +  cell.className;
17387         };
17388
17389         var i = 0;
17390         
17391         for(; i < startingPos; i++) {
17392             textEls[i].innerHTML = (++prevStart);
17393             d.setDate(d.getDate()+1);
17394             
17395             cells[i].className = "fc-past fc-other-month";
17396             setCellClass(this, cells[i]);
17397         }
17398         
17399         var intDay = 0;
17400         
17401         for(; i < days; i++){
17402             intDay = i - startingPos + 1;
17403             textEls[i].innerHTML = (intDay);
17404             d.setDate(d.getDate()+1);
17405             
17406             cells[i].className = ''; // "x-date-active";
17407             setCellClass(this, cells[i]);
17408         }
17409         var extraDays = 0;
17410         
17411         for(; i < 42; i++) {
17412             textEls[i].innerHTML = (++extraDays);
17413             d.setDate(d.getDate()+1);
17414             
17415             cells[i].className = "fc-future fc-other-month";
17416             setCellClass(this, cells[i]);
17417         }
17418         
17419         this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
17420         
17421         var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
17422         
17423         this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
17424         this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
17425         
17426         if(totalRows != 6){
17427             this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
17428             this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
17429         }
17430         
17431         this.fireEvent('monthchange', this, date);
17432         
17433         
17434         /*
17435         if(!this.internalRender){
17436             var main = this.el.dom.firstChild;
17437             var w = main.offsetWidth;
17438             this.el.setWidth(w + this.el.getBorderWidth("lr"));
17439             Roo.fly(main).setWidth(w);
17440             this.internalRender = true;
17441             // opera does not respect the auto grow header center column
17442             // then, after it gets a width opera refuses to recalculate
17443             // without a second pass
17444             if(Roo.isOpera && !this.secondPass){
17445                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
17446                 this.secondPass = true;
17447                 this.update.defer(10, this, [date]);
17448             }
17449         }
17450         */
17451         
17452     },
17453     
17454     findCell : function(dt) {
17455         dt = dt.clearTime().getTime();
17456         var ret = false;
17457         this.cells.each(function(c){
17458             //Roo.log("check " +c.dateValue + '?=' + dt);
17459             if(c.dateValue == dt){
17460                 ret = c;
17461                 return false;
17462             }
17463             return true;
17464         });
17465         
17466         return ret;
17467     },
17468     
17469     findCells : function(ev) {
17470         var s = ev.start.clone().clearTime().getTime();
17471        // Roo.log(s);
17472         var e= ev.end.clone().clearTime().getTime();
17473        // Roo.log(e);
17474         var ret = [];
17475         this.cells.each(function(c){
17476              ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
17477             
17478             if(c.dateValue > e){
17479                 return ;
17480             }
17481             if(c.dateValue < s){
17482                 return ;
17483             }
17484             ret.push(c);
17485         });
17486         
17487         return ret;    
17488     },
17489     
17490 //    findBestRow: function(cells)
17491 //    {
17492 //        var ret = 0;
17493 //        
17494 //        for (var i =0 ; i < cells.length;i++) {
17495 //            ret  = Math.max(cells[i].rows || 0,ret);
17496 //        }
17497 //        return ret;
17498 //        
17499 //    },
17500     
17501     
17502     addItem : function(ev)
17503     {
17504         // look for vertical location slot in
17505         var cells = this.findCells(ev);
17506         
17507 //        ev.row = this.findBestRow(cells);
17508         
17509         // work out the location.
17510         
17511         var crow = false;
17512         var rows = [];
17513         for(var i =0; i < cells.length; i++) {
17514             
17515             cells[i].row = cells[0].row;
17516             
17517             if(i == 0){
17518                 cells[i].row = cells[i].row + 1;
17519             }
17520             
17521             if (!crow) {
17522                 crow = {
17523                     start : cells[i],
17524                     end :  cells[i]
17525                 };
17526                 continue;
17527             }
17528             if (crow.start.getY() == cells[i].getY()) {
17529                 // on same row.
17530                 crow.end = cells[i];
17531                 continue;
17532             }
17533             // different row.
17534             rows.push(crow);
17535             crow = {
17536                 start: cells[i],
17537                 end : cells[i]
17538             };
17539             
17540         }
17541         
17542         rows.push(crow);
17543         ev.els = [];
17544         ev.rows = rows;
17545         ev.cells = cells;
17546         
17547         cells[0].events.push(ev);
17548         
17549         this.calevents.push(ev);
17550     },
17551     
17552     clearEvents: function() {
17553         
17554         if(!this.calevents){
17555             return;
17556         }
17557         
17558         Roo.each(this.cells.elements, function(c){
17559             c.row = 0;
17560             c.events = [];
17561             c.more = [];
17562         });
17563         
17564         Roo.each(this.calevents, function(e) {
17565             Roo.each(e.els, function(el) {
17566                 el.un('mouseenter' ,this.onEventEnter, this);
17567                 el.un('mouseleave' ,this.onEventLeave, this);
17568                 el.remove();
17569             },this);
17570         },this);
17571         
17572         Roo.each(Roo.select('.fc-more-event', true).elements, function(e){
17573             e.remove();
17574         });
17575         
17576     },
17577     
17578     renderEvents: function()
17579     {   
17580         var _this = this;
17581         
17582         this.cells.each(function(c) {
17583             
17584             if(c.row < 5){
17585                 return;
17586             }
17587             
17588             var ev = c.events;
17589             
17590             var r = 4;
17591             if(c.row != c.events.length){
17592                 r = 4 - (4 - (c.row - c.events.length));
17593             }
17594             
17595             c.events = ev.slice(0, r);
17596             c.more = ev.slice(r);
17597             
17598             if(c.more.length && c.more.length == 1){
17599                 c.events.push(c.more.pop());
17600             }
17601             
17602             c.row = (c.row - ev.length) + c.events.length + ((c.more.length) ? 1 : 0);
17603             
17604         });
17605             
17606         this.cells.each(function(c) {
17607             
17608             c.select('.fc-day-content div',true).first().setHeight(Math.max(34, c.row * 20));
17609             
17610             
17611             for (var e = 0; e < c.events.length; e++){
17612                 var ev = c.events[e];
17613                 var rows = ev.rows;
17614                 
17615                 for(var i = 0; i < rows.length; i++) {
17616                 
17617                     // how many rows should it span..
17618
17619                     var  cfg = {
17620                         cls : 'roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable',
17621                         style : 'position: absolute', // left: 387px; width: 121px; top: 359px;
17622
17623                         unselectable : "on",
17624                         cn : [
17625                             {
17626                                 cls: 'fc-event-inner',
17627                                 cn : [
17628     //                                {
17629     //                                  tag:'span',
17630     //                                  cls: 'fc-event-time',
17631     //                                  html : cells.length > 1 ? '' : ev.time
17632     //                                },
17633                                     {
17634                                       tag:'span',
17635                                       cls: 'fc-event-title',
17636                                       html : String.format('{0}', ev.title)
17637                                     }
17638
17639
17640                                 ]
17641                             },
17642                             {
17643                                 cls: 'ui-resizable-handle ui-resizable-e',
17644                                 html : '&nbsp;&nbsp;&nbsp'
17645                             }
17646
17647                         ]
17648                     };
17649
17650                     if (i == 0) {
17651                         cfg.cls += ' fc-event-start';
17652                     }
17653                     if ((i+1) == rows.length) {
17654                         cfg.cls += ' fc-event-end';
17655                     }
17656
17657                     var ctr = _this.el.select('.fc-event-container',true).first();
17658                     var cg = ctr.createChild(cfg);
17659
17660                     var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
17661                     var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
17662
17663                     var r = (c.more.length) ? 1 : 0;
17664                     cg.setXY([sbox.x +2, sbox.y + ((c.row - c.events.length - r + e) * 20)]);    
17665                     cg.setWidth(ebox.right - sbox.x -2);
17666
17667                     cg.on('mouseenter' ,_this.onEventEnter, _this, ev);
17668                     cg.on('mouseleave' ,_this.onEventLeave, _this, ev);
17669                     cg.on('click', _this.onEventClick, _this, ev);
17670
17671                     ev.els.push(cg);
17672                     
17673                 }
17674                 
17675             }
17676             
17677             
17678             if(c.more.length){
17679                 var  cfg = {
17680                     cls : 'fc-more-event roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable fc-event-start fc-event-end',
17681                     style : 'position: absolute',
17682                     unselectable : "on",
17683                     cn : [
17684                         {
17685                             cls: 'fc-event-inner',
17686                             cn : [
17687                                 {
17688                                   tag:'span',
17689                                   cls: 'fc-event-title',
17690                                   html : 'More'
17691                                 }
17692
17693
17694                             ]
17695                         },
17696                         {
17697                             cls: 'ui-resizable-handle ui-resizable-e',
17698                             html : '&nbsp;&nbsp;&nbsp'
17699                         }
17700
17701                     ]
17702                 };
17703
17704                 var ctr = _this.el.select('.fc-event-container',true).first();
17705                 var cg = ctr.createChild(cfg);
17706
17707                 var sbox = c.select('.fc-day-content',true).first().getBox();
17708                 var ebox = c.select('.fc-day-content',true).first().getBox();
17709                 //Roo.log(cg);
17710                 cg.setXY([sbox.x +2, sbox.y +((c.row - 1) * 20)]);    
17711                 cg.setWidth(ebox.right - sbox.x -2);
17712
17713                 cg.on('click', _this.onMoreEventClick, _this, c.more);
17714                 
17715             }
17716             
17717         });
17718         
17719         
17720         
17721     },
17722     
17723     onEventEnter: function (e, el,event,d) {
17724         this.fireEvent('evententer', this, el, event);
17725     },
17726     
17727     onEventLeave: function (e, el,event,d) {
17728         this.fireEvent('eventleave', this, el, event);
17729     },
17730     
17731     onEventClick: function (e, el,event,d) {
17732         this.fireEvent('eventclick', this, el, event);
17733     },
17734     
17735     onMonthChange: function () {
17736         this.store.load();
17737     },
17738     
17739     onMoreEventClick: function(e, el, more)
17740     {
17741         var _this = this;
17742         
17743         this.calpopover.placement = 'right';
17744         this.calpopover.setTitle('More');
17745         
17746         this.calpopover.setContent('');
17747         
17748         var ctr = this.calpopover.el.select('.popover-content', true).first();
17749         
17750         Roo.each(more, function(m){
17751             var cfg = {
17752                 cls : 'fc-event-hori fc-event-draggable',
17753                 html : m.title
17754             };
17755             var cg = ctr.createChild(cfg);
17756             
17757             cg.on('click', _this.onEventClick, _this, m);
17758         });
17759         
17760         this.calpopover.show(el);
17761         
17762         
17763     },
17764     
17765     onLoad: function () 
17766     {   
17767         this.calevents = [];
17768         var cal = this;
17769         
17770         if(this.store.getCount() > 0){
17771             this.store.data.each(function(d){
17772                cal.addItem({
17773                     id : d.data.id,
17774                     start: (typeof(d.data.start_dt) === 'string') ? new Date.parseDate(d.data.start_dt, 'Y-m-d H:i:s') : d.data.start_dt,
17775                     end : (typeof(d.data.end_dt) === 'string') ? new Date.parseDate(d.data.end_dt, 'Y-m-d H:i:s') : d.data.end_dt,
17776                     time : d.data.start_time,
17777                     title : d.data.title,
17778                     description : d.data.description,
17779                     venue : d.data.venue
17780                 });
17781             });
17782         }
17783         
17784         this.renderEvents();
17785         
17786         if(this.calevents.length && this.loadMask){
17787             this.maskEl.hide();
17788         }
17789     },
17790     
17791     onBeforeLoad: function()
17792     {
17793         this.clearEvents();
17794         if(this.loadMask){
17795             this.maskEl.show();
17796         }
17797     }
17798 });
17799
17800  
17801  /*
17802  * - LGPL
17803  *
17804  * element
17805  * 
17806  */
17807
17808 /**
17809  * @class Roo.bootstrap.Popover
17810  * @extends Roo.bootstrap.Component
17811  * Bootstrap Popover class
17812  * @cfg {String} html contents of the popover   (or false to use children..)
17813  * @cfg {String} title of popover (or false to hide)
17814  * @cfg {String} placement how it is placed
17815  * @cfg {String} trigger click || hover (or false to trigger manually)
17816  * @cfg {String} over what (parent or false to trigger manually.)
17817  * @cfg {Number} delay - delay before showing
17818  
17819  * @constructor
17820  * Create a new Popover
17821  * @param {Object} config The config object
17822  */
17823
17824 Roo.bootstrap.Popover = function(config){
17825     Roo.bootstrap.Popover.superclass.constructor.call(this, config);
17826     
17827     this.addEvents({
17828         // raw events
17829          /**
17830          * @event show
17831          * After the popover show
17832          * 
17833          * @param {Roo.bootstrap.Popover} this
17834          */
17835         "show" : true,
17836         /**
17837          * @event hide
17838          * After the popover hide
17839          * 
17840          * @param {Roo.bootstrap.Popover} this
17841          */
17842         "hide" : true
17843     });
17844 };
17845
17846 Roo.extend(Roo.bootstrap.Popover, Roo.bootstrap.Component,  {
17847     
17848     title: 'Fill in a title',
17849     html: false,
17850     
17851     placement : 'right',
17852     trigger : 'hover', // hover
17853     
17854     delay : 0,
17855     
17856     over: 'parent',
17857     
17858     can_build_overlaid : false,
17859     
17860     getChildContainer : function()
17861     {
17862         return this.el.select('.popover-content',true).first();
17863     },
17864     
17865     getAutoCreate : function(){
17866          
17867         var cfg = {
17868            cls : 'popover roo-dynamic',
17869            style: 'display:block',
17870            cn : [
17871                 {
17872                     cls : 'arrow'
17873                 },
17874                 {
17875                     cls : 'popover-inner',
17876                     cn : [
17877                         {
17878                             tag: 'h3',
17879                             cls: 'popover-title popover-header',
17880                             html : this.title
17881                         },
17882                         {
17883                             cls : 'popover-content popover-body',
17884                             html : this.html
17885                         }
17886                     ]
17887                     
17888                 }
17889            ]
17890         };
17891         
17892         return cfg;
17893     },
17894     setTitle: function(str)
17895     {
17896         this.title = str;
17897         this.el.select('.popover-title',true).first().dom.innerHTML = str;
17898     },
17899     setContent: function(str)
17900     {
17901         this.html = str;
17902         this.el.select('.popover-content',true).first().dom.innerHTML = str;
17903     },
17904     // as it get's added to the bottom of the page.
17905     onRender : function(ct, position)
17906     {
17907         Roo.bootstrap.Component.superclass.onRender.call(this, ct, position);
17908         if(!this.el){
17909             var cfg = Roo.apply({},  this.getAutoCreate());
17910             cfg.id = Roo.id();
17911             
17912             if (this.cls) {
17913                 cfg.cls += ' ' + this.cls;
17914             }
17915             if (this.style) {
17916                 cfg.style = this.style;
17917             }
17918             //Roo.log("adding to ");
17919             this.el = Roo.get(document.body).createChild(cfg, position);
17920 //            Roo.log(this.el);
17921         }
17922         this.initEvents();
17923     },
17924     
17925     initEvents : function()
17926     {
17927         this.el.select('.popover-title',true).setVisibilityMode(Roo.Element.DISPLAY);
17928         this.el.enableDisplayMode('block');
17929         this.el.hide();
17930         if (this.over === false) {
17931             return; 
17932         }
17933         if (this.triggers === false) {
17934             return;
17935         }
17936         var on_el = (this.over == 'parent') ? this.parent().el : Roo.get(this.over);
17937         var triggers = this.trigger ? this.trigger.split(' ') : [];
17938         Roo.each(triggers, function(trigger) {
17939         
17940             if (trigger == 'click') {
17941                 on_el.on('click', this.toggle, this);
17942             } else if (trigger != 'manual') {
17943                 var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focusin';
17944                 var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout';
17945       
17946                 on_el.on(eventIn  ,this.enter, this);
17947                 on_el.on(eventOut, this.leave, this);
17948             }
17949         }, this);
17950         
17951     },
17952     
17953     
17954     // private
17955     timeout : null,
17956     hoverState : null,
17957     
17958     toggle : function () {
17959         this.hoverState == 'in' ? this.leave() : this.enter();
17960     },
17961     
17962     enter : function () {
17963         
17964         clearTimeout(this.timeout);
17965     
17966         this.hoverState = 'in';
17967     
17968         if (!this.delay || !this.delay.show) {
17969             this.show();
17970             return;
17971         }
17972         var _t = this;
17973         this.timeout = setTimeout(function () {
17974             if (_t.hoverState == 'in') {
17975                 _t.show();
17976             }
17977         }, this.delay.show)
17978     },
17979     
17980     leave : function() {
17981         clearTimeout(this.timeout);
17982     
17983         this.hoverState = 'out';
17984     
17985         if (!this.delay || !this.delay.hide) {
17986             this.hide();
17987             return;
17988         }
17989         var _t = this;
17990         this.timeout = setTimeout(function () {
17991             if (_t.hoverState == 'out') {
17992                 _t.hide();
17993             }
17994         }, this.delay.hide)
17995     },
17996     
17997     show : function (on_el)
17998     {
17999         if (!on_el) {
18000             on_el= (this.over == 'parent') ? this.parent().el : Roo.get(this.over);
18001         }
18002         
18003         // set content.
18004         this.el.select('.popover-title',true).first().dom.innerHtml = this.title;
18005         if (this.html !== false) {
18006             this.el.select('.popover-content',true).first().dom.innerHtml = this.html;
18007         }
18008         this.el.removeClass([
18009             'fade','top','bottom', 'left', 'right','in',
18010             'bs-popover-top','bs-popover-bottom', 'bs-popover-left', 'bs-popover-right'
18011         ]);
18012         if (!this.title.length) {
18013             this.el.select('.popover-title',true).hide();
18014         }
18015         
18016         var placement = typeof this.placement == 'function' ?
18017             this.placement.call(this, this.el, on_el) :
18018             this.placement;
18019             
18020         var autoToken = /\s?auto?\s?/i;
18021         var autoPlace = autoToken.test(placement);
18022         if (autoPlace) {
18023             placement = placement.replace(autoToken, '') || 'top';
18024         }
18025         
18026         //this.el.detach()
18027         //this.el.setXY([0,0]);
18028         this.el.show();
18029         this.el.dom.style.display='block';
18030         this.el.addClass(placement);
18031         
18032         //this.el.appendTo(on_el);
18033         
18034         var p = this.getPosition();
18035         var box = this.el.getBox();
18036         
18037         if (autoPlace) {
18038             // fixme..
18039         }
18040         var align = Roo.bootstrap.Popover.alignment[placement];
18041         
18042 //        Roo.log(align);
18043         this.el.alignTo(on_el, align[0],align[1]);
18044         //var arrow = this.el.select('.arrow',true).first();
18045         //arrow.set(align[2], 
18046         
18047         this.el.addClass('in');
18048         
18049         
18050         if (this.el.hasClass('fade')) {
18051             // fade it?
18052         }
18053         
18054         this.hoverState = 'in';
18055         
18056         this.fireEvent('show', this);
18057         
18058     },
18059     hide : function()
18060     {
18061         this.el.setXY([0,0]);
18062         this.el.removeClass('in');
18063         this.el.hide();
18064         this.hoverState = null;
18065         
18066         this.fireEvent('hide', this);
18067     }
18068     
18069 });
18070
18071 Roo.bootstrap.Popover.alignment = {
18072     'left' : ['r-l', [-10,0], 'right bs-popover-right'],
18073     'right' : ['l-r', [10,0], 'left bs-popover-left'],
18074     'bottom' : ['t-b', [0,10], 'top bs-popover-top'],
18075     'top' : [ 'b-t', [0,-10], 'bottom bs-popover-bottom']
18076 };
18077
18078  /*
18079  * - LGPL
18080  *
18081  * Progress
18082  * 
18083  */
18084
18085 /**
18086  * @class Roo.bootstrap.Progress
18087  * @extends Roo.bootstrap.Component
18088  * Bootstrap Progress class
18089  * @cfg {Boolean} striped striped of the progress bar
18090  * @cfg {Boolean} active animated of the progress bar
18091  * 
18092  * 
18093  * @constructor
18094  * Create a new Progress
18095  * @param {Object} config The config object
18096  */
18097
18098 Roo.bootstrap.Progress = function(config){
18099     Roo.bootstrap.Progress.superclass.constructor.call(this, config);
18100 };
18101
18102 Roo.extend(Roo.bootstrap.Progress, Roo.bootstrap.Component,  {
18103     
18104     striped : false,
18105     active: false,
18106     
18107     getAutoCreate : function(){
18108         var cfg = {
18109             tag: 'div',
18110             cls: 'progress'
18111         };
18112         
18113         
18114         if(this.striped){
18115             cfg.cls += ' progress-striped';
18116         }
18117       
18118         if(this.active){
18119             cfg.cls += ' active';
18120         }
18121         
18122         
18123         return cfg;
18124     }
18125    
18126 });
18127
18128  
18129
18130  /*
18131  * - LGPL
18132  *
18133  * ProgressBar
18134  * 
18135  */
18136
18137 /**
18138  * @class Roo.bootstrap.ProgressBar
18139  * @extends Roo.bootstrap.Component
18140  * Bootstrap ProgressBar class
18141  * @cfg {Number} aria_valuenow aria-value now
18142  * @cfg {Number} aria_valuemin aria-value min
18143  * @cfg {Number} aria_valuemax aria-value max
18144  * @cfg {String} label label for the progress bar
18145  * @cfg {String} panel (success | info | warning | danger )
18146  * @cfg {String} role role of the progress bar
18147  * @cfg {String} sr_only text
18148  * 
18149  * 
18150  * @constructor
18151  * Create a new ProgressBar
18152  * @param {Object} config The config object
18153  */
18154
18155 Roo.bootstrap.ProgressBar = function(config){
18156     Roo.bootstrap.ProgressBar.superclass.constructor.call(this, config);
18157 };
18158
18159 Roo.extend(Roo.bootstrap.ProgressBar, Roo.bootstrap.Component,  {
18160     
18161     aria_valuenow : 0,
18162     aria_valuemin : 0,
18163     aria_valuemax : 100,
18164     label : false,
18165     panel : false,
18166     role : false,
18167     sr_only: false,
18168     
18169     getAutoCreate : function()
18170     {
18171         
18172         var cfg = {
18173             tag: 'div',
18174             cls: 'progress-bar',
18175             style: 'width:' + Math.ceil((this.aria_valuenow / this.aria_valuemax) * 100) + '%'
18176         };
18177         
18178         if(this.sr_only){
18179             cfg.cn = {
18180                 tag: 'span',
18181                 cls: 'sr-only',
18182                 html: this.sr_only
18183             }
18184         }
18185         
18186         if(this.role){
18187             cfg.role = this.role;
18188         }
18189         
18190         if(this.aria_valuenow){
18191             cfg['aria-valuenow'] = this.aria_valuenow;
18192         }
18193         
18194         if(this.aria_valuemin){
18195             cfg['aria-valuemin'] = this.aria_valuemin;
18196         }
18197         
18198         if(this.aria_valuemax){
18199             cfg['aria-valuemax'] = this.aria_valuemax;
18200         }
18201         
18202         if(this.label && !this.sr_only){
18203             cfg.html = this.label;
18204         }
18205         
18206         if(this.panel){
18207             cfg.cls += ' progress-bar-' + this.panel;
18208         }
18209         
18210         return cfg;
18211     },
18212     
18213     update : function(aria_valuenow)
18214     {
18215         this.aria_valuenow = aria_valuenow;
18216         
18217         this.el.setStyle('width', Math.ceil((this.aria_valuenow / this.aria_valuemax) * 100) + '%');
18218     }
18219    
18220 });
18221
18222  
18223
18224  /*
18225  * - LGPL
18226  *
18227  * column
18228  * 
18229  */
18230
18231 /**
18232  * @class Roo.bootstrap.TabGroup
18233  * @extends Roo.bootstrap.Column
18234  * Bootstrap Column class
18235  * @cfg {String} navId the navigation id (for use with navbars) - will be auto generated if it does not exist..
18236  * @cfg {Boolean} carousel true to make the group behave like a carousel
18237  * @cfg {Boolean} bullets show bullets for the panels
18238  * @cfg {Boolean} autoslide (true|false) auto slide .. default false
18239  * @cfg {Number} timer auto slide timer .. default 0 millisecond
18240  * @cfg {Boolean} showarrow (true|false) show arrow default true
18241  * 
18242  * @constructor
18243  * Create a new TabGroup
18244  * @param {Object} config The config object
18245  */
18246
18247 Roo.bootstrap.TabGroup = function(config){
18248     Roo.bootstrap.TabGroup.superclass.constructor.call(this, config);
18249     if (!this.navId) {
18250         this.navId = Roo.id();
18251     }
18252     this.tabs = [];
18253     Roo.bootstrap.TabGroup.register(this);
18254     
18255 };
18256
18257 Roo.extend(Roo.bootstrap.TabGroup, Roo.bootstrap.Column,  {
18258     
18259     carousel : false,
18260     transition : false,
18261     bullets : 0,
18262     timer : 0,
18263     autoslide : false,
18264     slideFn : false,
18265     slideOnTouch : false,
18266     showarrow : true,
18267     
18268     getAutoCreate : function()
18269     {
18270         var cfg = Roo.apply({}, Roo.bootstrap.TabGroup.superclass.getAutoCreate.call(this));
18271         
18272         cfg.cls += ' tab-content';
18273         
18274         if (this.carousel) {
18275             cfg.cls += ' carousel slide';
18276             
18277             cfg.cn = [{
18278                cls : 'carousel-inner',
18279                cn : []
18280             }];
18281         
18282             if(this.bullets  && !Roo.isTouch){
18283                 
18284                 var bullets = {
18285                     cls : 'carousel-bullets',
18286                     cn : []
18287                 };
18288                
18289                 if(this.bullets_cls){
18290                     bullets.cls = bullets.cls + ' ' + this.bullets_cls;
18291                 }
18292                 
18293                 bullets.cn.push({
18294                     cls : 'clear'
18295                 });
18296                 
18297                 cfg.cn[0].cn.push(bullets);
18298             }
18299             
18300             if(this.showarrow){
18301                 cfg.cn[0].cn.push({
18302                     tag : 'div',
18303                     class : 'carousel-arrow',
18304                     cn : [
18305                         {
18306                             tag : 'div',
18307                             class : 'carousel-prev',
18308                             cn : [
18309                                 {
18310                                     tag : 'i',
18311                                     class : 'fa fa-chevron-left'
18312                                 }
18313                             ]
18314                         },
18315                         {
18316                             tag : 'div',
18317                             class : 'carousel-next',
18318                             cn : [
18319                                 {
18320                                     tag : 'i',
18321                                     class : 'fa fa-chevron-right'
18322                                 }
18323                             ]
18324                         }
18325                     ]
18326                 });
18327             }
18328             
18329         }
18330         
18331         return cfg;
18332     },
18333     
18334     initEvents:  function()
18335     {
18336 //        if(Roo.isTouch && this.slideOnTouch && !this.showarrow){
18337 //            this.el.on("touchstart", this.onTouchStart, this);
18338 //        }
18339         
18340         if(this.autoslide){
18341             var _this = this;
18342             
18343             this.slideFn = window.setInterval(function() {
18344                 _this.showPanelNext();
18345             }, this.timer);
18346         }
18347         
18348         if(this.showarrow){
18349             this.el.select('.carousel-prev', true).first().on('click', this.showPanelPrev, this);
18350             this.el.select('.carousel-next', true).first().on('click', this.showPanelNext, this);
18351         }
18352         
18353         
18354     },
18355     
18356 //    onTouchStart : function(e, el, o)
18357 //    {
18358 //        if(!this.slideOnTouch || !Roo.isTouch || Roo.get(e.getTarget()).hasClass('roo-button-text')){
18359 //            return;
18360 //        }
18361 //        
18362 //        this.showPanelNext();
18363 //    },
18364     
18365     
18366     getChildContainer : function()
18367     {
18368         return this.carousel ? this.el.select('.carousel-inner', true).first() : this.el;
18369     },
18370     
18371     /**
18372     * register a Navigation item
18373     * @param {Roo.bootstrap.NavItem} the navitem to add
18374     */
18375     register : function(item)
18376     {
18377         this.tabs.push( item);
18378         item.navId = this.navId; // not really needed..
18379         this.addBullet();
18380     
18381     },
18382     
18383     getActivePanel : function()
18384     {
18385         var r = false;
18386         Roo.each(this.tabs, function(t) {
18387             if (t.active) {
18388                 r = t;
18389                 return false;
18390             }
18391             return null;
18392         });
18393         return r;
18394         
18395     },
18396     getPanelByName : function(n)
18397     {
18398         var r = false;
18399         Roo.each(this.tabs, function(t) {
18400             if (t.tabId == n) {
18401                 r = t;
18402                 return false;
18403             }
18404             return null;
18405         });
18406         return r;
18407     },
18408     indexOfPanel : function(p)
18409     {
18410         var r = false;
18411         Roo.each(this.tabs, function(t,i) {
18412             if (t.tabId == p.tabId) {
18413                 r = i;
18414                 return false;
18415             }
18416             return null;
18417         });
18418         return r;
18419     },
18420     /**
18421      * show a specific panel
18422      * @param {Roo.bootstrap.TabPanel|number|string} panel to change to (use the tabId to specify a specific one)
18423      * @return {boolean} false if panel was not shown (invalid entry or beforedeactivate fails.)
18424      */
18425     showPanel : function (pan)
18426     {
18427         if(this.transition || typeof(pan) == 'undefined'){
18428             Roo.log("waiting for the transitionend");
18429             return false;
18430         }
18431         
18432         if (typeof(pan) == 'number') {
18433             pan = this.tabs[pan];
18434         }
18435         
18436         if (typeof(pan) == 'string') {
18437             pan = this.getPanelByName(pan);
18438         }
18439         
18440         var cur = this.getActivePanel();
18441         
18442         if(!pan || !cur){
18443             Roo.log('pan or acitve pan is undefined');
18444             return false;
18445         }
18446         
18447         if (pan.tabId == this.getActivePanel().tabId) {
18448             return true;
18449         }
18450         
18451         if (false === cur.fireEvent('beforedeactivate')) {
18452             return false;
18453         }
18454         
18455         if(this.bullets > 0 && !Roo.isTouch){
18456             this.setActiveBullet(this.indexOfPanel(pan));
18457         }
18458         
18459         if (this.carousel && typeof(Roo.get(document.body).dom.style.transition) != 'undefined') {
18460             
18461             //class="carousel-item carousel-item-next carousel-item-left"
18462             
18463             this.transition = true;
18464             var dir = this.indexOfPanel(pan) > this.indexOfPanel(cur)  ? 'next' : 'prev';
18465             var lr = dir == 'next' ? 'left' : 'right';
18466             pan.el.addClass(dir); // or prev
18467             pan.el.addClass('carousel-item-' + dir); // or prev
18468             pan.el.dom.offsetWidth; // find the offset with - causing a reflow?
18469             cur.el.addClass(lr); // or right
18470             pan.el.addClass(lr);
18471             cur.el.addClass('carousel-item-' +lr); // or right
18472             pan.el.addClass('carousel-item-' +lr);
18473             
18474             
18475             var _this = this;
18476             cur.el.on('transitionend', function() {
18477                 Roo.log("trans end?");
18478                 
18479                 pan.el.removeClass([lr,dir, 'carousel-item-' + lr, 'carousel-item-' + dir]);
18480                 pan.setActive(true);
18481                 
18482                 cur.el.removeClass([lr, 'carousel-item-' + lr]);
18483                 cur.setActive(false);
18484                 
18485                 _this.transition = false;
18486                 
18487             }, this, { single:  true } );
18488             
18489             return true;
18490         }
18491         
18492         cur.setActive(false);
18493         pan.setActive(true);
18494         
18495         return true;
18496         
18497     },
18498     showPanelNext : function()
18499     {
18500         var i = this.indexOfPanel(this.getActivePanel());
18501         
18502         if (i >= this.tabs.length - 1 && !this.autoslide) {
18503             return;
18504         }
18505         
18506         if (i >= this.tabs.length - 1 && this.autoslide) {
18507             i = -1;
18508         }
18509         
18510         this.showPanel(this.tabs[i+1]);
18511     },
18512     
18513     showPanelPrev : function()
18514     {
18515         var i = this.indexOfPanel(this.getActivePanel());
18516         
18517         if (i  < 1 && !this.autoslide) {
18518             return;
18519         }
18520         
18521         if (i < 1 && this.autoslide) {
18522             i = this.tabs.length;
18523         }
18524         
18525         this.showPanel(this.tabs[i-1]);
18526     },
18527     
18528     
18529     addBullet: function()
18530     {
18531         if(!this.bullets || Roo.isTouch){
18532             return;
18533         }
18534         var ctr = this.el.select('.carousel-bullets',true).first();
18535         var i = this.el.select('.carousel-bullets .bullet',true).getCount() ;
18536         var bullet = ctr.createChild({
18537             cls : 'bullet bullet-' + i
18538         },ctr.dom.lastChild);
18539         
18540         
18541         var _this = this;
18542         
18543         bullet.on('click', (function(e, el, o, ii, t){
18544
18545             e.preventDefault();
18546
18547             this.showPanel(ii);
18548
18549             if(this.autoslide && this.slideFn){
18550                 clearInterval(this.slideFn);
18551                 this.slideFn = window.setInterval(function() {
18552                     _this.showPanelNext();
18553                 }, this.timer);
18554             }
18555
18556         }).createDelegate(this, [i, bullet], true));
18557                 
18558         
18559     },
18560      
18561     setActiveBullet : function(i)
18562     {
18563         if(Roo.isTouch){
18564             return;
18565         }
18566         
18567         Roo.each(this.el.select('.bullet', true).elements, function(el){
18568             el.removeClass('selected');
18569         });
18570
18571         var bullet = this.el.select('.bullet-' + i, true).first();
18572         
18573         if(!bullet){
18574             return;
18575         }
18576         
18577         bullet.addClass('selected');
18578     }
18579     
18580     
18581   
18582 });
18583
18584  
18585
18586  
18587  
18588 Roo.apply(Roo.bootstrap.TabGroup, {
18589     
18590     groups: {},
18591      /**
18592     * register a Navigation Group
18593     * @param {Roo.bootstrap.NavGroup} the navgroup to add
18594     */
18595     register : function(navgrp)
18596     {
18597         this.groups[navgrp.navId] = navgrp;
18598         
18599     },
18600     /**
18601     * fetch a Navigation Group based on the navigation ID
18602     * if one does not exist , it will get created.
18603     * @param {string} the navgroup to add
18604     * @returns {Roo.bootstrap.NavGroup} the navgroup 
18605     */
18606     get: function(navId) {
18607         if (typeof(this.groups[navId]) == 'undefined') {
18608             this.register(new Roo.bootstrap.TabGroup({ navId : navId }));
18609         }
18610         return this.groups[navId] ;
18611     }
18612     
18613     
18614     
18615 });
18616
18617  /*
18618  * - LGPL
18619  *
18620  * TabPanel
18621  * 
18622  */
18623
18624 /**
18625  * @class Roo.bootstrap.TabPanel
18626  * @extends Roo.bootstrap.Component
18627  * Bootstrap TabPanel class
18628  * @cfg {Boolean} active panel active
18629  * @cfg {String} html panel content
18630  * @cfg {String} tabId  unique tab ID (will be autogenerated if not set. - used to match TabItem to Panel)
18631  * @cfg {String} navId The Roo.bootstrap.NavGroup which triggers show hide ()
18632  * @cfg {String} href click to link..
18633  * 
18634  * 
18635  * @constructor
18636  * Create a new TabPanel
18637  * @param {Object} config The config object
18638  */
18639
18640 Roo.bootstrap.TabPanel = function(config){
18641     Roo.bootstrap.TabPanel.superclass.constructor.call(this, config);
18642     this.addEvents({
18643         /**
18644              * @event changed
18645              * Fires when the active status changes
18646              * @param {Roo.bootstrap.TabPanel} this
18647              * @param {Boolean} state the new state
18648             
18649          */
18650         'changed': true,
18651         /**
18652              * @event beforedeactivate
18653              * Fires before a tab is de-activated - can be used to do validation on a form.
18654              * @param {Roo.bootstrap.TabPanel} this
18655              * @return {Boolean} false if there is an error
18656             
18657          */
18658         'beforedeactivate': true
18659      });
18660     
18661     this.tabId = this.tabId || Roo.id();
18662   
18663 };
18664
18665 Roo.extend(Roo.bootstrap.TabPanel, Roo.bootstrap.Component,  {
18666     
18667     active: false,
18668     html: false,
18669     tabId: false,
18670     navId : false,
18671     href : '',
18672     
18673     getAutoCreate : function(){
18674         
18675         
18676         var cfg = {
18677             tag: 'div',
18678             // item is needed for carousel - not sure if it has any effect otherwise
18679             cls: 'carousel-item tab-pane item' + ((this.href.length) ? ' clickable ' : ''),
18680             html: this.html || ''
18681         };
18682         
18683         if(this.active){
18684             cfg.cls += ' active';
18685         }
18686         
18687         if(this.tabId){
18688             cfg.tabId = this.tabId;
18689         }
18690         
18691         
18692         
18693         return cfg;
18694     },
18695     
18696     initEvents:  function()
18697     {
18698         var p = this.parent();
18699         
18700         this.navId = this.navId || p.navId;
18701         
18702         if (typeof(this.navId) != 'undefined') {
18703             // not really needed.. but just in case.. parent should be a NavGroup.
18704             var tg = Roo.bootstrap.TabGroup.get(this.navId);
18705             
18706             tg.register(this);
18707             
18708             var i = tg.tabs.length - 1;
18709             
18710             if(this.active && tg.bullets > 0 && i < tg.bullets){
18711                 tg.setActiveBullet(i);
18712             }
18713         }
18714         
18715         this.el.on('click', this.onClick, this);
18716         
18717         if(Roo.isTouch){
18718             this.el.on("touchstart", this.onTouchStart, this);
18719             this.el.on("touchmove", this.onTouchMove, this);
18720             this.el.on("touchend", this.onTouchEnd, this);
18721         }
18722         
18723     },
18724     
18725     onRender : function(ct, position)
18726     {
18727         Roo.bootstrap.TabPanel.superclass.onRender.call(this, ct, position);
18728     },
18729     
18730     setActive : function(state)
18731     {
18732         Roo.log("panel - set active " + this.tabId + "=" + state);
18733         
18734         this.active = state;
18735         if (!state) {
18736             this.el.removeClass('active');
18737             
18738         } else  if (!this.el.hasClass('active')) {
18739             this.el.addClass('active');
18740         }
18741         
18742         this.fireEvent('changed', this, state);
18743     },
18744     
18745     onClick : function(e)
18746     {
18747         e.preventDefault();
18748         
18749         if(!this.href.length){
18750             return;
18751         }
18752         
18753         window.location.href = this.href;
18754     },
18755     
18756     startX : 0,
18757     startY : 0,
18758     endX : 0,
18759     endY : 0,
18760     swiping : false,
18761     
18762     onTouchStart : function(e)
18763     {
18764         this.swiping = false;
18765         
18766         this.startX = e.browserEvent.touches[0].clientX;
18767         this.startY = e.browserEvent.touches[0].clientY;
18768     },
18769     
18770     onTouchMove : function(e)
18771     {
18772         this.swiping = true;
18773         
18774         this.endX = e.browserEvent.touches[0].clientX;
18775         this.endY = e.browserEvent.touches[0].clientY;
18776     },
18777     
18778     onTouchEnd : function(e)
18779     {
18780         if(!this.swiping){
18781             this.onClick(e);
18782             return;
18783         }
18784         
18785         var tabGroup = this.parent();
18786         
18787         if(this.endX > this.startX){ // swiping right
18788             tabGroup.showPanelPrev();
18789             return;
18790         }
18791         
18792         if(this.startX > this.endX){ // swiping left
18793             tabGroup.showPanelNext();
18794             return;
18795         }
18796     }
18797     
18798     
18799 });
18800  
18801
18802  
18803
18804  /*
18805  * - LGPL
18806  *
18807  * DateField
18808  * 
18809  */
18810
18811 /**
18812  * @class Roo.bootstrap.DateField
18813  * @extends Roo.bootstrap.Input
18814  * Bootstrap DateField class
18815  * @cfg {Number} weekStart default 0
18816  * @cfg {String} viewMode default empty, (months|years)
18817  * @cfg {String} minViewMode default empty, (months|years)
18818  * @cfg {Number} startDate default -Infinity
18819  * @cfg {Number} endDate default Infinity
18820  * @cfg {Boolean} todayHighlight default false
18821  * @cfg {Boolean} todayBtn default false
18822  * @cfg {Boolean} calendarWeeks default false
18823  * @cfg {Object} daysOfWeekDisabled default empty
18824  * @cfg {Boolean} singleMode default false (true | false)
18825  * 
18826  * @cfg {Boolean} keyboardNavigation default true
18827  * @cfg {String} language default en
18828  * 
18829  * @constructor
18830  * Create a new DateField
18831  * @param {Object} config The config object
18832  */
18833
18834 Roo.bootstrap.DateField = function(config){
18835     Roo.bootstrap.DateField.superclass.constructor.call(this, config);
18836      this.addEvents({
18837             /**
18838              * @event show
18839              * Fires when this field show.
18840              * @param {Roo.bootstrap.DateField} this
18841              * @param {Mixed} date The date value
18842              */
18843             show : true,
18844             /**
18845              * @event show
18846              * Fires when this field hide.
18847              * @param {Roo.bootstrap.DateField} this
18848              * @param {Mixed} date The date value
18849              */
18850             hide : true,
18851             /**
18852              * @event select
18853              * Fires when select a date.
18854              * @param {Roo.bootstrap.DateField} this
18855              * @param {Mixed} date The date value
18856              */
18857             select : true,
18858             /**
18859              * @event beforeselect
18860              * Fires when before select a date.
18861              * @param {Roo.bootstrap.DateField} this
18862              * @param {Mixed} date The date value
18863              */
18864             beforeselect : true
18865         });
18866 };
18867
18868 Roo.extend(Roo.bootstrap.DateField, Roo.bootstrap.Input,  {
18869     
18870     /**
18871      * @cfg {String} format
18872      * The default date format string which can be overriden for localization support.  The format must be
18873      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
18874      */
18875     format : "m/d/y",
18876     /**
18877      * @cfg {String} altFormats
18878      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
18879      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
18880      */
18881     altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
18882     
18883     weekStart : 0,
18884     
18885     viewMode : '',
18886     
18887     minViewMode : '',
18888     
18889     todayHighlight : false,
18890     
18891     todayBtn: false,
18892     
18893     language: 'en',
18894     
18895     keyboardNavigation: true,
18896     
18897     calendarWeeks: false,
18898     
18899     startDate: -Infinity,
18900     
18901     endDate: Infinity,
18902     
18903     daysOfWeekDisabled: [],
18904     
18905     _events: [],
18906     
18907     singleMode : false,
18908     
18909     UTCDate: function()
18910     {
18911         return new Date(Date.UTC.apply(Date, arguments));
18912     },
18913     
18914     UTCToday: function()
18915     {
18916         var today = new Date();
18917         return this.UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
18918     },
18919     
18920     getDate: function() {
18921             var d = this.getUTCDate();
18922             return new Date(d.getTime() + (d.getTimezoneOffset()*60000));
18923     },
18924     
18925     getUTCDate: function() {
18926             return this.date;
18927     },
18928     
18929     setDate: function(d) {
18930             this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000)));
18931     },
18932     
18933     setUTCDate: function(d) {
18934             this.date = d;
18935             this.setValue(this.formatDate(this.date));
18936     },
18937         
18938     onRender: function(ct, position)
18939     {
18940         
18941         Roo.bootstrap.DateField.superclass.onRender.call(this, ct, position);
18942         
18943         this.language = this.language || 'en';
18944         this.language = this.language in Roo.bootstrap.DateField.dates ? this.language : this.language.split('-')[0];
18945         this.language = this.language in Roo.bootstrap.DateField.dates ? this.language : "en";
18946         
18947         this.isRTL = Roo.bootstrap.DateField.dates[this.language].rtl || false;
18948         this.format = this.format || 'm/d/y';
18949         this.isInline = false;
18950         this.isInput = true;
18951         this.component = this.el.select('.add-on', true).first() || false;
18952         this.component = (this.component && this.component.length === 0) ? false : this.component;
18953         this.hasInput = this.component && this.inputEl().length;
18954         
18955         if (typeof(this.minViewMode === 'string')) {
18956             switch (this.minViewMode) {
18957                 case 'months':
18958                     this.minViewMode = 1;
18959                     break;
18960                 case 'years':
18961                     this.minViewMode = 2;
18962                     break;
18963                 default:
18964                     this.minViewMode = 0;
18965                     break;
18966             }
18967         }
18968         
18969         if (typeof(this.viewMode === 'string')) {
18970             switch (this.viewMode) {
18971                 case 'months':
18972                     this.viewMode = 1;
18973                     break;
18974                 case 'years':
18975                     this.viewMode = 2;
18976                     break;
18977                 default:
18978                     this.viewMode = 0;
18979                     break;
18980             }
18981         }
18982                 
18983         this.pickerEl = Roo.get(document.body).createChild(Roo.bootstrap.DateField.template);
18984         
18985 //        this.el.select('>.input-group', true).first().createChild(Roo.bootstrap.DateField.template);
18986         
18987         this.picker().setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
18988         
18989         this.picker().on('mousedown', this.onMousedown, this);
18990         this.picker().on('click', this.onClick, this);
18991         
18992         this.picker().addClass('datepicker-dropdown');
18993         
18994         this.startViewMode = this.viewMode;
18995         
18996         if(this.singleMode){
18997             Roo.each(this.picker().select('thead > tr > th', true).elements, function(v){
18998                 v.setVisibilityMode(Roo.Element.DISPLAY);
18999                 v.hide();
19000             });
19001             
19002             Roo.each(this.picker().select('tbody > tr > td', true).elements, function(v){
19003                 v.setStyle('width', '189px');
19004             });
19005         }
19006         
19007         Roo.each(this.picker().select('tfoot th.today', true).elements, function(v){
19008             if(!this.calendarWeeks){
19009                 v.remove();
19010                 return;
19011             }
19012             
19013             v.dom.innerHTML = Roo.bootstrap.DateField.dates[this.language].today;
19014             v.attr('colspan', function(i, val){
19015                 return parseInt(val) + 1;
19016             });
19017         });
19018                         
19019         
19020         this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
19021         
19022         this.setStartDate(this.startDate);
19023         this.setEndDate(this.endDate);
19024         
19025         this.setDaysOfWeekDisabled(this.daysOfWeekDisabled);
19026         
19027         this.fillDow();
19028         this.fillMonths();
19029         this.update();
19030         this.showMode();
19031         
19032         if(this.isInline) {
19033             this.showPopup();
19034         }
19035     },
19036     
19037     picker : function()
19038     {
19039         return this.pickerEl;
19040 //        return this.el.select('.datepicker', true).first();
19041     },
19042     
19043     fillDow: function()
19044     {
19045         var dowCnt = this.weekStart;
19046         
19047         var dow = {
19048             tag: 'tr',
19049             cn: [
19050                 
19051             ]
19052         };
19053         
19054         if(this.calendarWeeks){
19055             dow.cn.push({
19056                 tag: 'th',
19057                 cls: 'cw',
19058                 html: '&nbsp;'
19059             })
19060         }
19061         
19062         while (dowCnt < this.weekStart + 7) {
19063             dow.cn.push({
19064                 tag: 'th',
19065                 cls: 'dow',
19066                 html: Roo.bootstrap.DateField.dates[this.language].daysMin[(dowCnt++)%7]
19067             });
19068         }
19069         
19070         this.picker().select('>.datepicker-days thead', true).first().createChild(dow);
19071     },
19072     
19073     fillMonths: function()
19074     {    
19075         var i = 0;
19076         var months = this.picker().select('>.datepicker-months td', true).first();
19077         
19078         months.dom.innerHTML = '';
19079         
19080         while (i < 12) {
19081             var month = {
19082                 tag: 'span',
19083                 cls: 'month',
19084                 html: Roo.bootstrap.DateField.dates[this.language].monthsShort[i++]
19085             };
19086             
19087             months.createChild(month);
19088         }
19089         
19090     },
19091     
19092     update: function()
19093     {
19094         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;
19095         
19096         if (this.date < this.startDate) {
19097             this.viewDate = new Date(this.startDate);
19098         } else if (this.date > this.endDate) {
19099             this.viewDate = new Date(this.endDate);
19100         } else {
19101             this.viewDate = new Date(this.date);
19102         }
19103         
19104         this.fill();
19105     },
19106     
19107     fill: function() 
19108     {
19109         var d = new Date(this.viewDate),
19110                 year = d.getUTCFullYear(),
19111                 month = d.getUTCMonth(),
19112                 startYear = this.startDate !== -Infinity ? this.startDate.getUTCFullYear() : -Infinity,
19113                 startMonth = this.startDate !== -Infinity ? this.startDate.getUTCMonth() : -Infinity,
19114                 endYear = this.endDate !== Infinity ? this.endDate.getUTCFullYear() : Infinity,
19115                 endMonth = this.endDate !== Infinity ? this.endDate.getUTCMonth() : Infinity,
19116                 currentDate = this.date && this.date.valueOf(),
19117                 today = this.UTCToday();
19118         
19119         this.picker().select('>.datepicker-days thead th.switch', true).first().dom.innerHTML = Roo.bootstrap.DateField.dates[this.language].months[month]+' '+year;
19120         
19121 //        this.picker().select('>tfoot th.today', true).first().dom.innerHTML = Roo.bootstrap.DateField.dates[this.language].today;
19122         
19123 //        this.picker.select('>tfoot th.today').
19124 //                                              .text(dates[this.language].today)
19125 //                                              .toggle(this.todayBtn !== false);
19126     
19127         this.updateNavArrows();
19128         this.fillMonths();
19129                                                 
19130         var prevMonth = this.UTCDate(year, month-1, 28,0,0,0,0),
19131         
19132         day = prevMonth.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
19133          
19134         prevMonth.setUTCDate(day);
19135         
19136         prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.weekStart + 7)%7);
19137         
19138         var nextMonth = new Date(prevMonth);
19139         
19140         nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
19141         
19142         nextMonth = nextMonth.valueOf();
19143         
19144         var fillMonths = false;
19145         
19146         this.picker().select('>.datepicker-days tbody',true).first().dom.innerHTML = '';
19147         
19148         while(prevMonth.valueOf() <= nextMonth) {
19149             var clsName = '';
19150             
19151             if (prevMonth.getUTCDay() === this.weekStart) {
19152                 if(fillMonths){
19153                     this.picker().select('>.datepicker-days tbody',true).first().createChild(fillMonths);
19154                 }
19155                     
19156                 fillMonths = {
19157                     tag: 'tr',
19158                     cn: []
19159                 };
19160                 
19161                 if(this.calendarWeeks){
19162                     // ISO 8601: First week contains first thursday.
19163                     // ISO also states week starts on Monday, but we can be more abstract here.
19164                     var
19165                     // Start of current week: based on weekstart/current date
19166                     ws = new Date(+prevMonth + (this.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
19167                     // Thursday of this week
19168                     th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
19169                     // First Thursday of year, year from thursday
19170                     yth = new Date(+(yth = this.UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5),
19171                     // Calendar week: ms between thursdays, div ms per day, div 7 days
19172                     calWeek =  (th - yth) / 864e5 / 7 + 1;
19173                     
19174                     fillMonths.cn.push({
19175                         tag: 'td',
19176                         cls: 'cw',
19177                         html: calWeek
19178                     });
19179                 }
19180             }
19181             
19182             if (prevMonth.getUTCFullYear() < year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() < month)) {
19183                 clsName += ' old';
19184             } else if (prevMonth.getUTCFullYear() > year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() > month)) {
19185                 clsName += ' new';
19186             }
19187             if (this.todayHighlight &&
19188                 prevMonth.getUTCFullYear() == today.getFullYear() &&
19189                 prevMonth.getUTCMonth() == today.getMonth() &&
19190                 prevMonth.getUTCDate() == today.getDate()) {
19191                 clsName += ' today';
19192             }
19193             
19194             if (currentDate && prevMonth.valueOf() === currentDate) {
19195                 clsName += ' active';
19196             }
19197             
19198             if (prevMonth.valueOf() < this.startDate || prevMonth.valueOf() > this.endDate ||
19199                     this.daysOfWeekDisabled.indexOf(prevMonth.getUTCDay()) !== -1) {
19200                     clsName += ' disabled';
19201             }
19202             
19203             fillMonths.cn.push({
19204                 tag: 'td',
19205                 cls: 'day ' + clsName,
19206                 html: prevMonth.getDate()
19207             });
19208             
19209             prevMonth.setDate(prevMonth.getDate()+1);
19210         }
19211           
19212         var currentYear = this.date && this.date.getUTCFullYear();
19213         var currentMonth = this.date && this.date.getUTCMonth();
19214         
19215         this.picker().select('>.datepicker-months th.switch',true).first().dom.innerHTML = year;
19216         
19217         Roo.each(this.picker().select('>.datepicker-months tbody span',true).elements, function(v,k){
19218             v.removeClass('active');
19219             
19220             if(currentYear === year && k === currentMonth){
19221                 v.addClass('active');
19222             }
19223             
19224             if (year < startYear || year > endYear || (year == startYear && k < startMonth) || (year == endYear && k > endMonth)) {
19225                 v.addClass('disabled');
19226             }
19227             
19228         });
19229         
19230         
19231         year = parseInt(year/10, 10) * 10;
19232         
19233         this.picker().select('>.datepicker-years th.switch', true).first().dom.innerHTML = year + '-' + (year + 9);
19234         
19235         this.picker().select('>.datepicker-years tbody td',true).first().dom.innerHTML = '';
19236         
19237         year -= 1;
19238         for (var i = -1; i < 11; i++) {
19239             this.picker().select('>.datepicker-years tbody td',true).first().createChild({
19240                 tag: 'span',
19241                 cls: 'year' + (i === -1 || i === 10 ? ' old' : '') + (currentYear === year ? ' active' : '') + (year < startYear || year > endYear ? ' disabled' : ''),
19242                 html: year
19243             });
19244             
19245             year += 1;
19246         }
19247     },
19248     
19249     showMode: function(dir) 
19250     {
19251         if (dir) {
19252             this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
19253         }
19254         
19255         Roo.each(this.picker().select('>div',true).elements, function(v){
19256             v.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
19257             v.hide();
19258         });
19259         this.picker().select('>.datepicker-'+Roo.bootstrap.DateField.modes[this.viewMode].clsName, true).first().show();
19260     },
19261     
19262     place: function()
19263     {
19264         if(this.isInline) {
19265             return;
19266         }
19267         
19268         this.picker().removeClass(['bottom', 'top']);
19269         
19270         if((Roo.lib.Dom.getViewHeight() + Roo.get(document.body).getScroll().top) - (this.inputEl().getBottom() + this.picker().getHeight()) < 0){
19271             /*
19272              * place to the top of element!
19273              *
19274              */
19275             
19276             this.picker().addClass('top');
19277             this.picker().setTop(this.inputEl().getTop() - this.picker().getHeight()).setLeft(this.inputEl().getLeft());
19278             
19279             return;
19280         }
19281         
19282         this.picker().addClass('bottom');
19283         
19284         this.picker().setTop(this.inputEl().getBottom()).setLeft(this.inputEl().getLeft());
19285     },
19286     
19287     parseDate : function(value)
19288     {
19289         if(!value || value instanceof Date){
19290             return value;
19291         }
19292         var v = Date.parseDate(value, this.format);
19293         if (!v && (this.useIso || value.match(/^(\d{4})-0?(\d+)-0?(\d+)/))) {
19294             v = Date.parseDate(value, 'Y-m-d');
19295         }
19296         if(!v && this.altFormats){
19297             if(!this.altFormatsArray){
19298                 this.altFormatsArray = this.altFormats.split("|");
19299             }
19300             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
19301                 v = Date.parseDate(value, this.altFormatsArray[i]);
19302             }
19303         }
19304         return v;
19305     },
19306     
19307     formatDate : function(date, fmt)
19308     {   
19309         return (!date || !(date instanceof Date)) ?
19310         date : date.dateFormat(fmt || this.format);
19311     },
19312     
19313     onFocus : function()
19314     {
19315         Roo.bootstrap.DateField.superclass.onFocus.call(this);
19316         this.showPopup();
19317     },
19318     
19319     onBlur : function()
19320     {
19321         Roo.bootstrap.DateField.superclass.onBlur.call(this);
19322         
19323         var d = this.inputEl().getValue();
19324         
19325         this.setValue(d);
19326                 
19327         this.hidePopup();
19328     },
19329     
19330     showPopup : function()
19331     {
19332         this.picker().show();
19333         this.update();
19334         this.place();
19335         
19336         this.fireEvent('showpopup', this, this.date);
19337     },
19338     
19339     hidePopup : function()
19340     {
19341         if(this.isInline) {
19342             return;
19343         }
19344         this.picker().hide();
19345         this.viewMode = this.startViewMode;
19346         this.showMode();
19347         
19348         this.fireEvent('hidepopup', this, this.date);
19349         
19350     },
19351     
19352     onMousedown: function(e)
19353     {
19354         e.stopPropagation();
19355         e.preventDefault();
19356     },
19357     
19358     keyup: function(e)
19359     {
19360         Roo.bootstrap.DateField.superclass.keyup.call(this);
19361         this.update();
19362     },
19363
19364     setValue: function(v)
19365     {
19366         if(this.fireEvent('beforeselect', this, v) !== false){
19367             var d = new Date(this.parseDate(v) ).clearTime();
19368         
19369             if(isNaN(d.getTime())){
19370                 this.date = this.viewDate = '';
19371                 Roo.bootstrap.DateField.superclass.setValue.call(this, '');
19372                 return;
19373             }
19374
19375             v = this.formatDate(d);
19376
19377             Roo.bootstrap.DateField.superclass.setValue.call(this, v);
19378
19379             this.date = new Date(d.getTime() - d.getTimezoneOffset()*60000);
19380
19381             this.update();
19382
19383             this.fireEvent('select', this, this.date);
19384         }
19385     },
19386     
19387     getValue: function()
19388     {
19389         return this.formatDate(this.date);
19390     },
19391     
19392     fireKey: function(e)
19393     {
19394         if (!this.picker().isVisible()){
19395             if (e.keyCode == 27) { // allow escape to hide and re-show picker
19396                 this.showPopup();
19397             }
19398             return;
19399         }
19400         
19401         var dateChanged = false,
19402         dir, day, month,
19403         newDate, newViewDate;
19404         
19405         switch(e.keyCode){
19406             case 27: // escape
19407                 this.hidePopup();
19408                 e.preventDefault();
19409                 break;
19410             case 37: // left
19411             case 39: // right
19412                 if (!this.keyboardNavigation) {
19413                     break;
19414                 }
19415                 dir = e.keyCode == 37 ? -1 : 1;
19416                 
19417                 if (e.ctrlKey){
19418                     newDate = this.moveYear(this.date, dir);
19419                     newViewDate = this.moveYear(this.viewDate, dir);
19420                 } else if (e.shiftKey){
19421                     newDate = this.moveMonth(this.date, dir);
19422                     newViewDate = this.moveMonth(this.viewDate, dir);
19423                 } else {
19424                     newDate = new Date(this.date);
19425                     newDate.setUTCDate(this.date.getUTCDate() + dir);
19426                     newViewDate = new Date(this.viewDate);
19427                     newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir);
19428                 }
19429                 if (this.dateWithinRange(newDate)){
19430                     this.date = newDate;
19431                     this.viewDate = newViewDate;
19432                     this.setValue(this.formatDate(this.date));
19433 //                    this.update();
19434                     e.preventDefault();
19435                     dateChanged = true;
19436                 }
19437                 break;
19438             case 38: // up
19439             case 40: // down
19440                 if (!this.keyboardNavigation) {
19441                     break;
19442                 }
19443                 dir = e.keyCode == 38 ? -1 : 1;
19444                 if (e.ctrlKey){
19445                     newDate = this.moveYear(this.date, dir);
19446                     newViewDate = this.moveYear(this.viewDate, dir);
19447                 } else if (e.shiftKey){
19448                     newDate = this.moveMonth(this.date, dir);
19449                     newViewDate = this.moveMonth(this.viewDate, dir);
19450                 } else {
19451                     newDate = new Date(this.date);
19452                     newDate.setUTCDate(this.date.getUTCDate() + dir * 7);
19453                     newViewDate = new Date(this.viewDate);
19454                     newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7);
19455                 }
19456                 if (this.dateWithinRange(newDate)){
19457                     this.date = newDate;
19458                     this.viewDate = newViewDate;
19459                     this.setValue(this.formatDate(this.date));
19460 //                    this.update();
19461                     e.preventDefault();
19462                     dateChanged = true;
19463                 }
19464                 break;
19465             case 13: // enter
19466                 this.setValue(this.formatDate(this.date));
19467                 this.hidePopup();
19468                 e.preventDefault();
19469                 break;
19470             case 9: // tab
19471                 this.setValue(this.formatDate(this.date));
19472                 this.hidePopup();
19473                 break;
19474             case 16: // shift
19475             case 17: // ctrl
19476             case 18: // alt
19477                 break;
19478             default :
19479                 this.hidePopup();
19480                 
19481         }
19482     },
19483     
19484     
19485     onClick: function(e) 
19486     {
19487         e.stopPropagation();
19488         e.preventDefault();
19489         
19490         var target = e.getTarget();
19491         
19492         if(target.nodeName.toLowerCase() === 'i'){
19493             target = Roo.get(target).dom.parentNode;
19494         }
19495         
19496         var nodeName = target.nodeName;
19497         var className = target.className;
19498         var html = target.innerHTML;
19499         //Roo.log(nodeName);
19500         
19501         switch(nodeName.toLowerCase()) {
19502             case 'th':
19503                 switch(className) {
19504                     case 'switch':
19505                         this.showMode(1);
19506                         break;
19507                     case 'prev':
19508                     case 'next':
19509                         var dir = Roo.bootstrap.DateField.modes[this.viewMode].navStep * (className == 'prev' ? -1 : 1);
19510                         switch(this.viewMode){
19511                                 case 0:
19512                                         this.viewDate = this.moveMonth(this.viewDate, dir);
19513                                         break;
19514                                 case 1:
19515                                 case 2:
19516                                         this.viewDate = this.moveYear(this.viewDate, dir);
19517                                         break;
19518                         }
19519                         this.fill();
19520                         break;
19521                     case 'today':
19522                         var date = new Date();
19523                         this.date = this.UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
19524 //                        this.fill()
19525                         this.setValue(this.formatDate(this.date));
19526                         
19527                         this.hidePopup();
19528                         break;
19529                 }
19530                 break;
19531             case 'span':
19532                 if (className.indexOf('disabled') < 0) {
19533                     this.viewDate.setUTCDate(1);
19534                     if (className.indexOf('month') > -1) {
19535                         this.viewDate.setUTCMonth(Roo.bootstrap.DateField.dates[this.language].monthsShort.indexOf(html));
19536                     } else {
19537                         var year = parseInt(html, 10) || 0;
19538                         this.viewDate.setUTCFullYear(year);
19539                         
19540                     }
19541                     
19542                     if(this.singleMode){
19543                         this.setValue(this.formatDate(this.viewDate));
19544                         this.hidePopup();
19545                         return;
19546                     }
19547                     
19548                     this.showMode(-1);
19549                     this.fill();
19550                 }
19551                 break;
19552                 
19553             case 'td':
19554                 //Roo.log(className);
19555                 if (className.indexOf('day') > -1 && className.indexOf('disabled') < 0 ){
19556                     var day = parseInt(html, 10) || 1;
19557                     var year = this.viewDate.getUTCFullYear(),
19558                         month = this.viewDate.getUTCMonth();
19559
19560                     if (className.indexOf('old') > -1) {
19561                         if(month === 0 ){
19562                             month = 11;
19563                             year -= 1;
19564                         }else{
19565                             month -= 1;
19566                         }
19567                     } else if (className.indexOf('new') > -1) {
19568                         if (month == 11) {
19569                             month = 0;
19570                             year += 1;
19571                         } else {
19572                             month += 1;
19573                         }
19574                     }
19575                     //Roo.log([year,month,day]);
19576                     this.date = this.UTCDate(year, month, day,0,0,0,0);
19577                     this.viewDate = this.UTCDate(year, month, Math.min(28, day),0,0,0,0);
19578 //                    this.fill();
19579                     //Roo.log(this.formatDate(this.date));
19580                     this.setValue(this.formatDate(this.date));
19581                     this.hidePopup();
19582                 }
19583                 break;
19584         }
19585     },
19586     
19587     setStartDate: function(startDate)
19588     {
19589         this.startDate = startDate || -Infinity;
19590         if (this.startDate !== -Infinity) {
19591             this.startDate = this.parseDate(this.startDate);
19592         }
19593         this.update();
19594         this.updateNavArrows();
19595     },
19596
19597     setEndDate: function(endDate)
19598     {
19599         this.endDate = endDate || Infinity;
19600         if (this.endDate !== Infinity) {
19601             this.endDate = this.parseDate(this.endDate);
19602         }
19603         this.update();
19604         this.updateNavArrows();
19605     },
19606     
19607     setDaysOfWeekDisabled: function(daysOfWeekDisabled)
19608     {
19609         this.daysOfWeekDisabled = daysOfWeekDisabled || [];
19610         if (typeof(this.daysOfWeekDisabled) !== 'object') {
19611             this.daysOfWeekDisabled = this.daysOfWeekDisabled.split(/,\s*/);
19612         }
19613         this.daysOfWeekDisabled = this.daysOfWeekDisabled.map(function (d) {
19614             return parseInt(d, 10);
19615         });
19616         this.update();
19617         this.updateNavArrows();
19618     },
19619     
19620     updateNavArrows: function() 
19621     {
19622         if(this.singleMode){
19623             return;
19624         }
19625         
19626         var d = new Date(this.viewDate),
19627         year = d.getUTCFullYear(),
19628         month = d.getUTCMonth();
19629         
19630         Roo.each(this.picker().select('.prev', true).elements, function(v){
19631             v.show();
19632             switch (this.viewMode) {
19633                 case 0:
19634
19635                     if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth()) {
19636                         v.hide();
19637                     }
19638                     break;
19639                 case 1:
19640                 case 2:
19641                     if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear()) {
19642                         v.hide();
19643                     }
19644                     break;
19645             }
19646         });
19647         
19648         Roo.each(this.picker().select('.next', true).elements, function(v){
19649             v.show();
19650             switch (this.viewMode) {
19651                 case 0:
19652
19653                     if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth()) {
19654                         v.hide();
19655                     }
19656                     break;
19657                 case 1:
19658                 case 2:
19659                     if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear()) {
19660                         v.hide();
19661                     }
19662                     break;
19663             }
19664         })
19665     },
19666     
19667     moveMonth: function(date, dir)
19668     {
19669         if (!dir) {
19670             return date;
19671         }
19672         var new_date = new Date(date.valueOf()),
19673         day = new_date.getUTCDate(),
19674         month = new_date.getUTCMonth(),
19675         mag = Math.abs(dir),
19676         new_month, test;
19677         dir = dir > 0 ? 1 : -1;
19678         if (mag == 1){
19679             test = dir == -1
19680             // If going back one month, make sure month is not current month
19681             // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
19682             ? function(){
19683                 return new_date.getUTCMonth() == month;
19684             }
19685             // If going forward one month, make sure month is as expected
19686             // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
19687             : function(){
19688                 return new_date.getUTCMonth() != new_month;
19689             };
19690             new_month = month + dir;
19691             new_date.setUTCMonth(new_month);
19692             // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
19693             if (new_month < 0 || new_month > 11) {
19694                 new_month = (new_month + 12) % 12;
19695             }
19696         } else {
19697             // For magnitudes >1, move one month at a time...
19698             for (var i=0; i<mag; i++) {
19699                 // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
19700                 new_date = this.moveMonth(new_date, dir);
19701             }
19702             // ...then reset the day, keeping it in the new month
19703             new_month = new_date.getUTCMonth();
19704             new_date.setUTCDate(day);
19705             test = function(){
19706                 return new_month != new_date.getUTCMonth();
19707             };
19708         }
19709         // Common date-resetting loop -- if date is beyond end of month, make it
19710         // end of month
19711         while (test()){
19712             new_date.setUTCDate(--day);
19713             new_date.setUTCMonth(new_month);
19714         }
19715         return new_date;
19716     },
19717
19718     moveYear: function(date, dir)
19719     {
19720         return this.moveMonth(date, dir*12);
19721     },
19722
19723     dateWithinRange: function(date)
19724     {
19725         return date >= this.startDate && date <= this.endDate;
19726     },
19727
19728     
19729     remove: function() 
19730     {
19731         this.picker().remove();
19732     },
19733     
19734     validateValue : function(value)
19735     {
19736         if(this.getVisibilityEl().hasClass('hidden')){
19737             return true;
19738         }
19739         
19740         if(value.length < 1)  {
19741             if(this.allowBlank){
19742                 return true;
19743             }
19744             return false;
19745         }
19746         
19747         if(value.length < this.minLength){
19748             return false;
19749         }
19750         if(value.length > this.maxLength){
19751             return false;
19752         }
19753         if(this.vtype){
19754             var vt = Roo.form.VTypes;
19755             if(!vt[this.vtype](value, this)){
19756                 return false;
19757             }
19758         }
19759         if(typeof this.validator == "function"){
19760             var msg = this.validator(value);
19761             if(msg !== true){
19762                 return false;
19763             }
19764         }
19765         
19766         if(this.regex && !this.regex.test(value)){
19767             return false;
19768         }
19769         
19770         if(typeof(this.parseDate(value)) == 'undefined'){
19771             return false;
19772         }
19773         
19774         if (this.endDate !== Infinity && this.parseDate(value).getTime() > this.endDate.getTime()) {
19775             return false;
19776         }      
19777         
19778         if (this.startDate !== -Infinity && this.parseDate(value).getTime() < this.startDate.getTime()) {
19779             return false;
19780         } 
19781         
19782         
19783         return true;
19784     },
19785     
19786     reset : function()
19787     {
19788         this.date = this.viewDate = '';
19789         
19790         Roo.bootstrap.DateField.superclass.setValue.call(this, '');
19791     }
19792    
19793 });
19794
19795 Roo.apply(Roo.bootstrap.DateField,  {
19796     
19797     head : {
19798         tag: 'thead',
19799         cn: [
19800         {
19801             tag: 'tr',
19802             cn: [
19803             {
19804                 tag: 'th',
19805                 cls: 'prev',
19806                 html: '<i class="fa fa-arrow-left"/>'
19807             },
19808             {
19809                 tag: 'th',
19810                 cls: 'switch',
19811                 colspan: '5'
19812             },
19813             {
19814                 tag: 'th',
19815                 cls: 'next',
19816                 html: '<i class="fa fa-arrow-right"/>'
19817             }
19818
19819             ]
19820         }
19821         ]
19822     },
19823     
19824     content : {
19825         tag: 'tbody',
19826         cn: [
19827         {
19828             tag: 'tr',
19829             cn: [
19830             {
19831                 tag: 'td',
19832                 colspan: '7'
19833             }
19834             ]
19835         }
19836         ]
19837     },
19838     
19839     footer : {
19840         tag: 'tfoot',
19841         cn: [
19842         {
19843             tag: 'tr',
19844             cn: [
19845             {
19846                 tag: 'th',
19847                 colspan: '7',
19848                 cls: 'today'
19849             }
19850                     
19851             ]
19852         }
19853         ]
19854     },
19855     
19856     dates:{
19857         en: {
19858             days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
19859             daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
19860             daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
19861             months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
19862             monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
19863             today: "Today"
19864         }
19865     },
19866     
19867     modes: [
19868     {
19869         clsName: 'days',
19870         navFnc: 'Month',
19871         navStep: 1
19872     },
19873     {
19874         clsName: 'months',
19875         navFnc: 'FullYear',
19876         navStep: 1
19877     },
19878     {
19879         clsName: 'years',
19880         navFnc: 'FullYear',
19881         navStep: 10
19882     }]
19883 });
19884
19885 Roo.apply(Roo.bootstrap.DateField,  {
19886   
19887     template : {
19888         tag: 'div',
19889         cls: 'datepicker dropdown-menu roo-dynamic',
19890         cn: [
19891         {
19892             tag: 'div',
19893             cls: 'datepicker-days',
19894             cn: [
19895             {
19896                 tag: 'table',
19897                 cls: 'table-condensed',
19898                 cn:[
19899                 Roo.bootstrap.DateField.head,
19900                 {
19901                     tag: 'tbody'
19902                 },
19903                 Roo.bootstrap.DateField.footer
19904                 ]
19905             }
19906             ]
19907         },
19908         {
19909             tag: 'div',
19910             cls: 'datepicker-months',
19911             cn: [
19912             {
19913                 tag: 'table',
19914                 cls: 'table-condensed',
19915                 cn:[
19916                 Roo.bootstrap.DateField.head,
19917                 Roo.bootstrap.DateField.content,
19918                 Roo.bootstrap.DateField.footer
19919                 ]
19920             }
19921             ]
19922         },
19923         {
19924             tag: 'div',
19925             cls: 'datepicker-years',
19926             cn: [
19927             {
19928                 tag: 'table',
19929                 cls: 'table-condensed',
19930                 cn:[
19931                 Roo.bootstrap.DateField.head,
19932                 Roo.bootstrap.DateField.content,
19933                 Roo.bootstrap.DateField.footer
19934                 ]
19935             }
19936             ]
19937         }
19938         ]
19939     }
19940 });
19941
19942  
19943
19944  /*
19945  * - LGPL
19946  *
19947  * TimeField
19948  * 
19949  */
19950
19951 /**
19952  * @class Roo.bootstrap.TimeField
19953  * @extends Roo.bootstrap.Input
19954  * Bootstrap DateField class
19955  * 
19956  * 
19957  * @constructor
19958  * Create a new TimeField
19959  * @param {Object} config The config object
19960  */
19961
19962 Roo.bootstrap.TimeField = function(config){
19963     Roo.bootstrap.TimeField.superclass.constructor.call(this, config);
19964     this.addEvents({
19965             /**
19966              * @event show
19967              * Fires when this field show.
19968              * @param {Roo.bootstrap.DateField} thisthis
19969              * @param {Mixed} date The date value
19970              */
19971             show : true,
19972             /**
19973              * @event show
19974              * Fires when this field hide.
19975              * @param {Roo.bootstrap.DateField} this
19976              * @param {Mixed} date The date value
19977              */
19978             hide : true,
19979             /**
19980              * @event select
19981              * Fires when select a date.
19982              * @param {Roo.bootstrap.DateField} this
19983              * @param {Mixed} date The date value
19984              */
19985             select : true
19986         });
19987 };
19988
19989 Roo.extend(Roo.bootstrap.TimeField, Roo.bootstrap.Input,  {
19990     
19991     /**
19992      * @cfg {String} format
19993      * The default time format string which can be overriden for localization support.  The format must be
19994      * valid according to {@link Date#parseDate} (defaults to 'H:i').
19995      */
19996     format : "H:i",
19997        
19998     onRender: function(ct, position)
19999     {
20000         
20001         Roo.bootstrap.TimeField.superclass.onRender.call(this, ct, position);
20002                 
20003         this.el.select('>.input-group', true).first().createChild(Roo.bootstrap.TimeField.template);
20004         
20005         this.picker().setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
20006         
20007         this.pop = this.picker().select('>.datepicker-time',true).first();
20008         this.pop.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
20009         
20010         this.picker().on('mousedown', this.onMousedown, this);
20011         this.picker().on('click', this.onClick, this);
20012         
20013         this.picker().addClass('datepicker-dropdown');
20014     
20015         this.fillTime();
20016         this.update();
20017             
20018         this.pop.select('span.hours-up', true).first().on('click', this.onIncrementHours, this);
20019         this.pop.select('span.hours-down', true).first().on('click', this.onDecrementHours, this);
20020         this.pop.select('span.minutes-up', true).first().on('click', this.onIncrementMinutes, this);
20021         this.pop.select('span.minutes-down', true).first().on('click', this.onDecrementMinutes, this);
20022         this.pop.select('button.period', true).first().on('click', this.onTogglePeriod, this);
20023         this.pop.select('button.ok', true).first().on('click', this.setTime, this);
20024
20025     },
20026     
20027     fireKey: function(e){
20028         if (!this.picker().isVisible()){
20029             if (e.keyCode == 27) { // allow escape to hide and re-show picker
20030                 this.show();
20031             }
20032             return;
20033         }
20034
20035         e.preventDefault();
20036         
20037         switch(e.keyCode){
20038             case 27: // escape
20039                 this.hide();
20040                 break;
20041             case 37: // left
20042             case 39: // right
20043                 this.onTogglePeriod();
20044                 break;
20045             case 38: // up
20046                 this.onIncrementMinutes();
20047                 break;
20048             case 40: // down
20049                 this.onDecrementMinutes();
20050                 break;
20051             case 13: // enter
20052             case 9: // tab
20053                 this.setTime();
20054                 break;
20055         }
20056     },
20057     
20058     onClick: function(e) {
20059         e.stopPropagation();
20060         e.preventDefault();
20061     },
20062     
20063     picker : function()
20064     {
20065         return this.el.select('.datepicker', true).first();
20066     },
20067     
20068     fillTime: function()
20069     {    
20070         var time = this.pop.select('tbody', true).first();
20071         
20072         time.dom.innerHTML = '';
20073         
20074         time.createChild({
20075             tag: 'tr',
20076             cn: [
20077                 {
20078                     tag: 'td',
20079                     cn: [
20080                         {
20081                             tag: 'a',
20082                             href: '#',
20083                             cls: 'btn',
20084                             cn: [
20085                                 {
20086                                     tag: 'span',
20087                                     cls: 'hours-up glyphicon glyphicon-chevron-up'
20088                                 }
20089                             ]
20090                         } 
20091                     ]
20092                 },
20093                 {
20094                     tag: 'td',
20095                     cls: 'separator'
20096                 },
20097                 {
20098                     tag: 'td',
20099                     cn: [
20100                         {
20101                             tag: 'a',
20102                             href: '#',
20103                             cls: 'btn',
20104                             cn: [
20105                                 {
20106                                     tag: 'span',
20107                                     cls: 'minutes-up glyphicon glyphicon-chevron-up'
20108                                 }
20109                             ]
20110                         }
20111                     ]
20112                 },
20113                 {
20114                     tag: 'td',
20115                     cls: 'separator'
20116                 }
20117             ]
20118         });
20119         
20120         time.createChild({
20121             tag: 'tr',
20122             cn: [
20123                 {
20124                     tag: 'td',
20125                     cn: [
20126                         {
20127                             tag: 'span',
20128                             cls: 'timepicker-hour',
20129                             html: '00'
20130                         }  
20131                     ]
20132                 },
20133                 {
20134                     tag: 'td',
20135                     cls: 'separator',
20136                     html: ':'
20137                 },
20138                 {
20139                     tag: 'td',
20140                     cn: [
20141                         {
20142                             tag: 'span',
20143                             cls: 'timepicker-minute',
20144                             html: '00'
20145                         }  
20146                     ]
20147                 },
20148                 {
20149                     tag: 'td',
20150                     cls: 'separator'
20151                 },
20152                 {
20153                     tag: 'td',
20154                     cn: [
20155                         {
20156                             tag: 'button',
20157                             type: 'button',
20158                             cls: 'btn btn-primary period',
20159                             html: 'AM'
20160                             
20161                         }
20162                     ]
20163                 }
20164             ]
20165         });
20166         
20167         time.createChild({
20168             tag: 'tr',
20169             cn: [
20170                 {
20171                     tag: 'td',
20172                     cn: [
20173                         {
20174                             tag: 'a',
20175                             href: '#',
20176                             cls: 'btn',
20177                             cn: [
20178                                 {
20179                                     tag: 'span',
20180                                     cls: 'hours-down glyphicon glyphicon-chevron-down'
20181                                 }
20182                             ]
20183                         }
20184                     ]
20185                 },
20186                 {
20187                     tag: 'td',
20188                     cls: 'separator'
20189                 },
20190                 {
20191                     tag: 'td',
20192                     cn: [
20193                         {
20194                             tag: 'a',
20195                             href: '#',
20196                             cls: 'btn',
20197                             cn: [
20198                                 {
20199                                     tag: 'span',
20200                                     cls: 'minutes-down glyphicon glyphicon-chevron-down'
20201                                 }
20202                             ]
20203                         }
20204                     ]
20205                 },
20206                 {
20207                     tag: 'td',
20208                     cls: 'separator'
20209                 }
20210             ]
20211         });
20212         
20213     },
20214     
20215     update: function()
20216     {
20217         
20218         this.time = (typeof(this.time) === 'undefined') ? new Date() : this.time;
20219         
20220         this.fill();
20221     },
20222     
20223     fill: function() 
20224     {
20225         var hours = this.time.getHours();
20226         var minutes = this.time.getMinutes();
20227         var period = 'AM';
20228         
20229         if(hours > 11){
20230             period = 'PM';
20231         }
20232         
20233         if(hours == 0){
20234             hours = 12;
20235         }
20236         
20237         
20238         if(hours > 12){
20239             hours = hours - 12;
20240         }
20241         
20242         if(hours < 10){
20243             hours = '0' + hours;
20244         }
20245         
20246         if(minutes < 10){
20247             minutes = '0' + minutes;
20248         }
20249         
20250         this.pop.select('.timepicker-hour', true).first().dom.innerHTML = hours;
20251         this.pop.select('.timepicker-minute', true).first().dom.innerHTML = minutes;
20252         this.pop.select('button', true).first().dom.innerHTML = period;
20253         
20254     },
20255     
20256     place: function()
20257     {   
20258         this.picker().removeClass(['bottom-left', 'bottom-right', 'top-left', 'top-right']);
20259         
20260         var cls = ['bottom'];
20261         
20262         if((Roo.lib.Dom.getViewHeight() + Roo.get(document.body).getScroll().top) - (this.inputEl().getBottom() + this.picker().getHeight()) < 0){ // top
20263             cls.pop();
20264             cls.push('top');
20265         }
20266         
20267         cls.push('right');
20268         
20269         if((Roo.lib.Dom.getViewWidth() + Roo.get(document.body).getScroll().left) - (this.inputEl().getLeft() + this.picker().getWidth()) < 0){ // left
20270             cls.pop();
20271             cls.push('left');
20272         }
20273         
20274         this.picker().addClass(cls.join('-'));
20275         
20276         var _this = this;
20277         
20278         Roo.each(cls, function(c){
20279             if(c == 'bottom'){
20280                 _this.picker().setTop(_this.inputEl().getHeight());
20281                 return;
20282             }
20283             if(c == 'top'){
20284                 _this.picker().setTop(0 - _this.picker().getHeight());
20285                 return;
20286             }
20287             
20288             if(c == 'left'){
20289                 _this.picker().setLeft(_this.inputEl().getLeft() + _this.inputEl().getWidth() - _this.el.getLeft() - _this.picker().getWidth());
20290                 return;
20291             }
20292             if(c == 'right'){
20293                 _this.picker().setLeft(_this.inputEl().getLeft() - _this.el.getLeft());
20294                 return;
20295             }
20296         });
20297         
20298     },
20299   
20300     onFocus : function()
20301     {
20302         Roo.bootstrap.TimeField.superclass.onFocus.call(this);
20303         this.show();
20304     },
20305     
20306     onBlur : function()
20307     {
20308         Roo.bootstrap.TimeField.superclass.onBlur.call(this);
20309         this.hide();
20310     },
20311     
20312     show : function()
20313     {
20314         this.picker().show();
20315         this.pop.show();
20316         this.update();
20317         this.place();
20318         
20319         this.fireEvent('show', this, this.date);
20320     },
20321     
20322     hide : function()
20323     {
20324         this.picker().hide();
20325         this.pop.hide();
20326         
20327         this.fireEvent('hide', this, this.date);
20328     },
20329     
20330     setTime : function()
20331     {
20332         this.hide();
20333         this.setValue(this.time.format(this.format));
20334         
20335         this.fireEvent('select', this, this.date);
20336         
20337         
20338     },
20339     
20340     onMousedown: function(e){
20341         e.stopPropagation();
20342         e.preventDefault();
20343     },
20344     
20345     onIncrementHours: function()
20346     {
20347         Roo.log('onIncrementHours');
20348         this.time = this.time.add(Date.HOUR, 1);
20349         this.update();
20350         
20351     },
20352     
20353     onDecrementHours: function()
20354     {
20355         Roo.log('onDecrementHours');
20356         this.time = this.time.add(Date.HOUR, -1);
20357         this.update();
20358     },
20359     
20360     onIncrementMinutes: function()
20361     {
20362         Roo.log('onIncrementMinutes');
20363         this.time = this.time.add(Date.MINUTE, 1);
20364         this.update();
20365     },
20366     
20367     onDecrementMinutes: function()
20368     {
20369         Roo.log('onDecrementMinutes');
20370         this.time = this.time.add(Date.MINUTE, -1);
20371         this.update();
20372     },
20373     
20374     onTogglePeriod: function()
20375     {
20376         Roo.log('onTogglePeriod');
20377         this.time = this.time.add(Date.HOUR, 12);
20378         this.update();
20379     }
20380     
20381    
20382 });
20383
20384 Roo.apply(Roo.bootstrap.TimeField,  {
20385     
20386     content : {
20387         tag: 'tbody',
20388         cn: [
20389             {
20390                 tag: 'tr',
20391                 cn: [
20392                 {
20393                     tag: 'td',
20394                     colspan: '7'
20395                 }
20396                 ]
20397             }
20398         ]
20399     },
20400     
20401     footer : {
20402         tag: 'tfoot',
20403         cn: [
20404             {
20405                 tag: 'tr',
20406                 cn: [
20407                 {
20408                     tag: 'th',
20409                     colspan: '7',
20410                     cls: '',
20411                     cn: [
20412                         {
20413                             tag: 'button',
20414                             cls: 'btn btn-info ok',
20415                             html: 'OK'
20416                         }
20417                     ]
20418                 }
20419
20420                 ]
20421             }
20422         ]
20423     }
20424 });
20425
20426 Roo.apply(Roo.bootstrap.TimeField,  {
20427   
20428     template : {
20429         tag: 'div',
20430         cls: 'datepicker dropdown-menu',
20431         cn: [
20432             {
20433                 tag: 'div',
20434                 cls: 'datepicker-time',
20435                 cn: [
20436                 {
20437                     tag: 'table',
20438                     cls: 'table-condensed',
20439                     cn:[
20440                     Roo.bootstrap.TimeField.content,
20441                     Roo.bootstrap.TimeField.footer
20442                     ]
20443                 }
20444                 ]
20445             }
20446         ]
20447     }
20448 });
20449
20450  
20451
20452  /*
20453  * - LGPL
20454  *
20455  * MonthField
20456  * 
20457  */
20458
20459 /**
20460  * @class Roo.bootstrap.MonthField
20461  * @extends Roo.bootstrap.Input
20462  * Bootstrap MonthField class
20463  * 
20464  * @cfg {String} language default en
20465  * 
20466  * @constructor
20467  * Create a new MonthField
20468  * @param {Object} config The config object
20469  */
20470
20471 Roo.bootstrap.MonthField = function(config){
20472     Roo.bootstrap.MonthField.superclass.constructor.call(this, config);
20473     
20474     this.addEvents({
20475         /**
20476          * @event show
20477          * Fires when this field show.
20478          * @param {Roo.bootstrap.MonthField} this
20479          * @param {Mixed} date The date value
20480          */
20481         show : true,
20482         /**
20483          * @event show
20484          * Fires when this field hide.
20485          * @param {Roo.bootstrap.MonthField} this
20486          * @param {Mixed} date The date value
20487          */
20488         hide : true,
20489         /**
20490          * @event select
20491          * Fires when select a date.
20492          * @param {Roo.bootstrap.MonthField} this
20493          * @param {String} oldvalue The old value
20494          * @param {String} newvalue The new value
20495          */
20496         select : true
20497     });
20498 };
20499
20500 Roo.extend(Roo.bootstrap.MonthField, Roo.bootstrap.Input,  {
20501     
20502     onRender: function(ct, position)
20503     {
20504         
20505         Roo.bootstrap.MonthField.superclass.onRender.call(this, ct, position);
20506         
20507         this.language = this.language || 'en';
20508         this.language = this.language in Roo.bootstrap.MonthField.dates ? this.language : this.language.split('-')[0];
20509         this.language = this.language in Roo.bootstrap.MonthField.dates ? this.language : "en";
20510         
20511         this.isRTL = Roo.bootstrap.MonthField.dates[this.language].rtl || false;
20512         this.isInline = false;
20513         this.isInput = true;
20514         this.component = this.el.select('.add-on', true).first() || false;
20515         this.component = (this.component && this.component.length === 0) ? false : this.component;
20516         this.hasInput = this.component && this.inputEL().length;
20517         
20518         this.pickerEl = Roo.get(document.body).createChild(Roo.bootstrap.MonthField.template);
20519         
20520         this.picker().setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
20521         
20522         this.picker().on('mousedown', this.onMousedown, this);
20523         this.picker().on('click', this.onClick, this);
20524         
20525         this.picker().addClass('datepicker-dropdown');
20526         
20527         Roo.each(this.picker().select('tbody > tr > td', true).elements, function(v){
20528             v.setStyle('width', '189px');
20529         });
20530         
20531         this.fillMonths();
20532         
20533         this.update();
20534         
20535         if(this.isInline) {
20536             this.show();
20537         }
20538         
20539     },
20540     
20541     setValue: function(v, suppressEvent)
20542     {   
20543         var o = this.getValue();
20544         
20545         Roo.bootstrap.MonthField.superclass.setValue.call(this, v);
20546         
20547         this.update();
20548
20549         if(suppressEvent !== true){
20550             this.fireEvent('select', this, o, v);
20551         }
20552         
20553     },
20554     
20555     getValue: function()
20556     {
20557         return this.value;
20558     },
20559     
20560     onClick: function(e) 
20561     {
20562         e.stopPropagation();
20563         e.preventDefault();
20564         
20565         var target = e.getTarget();
20566         
20567         if(target.nodeName.toLowerCase() === 'i'){
20568             target = Roo.get(target).dom.parentNode;
20569         }
20570         
20571         var nodeName = target.nodeName;
20572         var className = target.className;
20573         var html = target.innerHTML;
20574         
20575         if(nodeName.toLowerCase() != 'span' || className.indexOf('disabled') > -1 || className.indexOf('month') == -1){
20576             return;
20577         }
20578         
20579         this.vIndex = Roo.bootstrap.MonthField.dates[this.language].monthsShort.indexOf(html);
20580         
20581         this.setValue(Roo.bootstrap.MonthField.dates[this.language].months[this.vIndex]);
20582         
20583         this.hide();
20584                         
20585     },
20586     
20587     picker : function()
20588     {
20589         return this.pickerEl;
20590     },
20591     
20592     fillMonths: function()
20593     {    
20594         var i = 0;
20595         var months = this.picker().select('>.datepicker-months td', true).first();
20596         
20597         months.dom.innerHTML = '';
20598         
20599         while (i < 12) {
20600             var month = {
20601                 tag: 'span',
20602                 cls: 'month',
20603                 html: Roo.bootstrap.MonthField.dates[this.language].monthsShort[i++]
20604             };
20605             
20606             months.createChild(month);
20607         }
20608         
20609     },
20610     
20611     update: function()
20612     {
20613         var _this = this;
20614         
20615         if(typeof(this.vIndex) == 'undefined' && this.value.length){
20616             this.vIndex = Roo.bootstrap.MonthField.dates[this.language].months.indexOf(this.value);
20617         }
20618         
20619         Roo.each(this.pickerEl.select('> .datepicker-months tbody > tr > td > span', true).elements, function(e, k){
20620             e.removeClass('active');
20621             
20622             if(typeof(_this.vIndex) != 'undefined' && k == _this.vIndex){
20623                 e.addClass('active');
20624             }
20625         })
20626     },
20627     
20628     place: function()
20629     {
20630         if(this.isInline) {
20631             return;
20632         }
20633         
20634         this.picker().removeClass(['bottom', 'top']);
20635         
20636         if((Roo.lib.Dom.getViewHeight() + Roo.get(document.body).getScroll().top) - (this.inputEl().getBottom() + this.picker().getHeight()) < 0){
20637             /*
20638              * place to the top of element!
20639              *
20640              */
20641             
20642             this.picker().addClass('top');
20643             this.picker().setTop(this.inputEl().getTop() - this.picker().getHeight()).setLeft(this.inputEl().getLeft());
20644             
20645             return;
20646         }
20647         
20648         this.picker().addClass('bottom');
20649         
20650         this.picker().setTop(this.inputEl().getBottom()).setLeft(this.inputEl().getLeft());
20651     },
20652     
20653     onFocus : function()
20654     {
20655         Roo.bootstrap.MonthField.superclass.onFocus.call(this);
20656         this.show();
20657     },
20658     
20659     onBlur : function()
20660     {
20661         Roo.bootstrap.MonthField.superclass.onBlur.call(this);
20662         
20663         var d = this.inputEl().getValue();
20664         
20665         this.setValue(d);
20666                 
20667         this.hide();
20668     },
20669     
20670     show : function()
20671     {
20672         this.picker().show();
20673         this.picker().select('>.datepicker-months', true).first().show();
20674         this.update();
20675         this.place();
20676         
20677         this.fireEvent('show', this, this.date);
20678     },
20679     
20680     hide : function()
20681     {
20682         if(this.isInline) {
20683             return;
20684         }
20685         this.picker().hide();
20686         this.fireEvent('hide', this, this.date);
20687         
20688     },
20689     
20690     onMousedown: function(e)
20691     {
20692         e.stopPropagation();
20693         e.preventDefault();
20694     },
20695     
20696     keyup: function(e)
20697     {
20698         Roo.bootstrap.MonthField.superclass.keyup.call(this);
20699         this.update();
20700     },
20701
20702     fireKey: function(e)
20703     {
20704         if (!this.picker().isVisible()){
20705             if (e.keyCode == 27)   {// allow escape to hide and re-show picker
20706                 this.show();
20707             }
20708             return;
20709         }
20710         
20711         var dir;
20712         
20713         switch(e.keyCode){
20714             case 27: // escape
20715                 this.hide();
20716                 e.preventDefault();
20717                 break;
20718             case 37: // left
20719             case 39: // right
20720                 dir = e.keyCode == 37 ? -1 : 1;
20721                 
20722                 this.vIndex = this.vIndex + dir;
20723                 
20724                 if(this.vIndex < 0){
20725                     this.vIndex = 0;
20726                 }
20727                 
20728                 if(this.vIndex > 11){
20729                     this.vIndex = 11;
20730                 }
20731                 
20732                 if(isNaN(this.vIndex)){
20733                     this.vIndex = 0;
20734                 }
20735                 
20736                 this.setValue(Roo.bootstrap.MonthField.dates[this.language].months[this.vIndex]);
20737                 
20738                 break;
20739             case 38: // up
20740             case 40: // down
20741                 
20742                 dir = e.keyCode == 38 ? -1 : 1;
20743                 
20744                 this.vIndex = this.vIndex + dir * 4;
20745                 
20746                 if(this.vIndex < 0){
20747                     this.vIndex = 0;
20748                 }
20749                 
20750                 if(this.vIndex > 11){
20751                     this.vIndex = 11;
20752                 }
20753                 
20754                 if(isNaN(this.vIndex)){
20755                     this.vIndex = 0;
20756                 }
20757                 
20758                 this.setValue(Roo.bootstrap.MonthField.dates[this.language].months[this.vIndex]);
20759                 break;
20760                 
20761             case 13: // enter
20762                 
20763                 if(typeof(this.vIndex) != 'undefined' && !isNaN(this.vIndex)){
20764                     this.setValue(Roo.bootstrap.MonthField.dates[this.language].months[this.vIndex]);
20765                 }
20766                 
20767                 this.hide();
20768                 e.preventDefault();
20769                 break;
20770             case 9: // tab
20771                 if(typeof(this.vIndex) != 'undefined' && !isNaN(this.vIndex)){
20772                     this.setValue(Roo.bootstrap.MonthField.dates[this.language].months[this.vIndex]);
20773                 }
20774                 this.hide();
20775                 break;
20776             case 16: // shift
20777             case 17: // ctrl
20778             case 18: // alt
20779                 break;
20780             default :
20781                 this.hide();
20782                 
20783         }
20784     },
20785     
20786     remove: function() 
20787     {
20788         this.picker().remove();
20789     }
20790    
20791 });
20792
20793 Roo.apply(Roo.bootstrap.MonthField,  {
20794     
20795     content : {
20796         tag: 'tbody',
20797         cn: [
20798         {
20799             tag: 'tr',
20800             cn: [
20801             {
20802                 tag: 'td',
20803                 colspan: '7'
20804             }
20805             ]
20806         }
20807         ]
20808     },
20809     
20810     dates:{
20811         en: {
20812             months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
20813             monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
20814         }
20815     }
20816 });
20817
20818 Roo.apply(Roo.bootstrap.MonthField,  {
20819   
20820     template : {
20821         tag: 'div',
20822         cls: 'datepicker dropdown-menu roo-dynamic',
20823         cn: [
20824             {
20825                 tag: 'div',
20826                 cls: 'datepicker-months',
20827                 cn: [
20828                 {
20829                     tag: 'table',
20830                     cls: 'table-condensed',
20831                     cn:[
20832                         Roo.bootstrap.DateField.content
20833                     ]
20834                 }
20835                 ]
20836             }
20837         ]
20838     }
20839 });
20840
20841  
20842
20843  
20844  /*
20845  * - LGPL
20846  *
20847  * CheckBox
20848  * 
20849  */
20850
20851 /**
20852  * @class Roo.bootstrap.CheckBox
20853  * @extends Roo.bootstrap.Input
20854  * Bootstrap CheckBox class
20855  * 
20856  * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
20857  * @cfg {String} inputValue The value that should go into the generated input element's value when checked.
20858  * @cfg {String} boxLabel The text that appears beside the checkbox
20859  * @cfg {String} weight (primary|warning|info|danger|success) The text that appears beside the checkbox
20860  * @cfg {Boolean} checked initnal the element
20861  * @cfg {Boolean} inline inline the element (default false)
20862  * @cfg {String} groupId the checkbox group id // normal just use for checkbox
20863  * @cfg {String} tooltip label tooltip
20864  * 
20865  * @constructor
20866  * Create a new CheckBox
20867  * @param {Object} config The config object
20868  */
20869
20870 Roo.bootstrap.CheckBox = function(config){
20871     Roo.bootstrap.CheckBox.superclass.constructor.call(this, config);
20872    
20873     this.addEvents({
20874         /**
20875         * @event check
20876         * Fires when the element is checked or unchecked.
20877         * @param {Roo.bootstrap.CheckBox} this This input
20878         * @param {Boolean} checked The new checked value
20879         */
20880        check : true,
20881        /**
20882         * @event click
20883         * Fires when the element is click.
20884         * @param {Roo.bootstrap.CheckBox} this This input
20885         */
20886        click : true
20887     });
20888     
20889 };
20890
20891 Roo.extend(Roo.bootstrap.CheckBox, Roo.bootstrap.Input,  {
20892   
20893     inputType: 'checkbox',
20894     inputValue: 1,
20895     valueOff: 0,
20896     boxLabel: false,
20897     checked: false,
20898     weight : false,
20899     inline: false,
20900     tooltip : '',
20901     
20902     // checkbox success does not make any sense really.. 
20903     invalidClass : "",
20904     validClass : "",
20905     
20906     
20907     getAutoCreate : function()
20908     {
20909         var align = (!this.labelAlign) ? this.parentLabelAlign() : this.labelAlign;
20910         
20911         var id = Roo.id();
20912         
20913         var cfg = {};
20914         
20915         cfg.cls = 'form-group ' + this.inputType; //input-group
20916         
20917         if(this.inline){
20918             cfg.cls += ' ' + this.inputType + '-inline';
20919         }
20920         
20921         var input =  {
20922             tag: 'input',
20923             id : id,
20924             type : this.inputType,
20925             value : this.inputValue,
20926             cls : 'roo-' + this.inputType, //'form-box',
20927             placeholder : this.placeholder || ''
20928             
20929         };
20930         
20931         if(this.inputType != 'radio'){
20932             var hidden =  {
20933                 tag: 'input',
20934                 type : 'hidden',
20935                 cls : 'roo-hidden-value',
20936                 value : this.checked ? this.inputValue : this.valueOff
20937             };
20938         }
20939         
20940             
20941         if (this.weight) { // Validity check?
20942             cfg.cls += " " + this.inputType + "-" + this.weight;
20943         }
20944         
20945         if (this.disabled) {
20946             input.disabled=true;
20947         }
20948         
20949         if(this.checked){
20950             input.checked = this.checked;
20951         }
20952         
20953         if (this.name) {
20954             
20955             input.name = this.name;
20956             
20957             if(this.inputType != 'radio'){
20958                 hidden.name = this.name;
20959                 input.name = '_hidden_' + this.name;
20960             }
20961         }
20962         
20963         if (this.size) {
20964             input.cls += ' input-' + this.size;
20965         }
20966         
20967         var settings=this;
20968         
20969         ['xs','sm','md','lg'].map(function(size){
20970             if (settings[size]) {
20971                 cfg.cls += ' col-' + size + '-' + settings[size];
20972             }
20973         });
20974         
20975         var inputblock = input;
20976          
20977         if (this.before || this.after) {
20978             
20979             inputblock = {
20980                 cls : 'input-group',
20981                 cn :  [] 
20982             };
20983             
20984             if (this.before) {
20985                 inputblock.cn.push({
20986                     tag :'span',
20987                     cls : 'input-group-addon',
20988                     html : this.before
20989                 });
20990             }
20991             
20992             inputblock.cn.push(input);
20993             
20994             if(this.inputType != 'radio'){
20995                 inputblock.cn.push(hidden);
20996             }
20997             
20998             if (this.after) {
20999                 inputblock.cn.push({
21000                     tag :'span',
21001                     cls : 'input-group-addon',
21002                     html : this.after
21003                 });
21004             }
21005             
21006         }
21007         var boxLabelCfg = false;
21008         
21009         if(this.boxLabel){
21010            
21011             boxLabelCfg = {
21012                 tag: 'label',
21013                 //'for': id, // box label is handled by onclick - so no for...
21014                 cls: 'box-label',
21015                 html: this.boxLabel
21016             };
21017             if(this.tooltip){
21018                 boxLabelCfg.tooltip = this.tooltip;
21019             }
21020              
21021         }
21022         
21023         
21024         if (align ==='left' && this.fieldLabel.length) {
21025 //                Roo.log("left and has label");
21026             cfg.cn = [
21027                 {
21028                     tag: 'label',
21029                     'for' :  id,
21030                     cls : 'control-label',
21031                     html : this.fieldLabel
21032                 },
21033                 {
21034                     cls : "", 
21035                     cn: [
21036                         inputblock
21037                     ]
21038                 }
21039             ];
21040             
21041             if (boxLabelCfg) {
21042                 cfg.cn[1].cn.push(boxLabelCfg);
21043             }
21044             
21045             if(this.labelWidth > 12){
21046                 cfg.cn[0].style = "width: " + this.labelWidth + 'px';
21047             }
21048             
21049             if(this.labelWidth < 13 && this.labelmd == 0){
21050                 this.labelmd = this.labelWidth;
21051             }
21052             
21053             if(this.labellg > 0){
21054                 cfg.cn[0].cls += ' col-lg-' + this.labellg;
21055                 cfg.cn[1].cls += ' col-lg-' + (12 - this.labellg);
21056             }
21057             
21058             if(this.labelmd > 0){
21059                 cfg.cn[0].cls += ' col-md-' + this.labelmd;
21060                 cfg.cn[1].cls += ' col-md-' + (12 - this.labelmd);
21061             }
21062             
21063             if(this.labelsm > 0){
21064                 cfg.cn[0].cls += ' col-sm-' + this.labelsm;
21065                 cfg.cn[1].cls += ' col-sm-' + (12 - this.labelsm);
21066             }
21067             
21068             if(this.labelxs > 0){
21069                 cfg.cn[0].cls += ' col-xs-' + this.labelxs;
21070                 cfg.cn[1].cls += ' col-xs-' + (12 - this.labelxs);
21071             }
21072             
21073         } else if ( this.fieldLabel.length) {
21074 //                Roo.log(" label");
21075                 cfg.cn = [
21076                    
21077                     {
21078                         tag: this.boxLabel ? 'span' : 'label',
21079                         'for': id,
21080                         cls: 'control-label box-input-label',
21081                         //cls : 'input-group-addon',
21082                         html : this.fieldLabel
21083                     },
21084                     
21085                     inputblock
21086                     
21087                 ];
21088                 if (boxLabelCfg) {
21089                     cfg.cn.push(boxLabelCfg);
21090                 }
21091
21092         } else {
21093             
21094 //                Roo.log(" no label && no align");
21095                 cfg.cn = [  inputblock ] ;
21096                 if (boxLabelCfg) {
21097                     cfg.cn.push(boxLabelCfg);
21098                 }
21099
21100                 
21101         }
21102         
21103        
21104         
21105         if(this.inputType != 'radio'){
21106             cfg.cn.push(hidden);
21107         }
21108         
21109         return cfg;
21110         
21111     },
21112     
21113     /**
21114      * return the real input element.
21115      */
21116     inputEl: function ()
21117     {
21118         return this.el.select('input.roo-' + this.inputType,true).first();
21119     },
21120     hiddenEl: function ()
21121     {
21122         return this.el.select('input.roo-hidden-value',true).first();
21123     },
21124     
21125     labelEl: function()
21126     {
21127         return this.el.select('label.control-label',true).first();
21128     },
21129     /* depricated... */
21130     
21131     label: function()
21132     {
21133         return this.labelEl();
21134     },
21135     
21136     boxLabelEl: function()
21137     {
21138         return this.el.select('label.box-label',true).first();
21139     },
21140     
21141     initEvents : function()
21142     {
21143 //        Roo.bootstrap.CheckBox.superclass.initEvents.call(this);
21144         
21145         this.inputEl().on('click', this.onClick,  this);
21146         
21147         if (this.boxLabel) { 
21148             this.el.select('label.box-label',true).first().on('click', this.onClick,  this);
21149         }
21150         
21151         this.startValue = this.getValue();
21152         
21153         if(this.groupId){
21154             Roo.bootstrap.CheckBox.register(this);
21155         }
21156     },
21157     
21158     onClick : function(e)
21159     {   
21160         if(this.fireEvent('click', this, e) !== false){
21161             this.setChecked(!this.checked);
21162         }
21163         
21164     },
21165     
21166     setChecked : function(state,suppressEvent)
21167     {
21168         this.startValue = this.getValue();
21169
21170         if(this.inputType == 'radio'){
21171             
21172             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
21173                 e.dom.checked = false;
21174             });
21175             
21176             this.inputEl().dom.checked = true;
21177             
21178             this.inputEl().dom.value = this.inputValue;
21179             
21180             if(suppressEvent !== true){
21181                 this.fireEvent('check', this, true);
21182             }
21183             
21184             this.validate();
21185             
21186             return;
21187         }
21188         
21189         this.checked = state;
21190         
21191         this.inputEl().dom.checked = state;
21192         
21193         
21194         this.hiddenEl().dom.value = state ? this.inputValue : this.valueOff;
21195         
21196         if(suppressEvent !== true){
21197             this.fireEvent('check', this, state);
21198         }
21199         
21200         this.validate();
21201     },
21202     
21203     getValue : function()
21204     {
21205         if(this.inputType == 'radio'){
21206             return this.getGroupValue();
21207         }
21208         
21209         return this.hiddenEl().dom.value;
21210         
21211     },
21212     
21213     getGroupValue : function()
21214     {
21215         if(typeof(this.el.up('form').child('input[name='+this.name+']:checked', true)) == 'undefined'){
21216             return '';
21217         }
21218         
21219         return this.el.up('form').child('input[name='+this.name+']:checked', true).value;
21220     },
21221     
21222     setValue : function(v,suppressEvent)
21223     {
21224         if(this.inputType == 'radio'){
21225             this.setGroupValue(v, suppressEvent);
21226             return;
21227         }
21228         
21229         this.setChecked(((typeof(v) == 'undefined') ? this.checked : (String(v) === String(this.inputValue))), suppressEvent);
21230         
21231         this.validate();
21232     },
21233     
21234     setGroupValue : function(v, suppressEvent)
21235     {
21236         this.startValue = this.getValue();
21237         
21238         Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
21239             e.dom.checked = false;
21240             
21241             if(e.dom.value == v){
21242                 e.dom.checked = true;
21243             }
21244         });
21245         
21246         if(suppressEvent !== true){
21247             this.fireEvent('check', this, true);
21248         }
21249
21250         this.validate();
21251         
21252         return;
21253     },
21254     
21255     validate : function()
21256     {
21257         if(this.getVisibilityEl().hasClass('hidden')){
21258             return true;
21259         }
21260         
21261         if(
21262                 this.disabled || 
21263                 (this.inputType == 'radio' && this.validateRadio()) ||
21264                 (this.inputType == 'checkbox' && this.validateCheckbox())
21265         ){
21266             this.markValid();
21267             return true;
21268         }
21269         
21270         this.markInvalid();
21271         return false;
21272     },
21273     
21274     validateRadio : function()
21275     {
21276         if(this.getVisibilityEl().hasClass('hidden')){
21277             return true;
21278         }
21279         
21280         if(this.allowBlank){
21281             return true;
21282         }
21283         
21284         var valid = false;
21285         
21286         Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
21287             if(!e.dom.checked){
21288                 return;
21289             }
21290             
21291             valid = true;
21292             
21293             return false;
21294         });
21295         
21296         return valid;
21297     },
21298     
21299     validateCheckbox : function()
21300     {
21301         if(!this.groupId){
21302             return (this.getValue() == this.inputValue || this.allowBlank) ? true : false;
21303             //return (this.getValue() == this.inputValue) ? true : false;
21304         }
21305         
21306         var group = Roo.bootstrap.CheckBox.get(this.groupId);
21307         
21308         if(!group){
21309             return false;
21310         }
21311         
21312         var r = false;
21313         
21314         for(var i in group){
21315             if(group[i].el.isVisible(true)){
21316                 r = false;
21317                 break;
21318             }
21319             
21320             r = true;
21321         }
21322         
21323         for(var i in group){
21324             if(r){
21325                 break;
21326             }
21327             
21328             r = (group[i].getValue() == group[i].inputValue) ? true : false;
21329         }
21330         
21331         return r;
21332     },
21333     
21334     /**
21335      * Mark this field as valid
21336      */
21337     markValid : function()
21338     {
21339         var _this = this;
21340         
21341         this.fireEvent('valid', this);
21342         
21343         var label = Roo.bootstrap.FieldLabel.get(this.name + '-group');
21344         
21345         if(this.groupId){
21346             label = Roo.bootstrap.FieldLabel.get(this.groupId + '-group');
21347         }
21348         
21349         if(label){
21350             label.markValid();
21351         }
21352
21353         if(this.inputType == 'radio'){
21354             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
21355                 var fg = e.findParent('.form-group', false, true);
21356                 if (Roo.bootstrap.version == 3) {
21357                     fg.removeClass([_this.invalidClass, _this.validClass]);
21358                     fg.addClass(_this.validClass);
21359                 } else {
21360                     fg.removeClass(['is-valid', 'is-invalid']);
21361                     fg.addClass('is-valid');
21362                 }
21363             });
21364             
21365             return;
21366         }
21367
21368         if(!this.groupId){
21369             var fg = this.el.findParent('.form-group', false, true);
21370             if (Roo.bootstrap.version == 3) {
21371                 fg.removeClass([this.invalidClass, this.validClass]);
21372                 fg.addClass(this.validClass);
21373             } else {
21374                 fg.removeClass(['is-valid', 'is-invalid']);
21375                 fg.addClass('is-valid');
21376             }
21377             return;
21378         }
21379         
21380         var group = Roo.bootstrap.CheckBox.get(this.groupId);
21381         
21382         if(!group){
21383             return;
21384         }
21385         
21386         for(var i in group){
21387             var fg = group[i].el.findParent('.form-group', false, true);
21388             if (Roo.bootstrap.version == 3) {
21389                 fg.removeClass([this.invalidClass, this.validClass]);
21390                 fg.addClass(this.validClass);
21391             } else {
21392                 fg.removeClass(['is-valid', 'is-invalid']);
21393                 fg.addClass('is-valid');
21394             }
21395         }
21396     },
21397     
21398      /**
21399      * Mark this field as invalid
21400      * @param {String} msg The validation message
21401      */
21402     markInvalid : function(msg)
21403     {
21404         if(this.allowBlank){
21405             return;
21406         }
21407         
21408         var _this = this;
21409         
21410         this.fireEvent('invalid', this, msg);
21411         
21412         var label = Roo.bootstrap.FieldLabel.get(this.name + '-group');
21413         
21414         if(this.groupId){
21415             label = Roo.bootstrap.FieldLabel.get(this.groupId + '-group');
21416         }
21417         
21418         if(label){
21419             label.markInvalid();
21420         }
21421             
21422         if(this.inputType == 'radio'){
21423             
21424             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
21425                 var fg = e.findParent('.form-group', false, true);
21426                 if (Roo.bootstrap.version == 3) {
21427                     fg.removeClass([_this.invalidClass, _this.validClass]);
21428                     fg.addClass(_this.invalidClass);
21429                 } else {
21430                     fg.removeClass(['is-invalid', 'is-valid']);
21431                     fg.addClass('is-invalid');
21432                 }
21433             });
21434             
21435             return;
21436         }
21437         
21438         if(!this.groupId){
21439             var fg = this.el.findParent('.form-group', false, true);
21440             if (Roo.bootstrap.version == 3) {
21441                 fg.removeClass([_this.invalidClass, _this.validClass]);
21442                 fg.addClass(_this.invalidClass);
21443             } else {
21444                 fg.removeClass(['is-invalid', 'is-valid']);
21445                 fg.addClass('is-invalid');
21446             }
21447             return;
21448         }
21449         
21450         var group = Roo.bootstrap.CheckBox.get(this.groupId);
21451         
21452         if(!group){
21453             return;
21454         }
21455         
21456         for(var i in group){
21457             var fg = group[i].el.findParent('.form-group', false, true);
21458             if (Roo.bootstrap.version == 3) {
21459                 fg.removeClass([_this.invalidClass, _this.validClass]);
21460                 fg.addClass(_this.invalidClass);
21461             } else {
21462                 fg.removeClass(['is-invalid', 'is-valid']);
21463                 fg.addClass('is-invalid');
21464             }
21465         }
21466         
21467     },
21468     
21469     clearInvalid : function()
21470     {
21471         Roo.bootstrap.Input.prototype.clearInvalid.call(this);
21472         
21473         // this.el.findParent('.form-group', false, true).removeClass([this.invalidClass, this.validClass]);
21474         
21475         var label = Roo.bootstrap.FieldLabel.get(this.name + '-group');
21476         
21477         if (label && label.iconEl) {
21478             label.iconEl.removeClass([ label.validClass, label.invalidClass ]);
21479             label.iconEl.removeClass(['is-invalid', 'is-valid']);
21480         }
21481     },
21482     
21483     disable : function()
21484     {
21485         if(this.inputType != 'radio'){
21486             Roo.bootstrap.CheckBox.superclass.disable.call(this);
21487             return;
21488         }
21489         
21490         var _this = this;
21491         
21492         if(this.rendered){
21493             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
21494                 _this.getActionEl().addClass(this.disabledClass);
21495                 e.dom.disabled = true;
21496             });
21497         }
21498         
21499         this.disabled = true;
21500         this.fireEvent("disable", this);
21501         return this;
21502     },
21503
21504     enable : function()
21505     {
21506         if(this.inputType != 'radio'){
21507             Roo.bootstrap.CheckBox.superclass.enable.call(this);
21508             return;
21509         }
21510         
21511         var _this = this;
21512         
21513         if(this.rendered){
21514             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
21515                 _this.getActionEl().removeClass(this.disabledClass);
21516                 e.dom.disabled = false;
21517             });
21518         }
21519         
21520         this.disabled = false;
21521         this.fireEvent("enable", this);
21522         return this;
21523     },
21524     
21525     setBoxLabel : function(v)
21526     {
21527         this.boxLabel = v;
21528         
21529         if(this.rendered){
21530             this.el.select('label.box-label',true).first().dom.innerHTML = (v === null || v === undefined ? '' : v);
21531         }
21532     }
21533
21534 });
21535
21536 Roo.apply(Roo.bootstrap.CheckBox, {
21537     
21538     groups: {},
21539     
21540      /**
21541     * register a CheckBox Group
21542     * @param {Roo.bootstrap.CheckBox} the CheckBox to add
21543     */
21544     register : function(checkbox)
21545     {
21546         if(typeof(this.groups[checkbox.groupId]) == 'undefined'){
21547             this.groups[checkbox.groupId] = {};
21548         }
21549         
21550         if(this.groups[checkbox.groupId].hasOwnProperty(checkbox.name)){
21551             return;
21552         }
21553         
21554         this.groups[checkbox.groupId][checkbox.name] = checkbox;
21555         
21556     },
21557     /**
21558     * fetch a CheckBox Group based on the group ID
21559     * @param {string} the group ID
21560     * @returns {Roo.bootstrap.CheckBox} the CheckBox group
21561     */
21562     get: function(groupId) {
21563         if (typeof(this.groups[groupId]) == 'undefined') {
21564             return false;
21565         }
21566         
21567         return this.groups[groupId] ;
21568     }
21569     
21570     
21571 });
21572 /*
21573  * - LGPL
21574  *
21575  * RadioItem
21576  * 
21577  */
21578
21579 /**
21580  * @class Roo.bootstrap.Radio
21581  * @extends Roo.bootstrap.Component
21582  * Bootstrap Radio class
21583  * @cfg {String} boxLabel - the label associated
21584  * @cfg {String} value - the value of radio
21585  * 
21586  * @constructor
21587  * Create a new Radio
21588  * @param {Object} config The config object
21589  */
21590 Roo.bootstrap.Radio = function(config){
21591     Roo.bootstrap.Radio.superclass.constructor.call(this, config);
21592     
21593 };
21594
21595 Roo.extend(Roo.bootstrap.Radio, Roo.bootstrap.Component, {
21596     
21597     boxLabel : '',
21598     
21599     value : '',
21600     
21601     getAutoCreate : function()
21602     {
21603         var cfg = {
21604             tag : 'div',
21605             cls : 'form-group radio',
21606             cn : [
21607                 {
21608                     tag : 'label',
21609                     cls : 'box-label',
21610                     html : this.boxLabel
21611                 }
21612             ]
21613         };
21614         
21615         return cfg;
21616     },
21617     
21618     initEvents : function() 
21619     {
21620         this.parent().register(this);
21621         
21622         this.el.on('click', this.onClick, this);
21623         
21624     },
21625     
21626     onClick : function(e)
21627     {
21628         if(this.parent().fireEvent('click', this.parent(), this, e) !== false){
21629             this.setChecked(true);
21630         }
21631     },
21632     
21633     setChecked : function(state, suppressEvent)
21634     {
21635         this.parent().setValue(this.value, suppressEvent);
21636         
21637     },
21638     
21639     setBoxLabel : function(v)
21640     {
21641         this.boxLabel = v;
21642         
21643         if(this.rendered){
21644             this.el.select('label.box-label',true).first().dom.innerHTML = (v === null || v === undefined ? '' : v);
21645         }
21646     }
21647     
21648 });
21649  
21650
21651  /*
21652  * - LGPL
21653  *
21654  * Input
21655  * 
21656  */
21657
21658 /**
21659  * @class Roo.bootstrap.SecurePass
21660  * @extends Roo.bootstrap.Input
21661  * Bootstrap SecurePass class
21662  *
21663  * 
21664  * @constructor
21665  * Create a new SecurePass
21666  * @param {Object} config The config object
21667  */
21668  
21669 Roo.bootstrap.SecurePass = function (config) {
21670     // these go here, so the translation tool can replace them..
21671     this.errors = {
21672         PwdEmpty: "Please type a password, and then retype it to confirm.",
21673         PwdShort: "Your password must be at least 6 characters long. Please type a different password.",
21674         PwdLong: "Your password can't contain more than 16 characters. Please type a different password.",
21675         PwdBadChar: "The password contains characters that aren't allowed. Please type a different password.",
21676         IDInPwd: "Your password can't include the part of your ID. Please type a different password.",
21677         FNInPwd: "Your password can't contain your first name. Please type a different password.",
21678         LNInPwd: "Your password can't contain your last name. Please type a different password.",
21679         TooWeak: "Your password is Too Weak."
21680     },
21681     this.meterLabel = "Password strength:";
21682     this.pwdStrengths = ["Too Weak", "Weak", "Medium", "Strong"];
21683     this.meterClass = [
21684         "roo-password-meter-tooweak", 
21685         "roo-password-meter-weak", 
21686         "roo-password-meter-medium", 
21687         "roo-password-meter-strong", 
21688         "roo-password-meter-grey"
21689     ];
21690     
21691     this.errors = {};
21692     
21693     Roo.bootstrap.SecurePass.superclass.constructor.call(this, config);
21694 }
21695
21696 Roo.extend(Roo.bootstrap.SecurePass, Roo.bootstrap.Input, {
21697     /**
21698      * @cfg {String/Object} errors A Error spec, or true for a default spec (defaults to
21699      * {
21700      *  PwdEmpty: "Please type a password, and then retype it to confirm.",
21701      *  PwdShort: "Your password must be at least 6 characters long. Please type a different password.",
21702      *  PwdLong: "Your password can't contain more than 16 characters. Please type a different password.",
21703      *  PwdBadChar: "The password contains characters that aren't allowed. Please type a different password.",
21704      *  IDInPwd: "Your password can't include the part of your ID. Please type a different password.",
21705      *  FNInPwd: "Your password can't contain your first name. Please type a different password.",
21706      *  LNInPwd: "Your password can't contain your last name. Please type a different password."
21707      * })
21708      */
21709     // private
21710     
21711     meterWidth: 300,
21712     errorMsg :'',    
21713     errors: false,
21714     imageRoot: '/',
21715     /**
21716      * @cfg {String/Object} Label for the strength meter (defaults to
21717      * 'Password strength:')
21718      */
21719     // private
21720     meterLabel: '',
21721     /**
21722      * @cfg {String/Object} pwdStrengths A pwdStrengths spec, or true for a default spec (defaults to
21723      * ['Weak', 'Medium', 'Strong'])
21724      */
21725     // private    
21726     pwdStrengths: false,    
21727     // private
21728     strength: 0,
21729     // private
21730     _lastPwd: null,
21731     // private
21732     kCapitalLetter: 0,
21733     kSmallLetter: 1,
21734     kDigit: 2,
21735     kPunctuation: 3,
21736     
21737     insecure: false,
21738     // private
21739     initEvents: function ()
21740     {
21741         Roo.bootstrap.SecurePass.superclass.initEvents.call(this);
21742
21743         if (this.el.is('input[type=password]') && Roo.isSafari) {
21744             this.el.on('keydown', this.SafariOnKeyDown, this);
21745         }
21746
21747         this.el.on('keyup', this.checkStrength, this, {buffer: 50});
21748     },
21749     // private
21750     onRender: function (ct, position)
21751     {
21752         Roo.bootstrap.SecurePass.superclass.onRender.call(this, ct, position);
21753         this.wrap = this.el.wrap({cls: 'x-form-field-wrap'});
21754         this.trigger = this.wrap.createChild({tag: 'div', cls: 'StrengthMeter ' + this.triggerClass});
21755
21756         this.trigger.createChild({
21757                    cn: [
21758                     {
21759                     //id: 'PwdMeter',
21760                     tag: 'div',
21761                     cls: 'roo-password-meter-grey col-xs-12',
21762                     style: {
21763                         //width: 0,
21764                         //width: this.meterWidth + 'px'                                                
21765                         }
21766                     },
21767                     {                            
21768                          cls: 'roo-password-meter-text'                          
21769                     }
21770                 ]            
21771         });
21772
21773          
21774         if (this.hideTrigger) {
21775             this.trigger.setDisplayed(false);
21776         }
21777         this.setSize(this.width || '', this.height || '');
21778     },
21779     // private
21780     onDestroy: function ()
21781     {
21782         if (this.trigger) {
21783             this.trigger.removeAllListeners();
21784             this.trigger.remove();
21785         }
21786         if (this.wrap) {
21787             this.wrap.remove();
21788         }
21789         Roo.bootstrap.TriggerField.superclass.onDestroy.call(this);
21790     },
21791     // private
21792     checkStrength: function ()
21793     {
21794         var pwd = this.inputEl().getValue();
21795         if (pwd == this._lastPwd) {
21796             return;
21797         }
21798
21799         var strength;
21800         if (this.ClientSideStrongPassword(pwd)) {
21801             strength = 3;
21802         } else if (this.ClientSideMediumPassword(pwd)) {
21803             strength = 2;
21804         } else if (this.ClientSideWeakPassword(pwd)) {
21805             strength = 1;
21806         } else {
21807             strength = 0;
21808         }
21809         
21810         Roo.log('strength1: ' + strength);
21811         
21812         //var pm = this.trigger.child('div/div/div').dom;
21813         var pm = this.trigger.child('div/div');
21814         pm.removeClass(this.meterClass);
21815         pm.addClass(this.meterClass[strength]);
21816                 
21817         
21818         var pt = this.trigger.child('/div').child('>*[class=roo-password-meter-text]').dom;        
21819                 
21820         pt.innerHTML = this.meterLabel + '&nbsp;' + this.pwdStrengths[strength];
21821         
21822         this._lastPwd = pwd;
21823     },
21824     reset: function ()
21825     {
21826         Roo.bootstrap.SecurePass.superclass.reset.call(this);
21827         
21828         this._lastPwd = '';
21829         
21830         var pm = this.trigger.child('div/div');
21831         pm.removeClass(this.meterClass);
21832         pm.addClass('roo-password-meter-grey');        
21833         
21834         
21835         var pt = this.trigger.child('/div').child('>*[class=roo-password-meter-text]').dom;        
21836         
21837         pt.innerHTML = '';
21838         this.inputEl().dom.type='password';
21839     },
21840     // private
21841     validateValue: function (value)
21842     {
21843         
21844         if (!Roo.bootstrap.SecurePass.superclass.validateValue.call(this, value)) {
21845             return false;
21846         }
21847         if (value.length == 0) {
21848             if (this.allowBlank) {
21849                 this.clearInvalid();
21850                 return true;
21851             }
21852
21853             this.markInvalid(this.errors.PwdEmpty);
21854             this.errorMsg = this.errors.PwdEmpty;
21855             return false;
21856         }
21857         
21858         if(this.insecure){
21859             return true;
21860         }
21861         
21862         if ('[\x21-\x7e]*'.match(value)) {
21863             this.markInvalid(this.errors.PwdBadChar);
21864             this.errorMsg = this.errors.PwdBadChar;
21865             return false;
21866         }
21867         if (value.length < 6) {
21868             this.markInvalid(this.errors.PwdShort);
21869             this.errorMsg = this.errors.PwdShort;
21870             return false;
21871         }
21872         if (value.length > 16) {
21873             this.markInvalid(this.errors.PwdLong);
21874             this.errorMsg = this.errors.PwdLong;
21875             return false;
21876         }
21877         var strength;
21878         if (this.ClientSideStrongPassword(value)) {
21879             strength = 3;
21880         } else if (this.ClientSideMediumPassword(value)) {
21881             strength = 2;
21882         } else if (this.ClientSideWeakPassword(value)) {
21883             strength = 1;
21884         } else {
21885             strength = 0;
21886         }
21887
21888         
21889         if (strength < 2) {
21890             //this.markInvalid(this.errors.TooWeak);
21891             this.errorMsg = this.errors.TooWeak;
21892             //return false;
21893         }
21894         
21895         
21896         console.log('strength2: ' + strength);
21897         
21898         //var pm = this.trigger.child('div/div/div').dom;
21899         
21900         var pm = this.trigger.child('div/div');
21901         pm.removeClass(this.meterClass);
21902         pm.addClass(this.meterClass[strength]);
21903                 
21904         var pt = this.trigger.child('/div').child('>*[class=roo-password-meter-text]').dom;        
21905                 
21906         pt.innerHTML = this.meterLabel + '&nbsp;' + this.pwdStrengths[strength];
21907         
21908         this.errorMsg = ''; 
21909         return true;
21910     },
21911     // private
21912     CharacterSetChecks: function (type)
21913     {
21914         this.type = type;
21915         this.fResult = false;
21916     },
21917     // private
21918     isctype: function (character, type)
21919     {
21920         switch (type) {  
21921             case this.kCapitalLetter:
21922                 if (character >= 'A' && character <= 'Z') {
21923                     return true;
21924                 }
21925                 break;
21926             
21927             case this.kSmallLetter:
21928                 if (character >= 'a' && character <= 'z') {
21929                     return true;
21930                 }
21931                 break;
21932             
21933             case this.kDigit:
21934                 if (character >= '0' && character <= '9') {
21935                     return true;
21936                 }
21937                 break;
21938             
21939             case this.kPunctuation:
21940                 if ('!@#$%^&*()_+-=\'";:[{]}|.>,</?`~'.indexOf(character) >= 0) {
21941                     return true;
21942                 }
21943                 break;
21944             
21945             default:
21946                 return false;
21947         }
21948
21949     },
21950     // private
21951     IsLongEnough: function (pwd, size)
21952     {
21953         return !(pwd == null || isNaN(size) || pwd.length < size);
21954     },
21955     // private
21956     SpansEnoughCharacterSets: function (word, nb)
21957     {
21958         if (!this.IsLongEnough(word, nb))
21959         {
21960             return false;
21961         }
21962
21963         var characterSetChecks = new Array(
21964             new this.CharacterSetChecks(this.kCapitalLetter), new this.CharacterSetChecks(this.kSmallLetter),
21965             new this.CharacterSetChecks(this.kDigit), new this.CharacterSetChecks(this.kPunctuation)
21966         );
21967         
21968         for (var index = 0; index < word.length; ++index) {
21969             for (var nCharSet = 0; nCharSet < characterSetChecks.length; ++nCharSet) {
21970                 if (!characterSetChecks[nCharSet].fResult && this.isctype(word.charAt(index), characterSetChecks[nCharSet].type)) {
21971                     characterSetChecks[nCharSet].fResult = true;
21972                     break;
21973                 }
21974             }
21975         }
21976
21977         var nCharSets = 0;
21978         for (var nCharSet = 0; nCharSet < characterSetChecks.length; ++nCharSet) {
21979             if (characterSetChecks[nCharSet].fResult) {
21980                 ++nCharSets;
21981             }
21982         }
21983
21984         if (nCharSets < nb) {
21985             return false;
21986         }
21987         return true;
21988     },
21989     // private
21990     ClientSideStrongPassword: function (pwd)
21991     {
21992         return this.IsLongEnough(pwd, 8) && this.SpansEnoughCharacterSets(pwd, 3);
21993     },
21994     // private
21995     ClientSideMediumPassword: function (pwd)
21996     {
21997         return this.IsLongEnough(pwd, 7) && this.SpansEnoughCharacterSets(pwd, 2);
21998     },
21999     // private
22000     ClientSideWeakPassword: function (pwd)
22001     {
22002         return this.IsLongEnough(pwd, 6) || !this.IsLongEnough(pwd, 0);
22003     }
22004           
22005 })//<script type="text/javascript">
22006
22007 /*
22008  * Based  Ext JS Library 1.1.1
22009  * Copyright(c) 2006-2007, Ext JS, LLC.
22010  * LGPL
22011  *
22012  */
22013  
22014 /**
22015  * @class Roo.HtmlEditorCore
22016  * @extends Roo.Component
22017  * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
22018  *
22019  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
22020  */
22021
22022 Roo.HtmlEditorCore = function(config){
22023     
22024     
22025     Roo.HtmlEditorCore.superclass.constructor.call(this, config);
22026     
22027     
22028     this.addEvents({
22029         /**
22030          * @event initialize
22031          * Fires when the editor is fully initialized (including the iframe)
22032          * @param {Roo.HtmlEditorCore} this
22033          */
22034         initialize: true,
22035         /**
22036          * @event activate
22037          * Fires when the editor is first receives the focus. Any insertion must wait
22038          * until after this event.
22039          * @param {Roo.HtmlEditorCore} this
22040          */
22041         activate: true,
22042          /**
22043          * @event beforesync
22044          * Fires before the textarea is updated with content from the editor iframe. Return false
22045          * to cancel the sync.
22046          * @param {Roo.HtmlEditorCore} this
22047          * @param {String} html
22048          */
22049         beforesync: true,
22050          /**
22051          * @event beforepush
22052          * Fires before the iframe editor is updated with content from the textarea. Return false
22053          * to cancel the push.
22054          * @param {Roo.HtmlEditorCore} this
22055          * @param {String} html
22056          */
22057         beforepush: true,
22058          /**
22059          * @event sync
22060          * Fires when the textarea is updated with content from the editor iframe.
22061          * @param {Roo.HtmlEditorCore} this
22062          * @param {String} html
22063          */
22064         sync: true,
22065          /**
22066          * @event push
22067          * Fires when the iframe editor is updated with content from the textarea.
22068          * @param {Roo.HtmlEditorCore} this
22069          * @param {String} html
22070          */
22071         push: true,
22072         
22073         /**
22074          * @event editorevent
22075          * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
22076          * @param {Roo.HtmlEditorCore} this
22077          */
22078         editorevent: true
22079         
22080     });
22081     
22082     // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
22083     
22084     // defaults : white / black...
22085     this.applyBlacklists();
22086     
22087     
22088     
22089 };
22090
22091
22092 Roo.extend(Roo.HtmlEditorCore, Roo.Component,  {
22093
22094
22095      /**
22096      * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field 
22097      */
22098     
22099     owner : false,
22100     
22101      /**
22102      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
22103      *                        Roo.resizable.
22104      */
22105     resizable : false,
22106      /**
22107      * @cfg {Number} height (in pixels)
22108      */   
22109     height: 300,
22110    /**
22111      * @cfg {Number} width (in pixels)
22112      */   
22113     width: 500,
22114     
22115     /**
22116      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
22117      * 
22118      */
22119     stylesheets: false,
22120     
22121     // id of frame..
22122     frameId: false,
22123     
22124     // private properties
22125     validationEvent : false,
22126     deferHeight: true,
22127     initialized : false,
22128     activated : false,
22129     sourceEditMode : false,
22130     onFocus : Roo.emptyFn,
22131     iframePad:3,
22132     hideMode:'offsets',
22133     
22134     clearUp: true,
22135     
22136     // blacklist + whitelisted elements..
22137     black: false,
22138     white: false,
22139      
22140     bodyCls : '',
22141
22142     /**
22143      * Protected method that will not generally be called directly. It
22144      * is called when the editor initializes the iframe with HTML contents. Override this method if you
22145      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
22146      */
22147     getDocMarkup : function(){
22148         // body styles..
22149         var st = '';
22150         
22151         // inherit styels from page...?? 
22152         if (this.stylesheets === false) {
22153             
22154             Roo.get(document.head).select('style').each(function(node) {
22155                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
22156             });
22157             
22158             Roo.get(document.head).select('link').each(function(node) { 
22159                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
22160             });
22161             
22162         } else if (!this.stylesheets.length) {
22163                 // simple..
22164                 st = '<style type="text/css">' +
22165                     'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
22166                    '</style>';
22167         } else { 
22168             st = '<style type="text/css">' +
22169                     this.stylesheets +
22170                 '</style>';
22171         }
22172         
22173         st +=  '<style type="text/css">' +
22174             'IMG { cursor: pointer } ' +
22175         '</style>';
22176
22177         var cls = 'roo-htmleditor-body';
22178         
22179         if(this.bodyCls.length){
22180             cls += ' ' + this.bodyCls;
22181         }
22182         
22183         return '<html><head>' + st  +
22184             //<style type="text/css">' +
22185             //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
22186             //'</style>' +
22187             ' </head><body class="' +  cls + '"></body></html>';
22188     },
22189
22190     // private
22191     onRender : function(ct, position)
22192     {
22193         var _t = this;
22194         //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
22195         this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
22196         
22197         
22198         this.el.dom.style.border = '0 none';
22199         this.el.dom.setAttribute('tabIndex', -1);
22200         this.el.addClass('x-hidden hide');
22201         
22202         
22203         
22204         if(Roo.isIE){ // fix IE 1px bogus margin
22205             this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
22206         }
22207        
22208         
22209         this.frameId = Roo.id();
22210         
22211          
22212         
22213         var iframe = this.owner.wrap.createChild({
22214             tag: 'iframe',
22215             cls: 'form-control', // bootstrap..
22216             id: this.frameId,
22217             name: this.frameId,
22218             frameBorder : 'no',
22219             'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL  :  "javascript:false"
22220         }, this.el
22221         );
22222         
22223         
22224         this.iframe = iframe.dom;
22225
22226          this.assignDocWin();
22227         
22228         this.doc.designMode = 'on';
22229        
22230         this.doc.open();
22231         this.doc.write(this.getDocMarkup());
22232         this.doc.close();
22233
22234         
22235         var task = { // must defer to wait for browser to be ready
22236             run : function(){
22237                 //console.log("run task?" + this.doc.readyState);
22238                 this.assignDocWin();
22239                 if(this.doc.body || this.doc.readyState == 'complete'){
22240                     try {
22241                         this.doc.designMode="on";
22242                     } catch (e) {
22243                         return;
22244                     }
22245                     Roo.TaskMgr.stop(task);
22246                     this.initEditor.defer(10, this);
22247                 }
22248             },
22249             interval : 10,
22250             duration: 10000,
22251             scope: this
22252         };
22253         Roo.TaskMgr.start(task);
22254
22255     },
22256
22257     // private
22258     onResize : function(w, h)
22259     {
22260          Roo.log('resize: ' +w + ',' + h );
22261         //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
22262         if(!this.iframe){
22263             return;
22264         }
22265         if(typeof w == 'number'){
22266             
22267             this.iframe.style.width = w + 'px';
22268         }
22269         if(typeof h == 'number'){
22270             
22271             this.iframe.style.height = h + 'px';
22272             if(this.doc){
22273                 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
22274             }
22275         }
22276         
22277     },
22278
22279     /**
22280      * Toggles the editor between standard and source edit mode.
22281      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
22282      */
22283     toggleSourceEdit : function(sourceEditMode){
22284         
22285         this.sourceEditMode = sourceEditMode === true;
22286         
22287         if(this.sourceEditMode){
22288  
22289             Roo.get(this.iframe).addClass(['x-hidden','hide']);     //FIXME - what's the BS styles for these
22290             
22291         }else{
22292             Roo.get(this.iframe).removeClass(['x-hidden','hide']);
22293             //this.iframe.className = '';
22294             this.deferFocus();
22295         }
22296         //this.setSize(this.owner.wrap.getSize());
22297         //this.fireEvent('editmodechange', this, this.sourceEditMode);
22298     },
22299
22300     
22301   
22302
22303     /**
22304      * Protected method that will not generally be called directly. If you need/want
22305      * custom HTML cleanup, this is the method you should override.
22306      * @param {String} html The HTML to be cleaned
22307      * return {String} The cleaned HTML
22308      */
22309     cleanHtml : function(html){
22310         html = String(html);
22311         if(html.length > 5){
22312             if(Roo.isSafari){ // strip safari nonsense
22313                 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
22314             }
22315         }
22316         if(html == '&nbsp;'){
22317             html = '';
22318         }
22319         return html;
22320     },
22321
22322     /**
22323      * HTML Editor -> Textarea
22324      * Protected method that will not generally be called directly. Syncs the contents
22325      * of the editor iframe with the textarea.
22326      */
22327     syncValue : function(){
22328         if(this.initialized){
22329             var bd = (this.doc.body || this.doc.documentElement);
22330             //this.cleanUpPaste(); -- this is done else where and causes havoc..
22331             var html = bd.innerHTML;
22332             if(Roo.isSafari){
22333                 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
22334                 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
22335                 if(m && m[1]){
22336                     html = '<div style="'+m[0]+'">' + html + '</div>';
22337                 }
22338             }
22339             html = this.cleanHtml(html);
22340             // fix up the special chars.. normaly like back quotes in word...
22341             // however we do not want to do this with chinese..
22342             html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
22343                 
22344                 var cc = match.charCodeAt();
22345
22346                 // Get the character value, handling surrogate pairs
22347                 if (match.length == 2) {
22348                     // It's a surrogate pair, calculate the Unicode code point
22349                     var high = match.charCodeAt(0) - 0xD800;
22350                     var low  = match.charCodeAt(1) - 0xDC00;
22351                     cc = (high * 0x400) + low + 0x10000;
22352                 }  else if (
22353                     (cc >= 0x4E00 && cc < 0xA000 ) ||
22354                     (cc >= 0x3400 && cc < 0x4E00 ) ||
22355                     (cc >= 0xf900 && cc < 0xfb00 )
22356                 ) {
22357                         return match;
22358                 }  
22359          
22360                 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
22361                 return "&#" + cc + ";";
22362                 
22363                 
22364             });
22365             
22366             
22367              
22368             if(this.owner.fireEvent('beforesync', this, html) !== false){
22369                 this.el.dom.value = html;
22370                 this.owner.fireEvent('sync', this, html);
22371             }
22372         }
22373     },
22374
22375     /**
22376      * Protected method that will not generally be called directly. Pushes the value of the textarea
22377      * into the iframe editor.
22378      */
22379     pushValue : function(){
22380         if(this.initialized){
22381             var v = this.el.dom.value.trim();
22382             
22383 //            if(v.length < 1){
22384 //                v = '&#160;';
22385 //            }
22386             
22387             if(this.owner.fireEvent('beforepush', this, v) !== false){
22388                 var d = (this.doc.body || this.doc.documentElement);
22389                 d.innerHTML = v;
22390                 this.cleanUpPaste();
22391                 this.el.dom.value = d.innerHTML;
22392                 this.owner.fireEvent('push', this, v);
22393             }
22394         }
22395     },
22396
22397     // private
22398     deferFocus : function(){
22399         this.focus.defer(10, this);
22400     },
22401
22402     // doc'ed in Field
22403     focus : function(){
22404         if(this.win && !this.sourceEditMode){
22405             this.win.focus();
22406         }else{
22407             this.el.focus();
22408         }
22409     },
22410     
22411     assignDocWin: function()
22412     {
22413         var iframe = this.iframe;
22414         
22415          if(Roo.isIE){
22416             this.doc = iframe.contentWindow.document;
22417             this.win = iframe.contentWindow;
22418         } else {
22419 //            if (!Roo.get(this.frameId)) {
22420 //                return;
22421 //            }
22422 //            this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
22423 //            this.win = Roo.get(this.frameId).dom.contentWindow;
22424             
22425             if (!Roo.get(this.frameId) && !iframe.contentDocument) {
22426                 return;
22427             }
22428             
22429             this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
22430             this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
22431         }
22432     },
22433     
22434     // private
22435     initEditor : function(){
22436         //console.log("INIT EDITOR");
22437         this.assignDocWin();
22438         
22439         
22440         
22441         this.doc.designMode="on";
22442         this.doc.open();
22443         this.doc.write(this.getDocMarkup());
22444         this.doc.close();
22445         
22446         var dbody = (this.doc.body || this.doc.documentElement);
22447         //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
22448         // this copies styles from the containing element into thsi one..
22449         // not sure why we need all of this..
22450         //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
22451         
22452         //var ss = this.el.getStyles( 'background-image', 'background-repeat');
22453         //ss['background-attachment'] = 'fixed'; // w3c
22454         dbody.bgProperties = 'fixed'; // ie
22455         //Roo.DomHelper.applyStyles(dbody, ss);
22456         Roo.EventManager.on(this.doc, {
22457             //'mousedown': this.onEditorEvent,
22458             'mouseup': this.onEditorEvent,
22459             'dblclick': this.onEditorEvent,
22460             'click': this.onEditorEvent,
22461             'keyup': this.onEditorEvent,
22462             buffer:100,
22463             scope: this
22464         });
22465         if(Roo.isGecko){
22466             Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
22467         }
22468         if(Roo.isIE || Roo.isSafari || Roo.isOpera){
22469             Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
22470         }
22471         this.initialized = true;
22472
22473         this.owner.fireEvent('initialize', this);
22474         this.pushValue();
22475     },
22476
22477     // private
22478     onDestroy : function(){
22479         
22480         
22481         
22482         if(this.rendered){
22483             
22484             //for (var i =0; i < this.toolbars.length;i++) {
22485             //    // fixme - ask toolbars for heights?
22486             //    this.toolbars[i].onDestroy();
22487            // }
22488             
22489             //this.wrap.dom.innerHTML = '';
22490             //this.wrap.remove();
22491         }
22492     },
22493
22494     // private
22495     onFirstFocus : function(){
22496         
22497         this.assignDocWin();
22498         
22499         
22500         this.activated = true;
22501          
22502     
22503         if(Roo.isGecko){ // prevent silly gecko errors
22504             this.win.focus();
22505             var s = this.win.getSelection();
22506             if(!s.focusNode || s.focusNode.nodeType != 3){
22507                 var r = s.getRangeAt(0);
22508                 r.selectNodeContents((this.doc.body || this.doc.documentElement));
22509                 r.collapse(true);
22510                 this.deferFocus();
22511             }
22512             try{
22513                 this.execCmd('useCSS', true);
22514                 this.execCmd('styleWithCSS', false);
22515             }catch(e){}
22516         }
22517         this.owner.fireEvent('activate', this);
22518     },
22519
22520     // private
22521     adjustFont: function(btn){
22522         var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
22523         //if(Roo.isSafari){ // safari
22524         //    adjust *= 2;
22525        // }
22526         var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
22527         if(Roo.isSafari){ // safari
22528             var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
22529             v =  (v < 10) ? 10 : v;
22530             v =  (v > 48) ? 48 : v;
22531             v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
22532             
22533         }
22534         
22535         
22536         v = Math.max(1, v+adjust);
22537         
22538         this.execCmd('FontSize', v  );
22539     },
22540
22541     onEditorEvent : function(e)
22542     {
22543         this.owner.fireEvent('editorevent', this, e);
22544       //  this.updateToolbar();
22545         this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
22546     },
22547
22548     insertTag : function(tg)
22549     {
22550         // could be a bit smarter... -> wrap the current selected tRoo..
22551         if (tg.toLowerCase() == 'span' ||
22552             tg.toLowerCase() == 'code' ||
22553             tg.toLowerCase() == 'sup' ||
22554             tg.toLowerCase() == 'sub' 
22555             ) {
22556             
22557             range = this.createRange(this.getSelection());
22558             var wrappingNode = this.doc.createElement(tg.toLowerCase());
22559             wrappingNode.appendChild(range.extractContents());
22560             range.insertNode(wrappingNode);
22561
22562             return;
22563             
22564             
22565             
22566         }
22567         this.execCmd("formatblock",   tg);
22568         
22569     },
22570     
22571     insertText : function(txt)
22572     {
22573         
22574         
22575         var range = this.createRange();
22576         range.deleteContents();
22577                //alert(Sender.getAttribute('label'));
22578                
22579         range.insertNode(this.doc.createTextNode(txt));
22580     } ,
22581     
22582      
22583
22584     /**
22585      * Executes a Midas editor command on the editor document and performs necessary focus and
22586      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
22587      * @param {String} cmd The Midas command
22588      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
22589      */
22590     relayCmd : function(cmd, value){
22591         this.win.focus();
22592         this.execCmd(cmd, value);
22593         this.owner.fireEvent('editorevent', this);
22594         //this.updateToolbar();
22595         this.owner.deferFocus();
22596     },
22597
22598     /**
22599      * Executes a Midas editor command directly on the editor document.
22600      * For visual commands, you should use {@link #relayCmd} instead.
22601      * <b>This should only be called after the editor is initialized.</b>
22602      * @param {String} cmd The Midas command
22603      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
22604      */
22605     execCmd : function(cmd, value){
22606         this.doc.execCommand(cmd, false, value === undefined ? null : value);
22607         this.syncValue();
22608     },
22609  
22610  
22611    
22612     /**
22613      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
22614      * to insert tRoo.
22615      * @param {String} text | dom node.. 
22616      */
22617     insertAtCursor : function(text)
22618     {
22619         
22620         if(!this.activated){
22621             return;
22622         }
22623         /*
22624         if(Roo.isIE){
22625             this.win.focus();
22626             var r = this.doc.selection.createRange();
22627             if(r){
22628                 r.collapse(true);
22629                 r.pasteHTML(text);
22630                 this.syncValue();
22631                 this.deferFocus();
22632             
22633             }
22634             return;
22635         }
22636         */
22637         if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
22638             this.win.focus();
22639             
22640             
22641             // from jquery ui (MIT licenced)
22642             var range, node;
22643             var win = this.win;
22644             
22645             if (win.getSelection && win.getSelection().getRangeAt) {
22646                 range = win.getSelection().getRangeAt(0);
22647                 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
22648                 range.insertNode(node);
22649             } else if (win.document.selection && win.document.selection.createRange) {
22650                 // no firefox support
22651                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
22652                 win.document.selection.createRange().pasteHTML(txt);
22653             } else {
22654                 // no firefox support
22655                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
22656                 this.execCmd('InsertHTML', txt);
22657             } 
22658             
22659             this.syncValue();
22660             
22661             this.deferFocus();
22662         }
22663     },
22664  // private
22665     mozKeyPress : function(e){
22666         if(e.ctrlKey){
22667             var c = e.getCharCode(), cmd;
22668           
22669             if(c > 0){
22670                 c = String.fromCharCode(c).toLowerCase();
22671                 switch(c){
22672                     case 'b':
22673                         cmd = 'bold';
22674                         break;
22675                     case 'i':
22676                         cmd = 'italic';
22677                         break;
22678                     
22679                     case 'u':
22680                         cmd = 'underline';
22681                         break;
22682                     
22683                     case 'v':
22684                         this.cleanUpPaste.defer(100, this);
22685                         return;
22686                         
22687                 }
22688                 if(cmd){
22689                     this.win.focus();
22690                     this.execCmd(cmd);
22691                     this.deferFocus();
22692                     e.preventDefault();
22693                 }
22694                 
22695             }
22696         }
22697     },
22698
22699     // private
22700     fixKeys : function(){ // load time branching for fastest keydown performance
22701         if(Roo.isIE){
22702             return function(e){
22703                 var k = e.getKey(), r;
22704                 if(k == e.TAB){
22705                     e.stopEvent();
22706                     r = this.doc.selection.createRange();
22707                     if(r){
22708                         r.collapse(true);
22709                         r.pasteHTML('&#160;&#160;&#160;&#160;');
22710                         this.deferFocus();
22711                     }
22712                     return;
22713                 }
22714                 
22715                 if(k == e.ENTER){
22716                     r = this.doc.selection.createRange();
22717                     if(r){
22718                         var target = r.parentElement();
22719                         if(!target || target.tagName.toLowerCase() != 'li'){
22720                             e.stopEvent();
22721                             r.pasteHTML('<br />');
22722                             r.collapse(false);
22723                             r.select();
22724                         }
22725                     }
22726                 }
22727                 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
22728                     this.cleanUpPaste.defer(100, this);
22729                     return;
22730                 }
22731                 
22732                 
22733             };
22734         }else if(Roo.isOpera){
22735             return function(e){
22736                 var k = e.getKey();
22737                 if(k == e.TAB){
22738                     e.stopEvent();
22739                     this.win.focus();
22740                     this.execCmd('InsertHTML','&#160;&#160;&#160;&#160;');
22741                     this.deferFocus();
22742                 }
22743                 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
22744                     this.cleanUpPaste.defer(100, this);
22745                     return;
22746                 }
22747                 
22748             };
22749         }else if(Roo.isSafari){
22750             return function(e){
22751                 var k = e.getKey();
22752                 
22753                 if(k == e.TAB){
22754                     e.stopEvent();
22755                     this.execCmd('InsertText','\t');
22756                     this.deferFocus();
22757                     return;
22758                 }
22759                if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
22760                     this.cleanUpPaste.defer(100, this);
22761                     return;
22762                 }
22763                 
22764              };
22765         }
22766     }(),
22767     
22768     getAllAncestors: function()
22769     {
22770         var p = this.getSelectedNode();
22771         var a = [];
22772         if (!p) {
22773             a.push(p); // push blank onto stack..
22774             p = this.getParentElement();
22775         }
22776         
22777         
22778         while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
22779             a.push(p);
22780             p = p.parentNode;
22781         }
22782         a.push(this.doc.body);
22783         return a;
22784     },
22785     lastSel : false,
22786     lastSelNode : false,
22787     
22788     
22789     getSelection : function() 
22790     {
22791         this.assignDocWin();
22792         return Roo.isIE ? this.doc.selection : this.win.getSelection();
22793     },
22794     
22795     getSelectedNode: function() 
22796     {
22797         // this may only work on Gecko!!!
22798         
22799         // should we cache this!!!!
22800         
22801         
22802         
22803          
22804         var range = this.createRange(this.getSelection()).cloneRange();
22805         
22806         if (Roo.isIE) {
22807             var parent = range.parentElement();
22808             while (true) {
22809                 var testRange = range.duplicate();
22810                 testRange.moveToElementText(parent);
22811                 if (testRange.inRange(range)) {
22812                     break;
22813                 }
22814                 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
22815                     break;
22816                 }
22817                 parent = parent.parentElement;
22818             }
22819             return parent;
22820         }
22821         
22822         // is ancestor a text element.
22823         var ac =  range.commonAncestorContainer;
22824         if (ac.nodeType == 3) {
22825             ac = ac.parentNode;
22826         }
22827         
22828         var ar = ac.childNodes;
22829          
22830         var nodes = [];
22831         var other_nodes = [];
22832         var has_other_nodes = false;
22833         for (var i=0;i<ar.length;i++) {
22834             if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ? 
22835                 continue;
22836             }
22837             // fullly contained node.
22838             
22839             if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
22840                 nodes.push(ar[i]);
22841                 continue;
22842             }
22843             
22844             // probably selected..
22845             if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
22846                 other_nodes.push(ar[i]);
22847                 continue;
22848             }
22849             // outer..
22850             if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0))  {
22851                 continue;
22852             }
22853             
22854             
22855             has_other_nodes = true;
22856         }
22857         if (!nodes.length && other_nodes.length) {
22858             nodes= other_nodes;
22859         }
22860         if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
22861             return false;
22862         }
22863         
22864         return nodes[0];
22865     },
22866     createRange: function(sel)
22867     {
22868         // this has strange effects when using with 
22869         // top toolbar - not sure if it's a great idea.
22870         //this.editor.contentWindow.focus();
22871         if (typeof sel != "undefined") {
22872             try {
22873                 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
22874             } catch(e) {
22875                 return this.doc.createRange();
22876             }
22877         } else {
22878             return this.doc.createRange();
22879         }
22880     },
22881     getParentElement: function()
22882     {
22883         
22884         this.assignDocWin();
22885         var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
22886         
22887         var range = this.createRange(sel);
22888          
22889         try {
22890             var p = range.commonAncestorContainer;
22891             while (p.nodeType == 3) { // text node
22892                 p = p.parentNode;
22893             }
22894             return p;
22895         } catch (e) {
22896             return null;
22897         }
22898     
22899     },
22900     /***
22901      *
22902      * Range intersection.. the hard stuff...
22903      *  '-1' = before
22904      *  '0' = hits..
22905      *  '1' = after.
22906      *         [ -- selected range --- ]
22907      *   [fail]                        [fail]
22908      *
22909      *    basically..
22910      *      if end is before start or  hits it. fail.
22911      *      if start is after end or hits it fail.
22912      *
22913      *   if either hits (but other is outside. - then it's not 
22914      *   
22915      *    
22916      **/
22917     
22918     
22919     // @see http://www.thismuchiknow.co.uk/?p=64.
22920     rangeIntersectsNode : function(range, node)
22921     {
22922         var nodeRange = node.ownerDocument.createRange();
22923         try {
22924             nodeRange.selectNode(node);
22925         } catch (e) {
22926             nodeRange.selectNodeContents(node);
22927         }
22928     
22929         var rangeStartRange = range.cloneRange();
22930         rangeStartRange.collapse(true);
22931     
22932         var rangeEndRange = range.cloneRange();
22933         rangeEndRange.collapse(false);
22934     
22935         var nodeStartRange = nodeRange.cloneRange();
22936         nodeStartRange.collapse(true);
22937     
22938         var nodeEndRange = nodeRange.cloneRange();
22939         nodeEndRange.collapse(false);
22940     
22941         return rangeStartRange.compareBoundaryPoints(
22942                  Range.START_TO_START, nodeEndRange) == -1 &&
22943                rangeEndRange.compareBoundaryPoints(
22944                  Range.START_TO_START, nodeStartRange) == 1;
22945         
22946          
22947     },
22948     rangeCompareNode : function(range, node)
22949     {
22950         var nodeRange = node.ownerDocument.createRange();
22951         try {
22952             nodeRange.selectNode(node);
22953         } catch (e) {
22954             nodeRange.selectNodeContents(node);
22955         }
22956         
22957         
22958         range.collapse(true);
22959     
22960         nodeRange.collapse(true);
22961      
22962         var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
22963         var ee = range.compareBoundaryPoints(  Range.END_TO_END, nodeRange);
22964          
22965         //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
22966         
22967         var nodeIsBefore   =  ss == 1;
22968         var nodeIsAfter    = ee == -1;
22969         
22970         if (nodeIsBefore && nodeIsAfter) {
22971             return 0; // outer
22972         }
22973         if (!nodeIsBefore && nodeIsAfter) {
22974             return 1; //right trailed.
22975         }
22976         
22977         if (nodeIsBefore && !nodeIsAfter) {
22978             return 2;  // left trailed.
22979         }
22980         // fully contined.
22981         return 3;
22982     },
22983
22984     // private? - in a new class?
22985     cleanUpPaste :  function()
22986     {
22987         // cleans up the whole document..
22988         Roo.log('cleanuppaste');
22989         
22990         this.cleanUpChildren(this.doc.body);
22991         var clean = this.cleanWordChars(this.doc.body.innerHTML);
22992         if (clean != this.doc.body.innerHTML) {
22993             this.doc.body.innerHTML = clean;
22994         }
22995         
22996     },
22997     
22998     cleanWordChars : function(input) {// change the chars to hex code
22999         var he = Roo.HtmlEditorCore;
23000         
23001         var output = input;
23002         Roo.each(he.swapCodes, function(sw) { 
23003             var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
23004             
23005             output = output.replace(swapper, sw[1]);
23006         });
23007         
23008         return output;
23009     },
23010     
23011     
23012     cleanUpChildren : function (n)
23013     {
23014         if (!n.childNodes.length) {
23015             return;
23016         }
23017         for (var i = n.childNodes.length-1; i > -1 ; i--) {
23018            this.cleanUpChild(n.childNodes[i]);
23019         }
23020     },
23021     
23022     
23023         
23024     
23025     cleanUpChild : function (node)
23026     {
23027         var ed = this;
23028         //console.log(node);
23029         if (node.nodeName == "#text") {
23030             // clean up silly Windows -- stuff?
23031             return; 
23032         }
23033         if (node.nodeName == "#comment") {
23034             node.parentNode.removeChild(node);
23035             // clean up silly Windows -- stuff?
23036             return; 
23037         }
23038         var lcname = node.tagName.toLowerCase();
23039         // we ignore whitelists... ?? = not really the way to go, but we probably have not got a full
23040         // whitelist of tags..
23041         
23042         if (this.black.indexOf(lcname) > -1 && this.clearUp ) {
23043             // remove node.
23044             node.parentNode.removeChild(node);
23045             return;
23046             
23047         }
23048         
23049         var remove_keep_children= Roo.HtmlEditorCore.remove.indexOf(node.tagName.toLowerCase()) > -1;
23050         
23051         // spans with no attributes - just remove them..
23052         if ((!node.attributes || !node.attributes.length) && lcname == 'span') { 
23053             remove_keep_children = true;
23054         }
23055         
23056         // remove <a name=....> as rendering on yahoo mailer is borked with this.
23057         // this will have to be flaged elsewhere - perhaps ablack=name... on the mailer..
23058         
23059         //if (node.tagName.toLowerCase() == 'a' && !node.hasAttribute('href')) {
23060         //    remove_keep_children = true;
23061         //}
23062         
23063         if (remove_keep_children) {
23064             this.cleanUpChildren(node);
23065             // inserts everything just before this node...
23066             while (node.childNodes.length) {
23067                 var cn = node.childNodes[0];
23068                 node.removeChild(cn);
23069                 node.parentNode.insertBefore(cn, node);
23070             }
23071             node.parentNode.removeChild(node);
23072             return;
23073         }
23074         
23075         if (!node.attributes || !node.attributes.length) {
23076             
23077           
23078             
23079             
23080             this.cleanUpChildren(node);
23081             return;
23082         }
23083         
23084         function cleanAttr(n,v)
23085         {
23086             
23087             if (v.match(/^\./) || v.match(/^\//)) {
23088                 return;
23089             }
23090             if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/) || v.match(/^ftp:/)) {
23091                 return;
23092             }
23093             if (v.match(/^#/)) {
23094                 return;
23095             }
23096 //            Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
23097             node.removeAttribute(n);
23098             
23099         }
23100         
23101         var cwhite = this.cwhite;
23102         var cblack = this.cblack;
23103             
23104         function cleanStyle(n,v)
23105         {
23106             if (v.match(/expression/)) { //XSS?? should we even bother..
23107                 node.removeAttribute(n);
23108                 return;
23109             }
23110             
23111             var parts = v.split(/;/);
23112             var clean = [];
23113             
23114             Roo.each(parts, function(p) {
23115                 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
23116                 if (!p.length) {
23117                     return true;
23118                 }
23119                 var l = p.split(':').shift().replace(/\s+/g,'');
23120                 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
23121                 
23122                 if ( cwhite.length && cblack.indexOf(l) > -1) {
23123 //                    Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
23124                     //node.removeAttribute(n);
23125                     return true;
23126                 }
23127                 //Roo.log()
23128                 // only allow 'c whitelisted system attributes'
23129                 if ( cwhite.length &&  cwhite.indexOf(l) < 0) {
23130 //                    Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
23131                     //node.removeAttribute(n);
23132                     return true;
23133                 }
23134                 
23135                 
23136                  
23137                 
23138                 clean.push(p);
23139                 return true;
23140             });
23141             if (clean.length) { 
23142                 node.setAttribute(n, clean.join(';'));
23143             } else {
23144                 node.removeAttribute(n);
23145             }
23146             
23147         }
23148         
23149         
23150         for (var i = node.attributes.length-1; i > -1 ; i--) {
23151             var a = node.attributes[i];
23152             //console.log(a);
23153             
23154             if (a.name.toLowerCase().substr(0,2)=='on')  {
23155                 node.removeAttribute(a.name);
23156                 continue;
23157             }
23158             if (Roo.HtmlEditorCore.ablack.indexOf(a.name.toLowerCase()) > -1) {
23159                 node.removeAttribute(a.name);
23160                 continue;
23161             }
23162             if (Roo.HtmlEditorCore.aclean.indexOf(a.name.toLowerCase()) > -1) {
23163                 cleanAttr(a.name,a.value); // fixme..
23164                 continue;
23165             }
23166             if (a.name == 'style') {
23167                 cleanStyle(a.name,a.value);
23168                 continue;
23169             }
23170             /// clean up MS crap..
23171             // tecnically this should be a list of valid class'es..
23172             
23173             
23174             if (a.name == 'class') {
23175                 if (a.value.match(/^Mso/)) {
23176                     node.removeAttribute('class');
23177                 }
23178                 
23179                 if (a.value.match(/^body$/)) {
23180                     node.removeAttribute('class');
23181                 }
23182                 continue;
23183             }
23184             
23185             // style cleanup!?
23186             // class cleanup?
23187             
23188         }
23189         
23190         
23191         this.cleanUpChildren(node);
23192         
23193         
23194     },
23195     
23196     /**
23197      * Clean up MS wordisms...
23198      */
23199     cleanWord : function(node)
23200     {
23201         if (!node) {
23202             this.cleanWord(this.doc.body);
23203             return;
23204         }
23205         
23206         if(
23207                 node.nodeName == 'SPAN' &&
23208                 !node.hasAttributes() &&
23209                 node.childNodes.length == 1 &&
23210                 node.firstChild.nodeName == "#text"  
23211         ) {
23212             var textNode = node.firstChild;
23213             node.removeChild(textNode);
23214             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
23215                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
23216             }
23217             node.parentNode.insertBefore(textNode, node);
23218             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
23219                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
23220             }
23221             node.parentNode.removeChild(node);
23222         }
23223         
23224         if (node.nodeName == "#text") {
23225             // clean up silly Windows -- stuff?
23226             return; 
23227         }
23228         if (node.nodeName == "#comment") {
23229             node.parentNode.removeChild(node);
23230             // clean up silly Windows -- stuff?
23231             return; 
23232         }
23233         
23234         if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
23235             node.parentNode.removeChild(node);
23236             return;
23237         }
23238         //Roo.log(node.tagName);
23239         // remove - but keep children..
23240         if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
23241             //Roo.log('-- removed');
23242             while (node.childNodes.length) {
23243                 var cn = node.childNodes[0];
23244                 node.removeChild(cn);
23245                 node.parentNode.insertBefore(cn, node);
23246                 // move node to parent - and clean it..
23247                 this.cleanWord(cn);
23248             }
23249             node.parentNode.removeChild(node);
23250             /// no need to iterate chidlren = it's got none..
23251             //this.iterateChildren(node, this.cleanWord);
23252             return;
23253         }
23254         // clean styles
23255         if (node.className.length) {
23256             
23257             var cn = node.className.split(/\W+/);
23258             var cna = [];
23259             Roo.each(cn, function(cls) {
23260                 if (cls.match(/Mso[a-zA-Z]+/)) {
23261                     return;
23262                 }
23263                 cna.push(cls);
23264             });
23265             node.className = cna.length ? cna.join(' ') : '';
23266             if (!cna.length) {
23267                 node.removeAttribute("class");
23268             }
23269         }
23270         
23271         if (node.hasAttribute("lang")) {
23272             node.removeAttribute("lang");
23273         }
23274         
23275         if (node.hasAttribute("style")) {
23276             
23277             var styles = node.getAttribute("style").split(";");
23278             var nstyle = [];
23279             Roo.each(styles, function(s) {
23280                 if (!s.match(/:/)) {
23281                     return;
23282                 }
23283                 var kv = s.split(":");
23284                 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
23285                     return;
23286                 }
23287                 // what ever is left... we allow.
23288                 nstyle.push(s);
23289             });
23290             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
23291             if (!nstyle.length) {
23292                 node.removeAttribute('style');
23293             }
23294         }
23295         this.iterateChildren(node, this.cleanWord);
23296         
23297         
23298         
23299     },
23300     /**
23301      * iterateChildren of a Node, calling fn each time, using this as the scole..
23302      * @param {DomNode} node node to iterate children of.
23303      * @param {Function} fn method of this class to call on each item.
23304      */
23305     iterateChildren : function(node, fn)
23306     {
23307         if (!node.childNodes.length) {
23308                 return;
23309         }
23310         for (var i = node.childNodes.length-1; i > -1 ; i--) {
23311            fn.call(this, node.childNodes[i])
23312         }
23313     },
23314     
23315     
23316     /**
23317      * cleanTableWidths.
23318      *
23319      * Quite often pasting from word etc.. results in tables with column and widths.
23320      * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
23321      *
23322      */
23323     cleanTableWidths : function(node)
23324     {
23325          
23326          
23327         if (!node) {
23328             this.cleanTableWidths(this.doc.body);
23329             return;
23330         }
23331         
23332         // ignore list...
23333         if (node.nodeName == "#text" || node.nodeName == "#comment") {
23334             return; 
23335         }
23336         Roo.log(node.tagName);
23337         if (!node.tagName.toLowerCase().match(/^(table|td|tr)$/)) {
23338             this.iterateChildren(node, this.cleanTableWidths);
23339             return;
23340         }
23341         if (node.hasAttribute('width')) {
23342             node.removeAttribute('width');
23343         }
23344         
23345          
23346         if (node.hasAttribute("style")) {
23347             // pretty basic...
23348             
23349             var styles = node.getAttribute("style").split(";");
23350             var nstyle = [];
23351             Roo.each(styles, function(s) {
23352                 if (!s.match(/:/)) {
23353                     return;
23354                 }
23355                 var kv = s.split(":");
23356                 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
23357                     return;
23358                 }
23359                 // what ever is left... we allow.
23360                 nstyle.push(s);
23361             });
23362             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
23363             if (!nstyle.length) {
23364                 node.removeAttribute('style');
23365             }
23366         }
23367         
23368         this.iterateChildren(node, this.cleanTableWidths);
23369         
23370         
23371     },
23372     
23373     
23374     
23375     
23376     domToHTML : function(currentElement, depth, nopadtext) {
23377         
23378         depth = depth || 0;
23379         nopadtext = nopadtext || false;
23380     
23381         if (!currentElement) {
23382             return this.domToHTML(this.doc.body);
23383         }
23384         
23385         //Roo.log(currentElement);
23386         var j;
23387         var allText = false;
23388         var nodeName = currentElement.nodeName;
23389         var tagName = Roo.util.Format.htmlEncode(currentElement.tagName);
23390         
23391         if  (nodeName == '#text') {
23392             
23393             return nopadtext ? currentElement.nodeValue : currentElement.nodeValue.trim();
23394         }
23395         
23396         
23397         var ret = '';
23398         if (nodeName != 'BODY') {
23399              
23400             var i = 0;
23401             // Prints the node tagName, such as <A>, <IMG>, etc
23402             if (tagName) {
23403                 var attr = [];
23404                 for(i = 0; i < currentElement.attributes.length;i++) {
23405                     // quoting?
23406                     var aname = currentElement.attributes.item(i).name;
23407                     if (!currentElement.attributes.item(i).value.length) {
23408                         continue;
23409                     }
23410                     attr.push(aname + '="' + Roo.util.Format.htmlEncode(currentElement.attributes.item(i).value) + '"' );
23411                 }
23412                 
23413                 ret = "<"+currentElement.tagName+ ( attr.length ? (' ' + attr.join(' ') ) : '') + ">";
23414             } 
23415             else {
23416                 
23417                 // eack
23418             }
23419         } else {
23420             tagName = false;
23421         }
23422         if (['IMG', 'BR', 'HR', 'INPUT'].indexOf(tagName) > -1) {
23423             return ret;
23424         }
23425         if (['PRE', 'TEXTAREA', 'TD', 'A', 'SPAN'].indexOf(tagName) > -1) { // or code?
23426             nopadtext = true;
23427         }
23428         
23429         
23430         // Traverse the tree
23431         i = 0;
23432         var currentElementChild = currentElement.childNodes.item(i);
23433         var allText = true;
23434         var innerHTML  = '';
23435         lastnode = '';
23436         while (currentElementChild) {
23437             // Formatting code (indent the tree so it looks nice on the screen)
23438             var nopad = nopadtext;
23439             if (lastnode == 'SPAN') {
23440                 nopad  = true;
23441             }
23442             // text
23443             if  (currentElementChild.nodeName == '#text') {
23444                 var toadd = Roo.util.Format.htmlEncode(currentElementChild.nodeValue);
23445                 toadd = nopadtext ? toadd : toadd.trim();
23446                 if (!nopad && toadd.length > 80) {
23447                     innerHTML  += "\n" + (new Array( depth + 1 )).join( "  "  );
23448                 }
23449                 innerHTML  += toadd;
23450                 
23451                 i++;
23452                 currentElementChild = currentElement.childNodes.item(i);
23453                 lastNode = '';
23454                 continue;
23455             }
23456             allText = false;
23457             
23458             innerHTML  += nopad ? '' : "\n" + (new Array( depth + 1 )).join( "  "  );
23459                 
23460             // Recursively traverse the tree structure of the child node
23461             innerHTML   += this.domToHTML(currentElementChild, depth+1, nopadtext);
23462             lastnode = currentElementChild.nodeName;
23463             i++;
23464             currentElementChild=currentElement.childNodes.item(i);
23465         }
23466         
23467         ret += innerHTML;
23468         
23469         if (!allText) {
23470                 // The remaining code is mostly for formatting the tree
23471             ret+= nopadtext ? '' : "\n" + (new Array( depth  )).join( "  "  );
23472         }
23473         
23474         
23475         if (tagName) {
23476             ret+= "</"+tagName+">";
23477         }
23478         return ret;
23479         
23480     },
23481         
23482     applyBlacklists : function()
23483     {
23484         var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white  : [];
23485         var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black :  [];
23486         
23487         this.white = [];
23488         this.black = [];
23489         Roo.each(Roo.HtmlEditorCore.white, function(tag) {
23490             if (b.indexOf(tag) > -1) {
23491                 return;
23492             }
23493             this.white.push(tag);
23494             
23495         }, this);
23496         
23497         Roo.each(w, function(tag) {
23498             if (b.indexOf(tag) > -1) {
23499                 return;
23500             }
23501             if (this.white.indexOf(tag) > -1) {
23502                 return;
23503             }
23504             this.white.push(tag);
23505             
23506         }, this);
23507         
23508         
23509         Roo.each(Roo.HtmlEditorCore.black, function(tag) {
23510             if (w.indexOf(tag) > -1) {
23511                 return;
23512             }
23513             this.black.push(tag);
23514             
23515         }, this);
23516         
23517         Roo.each(b, function(tag) {
23518             if (w.indexOf(tag) > -1) {
23519                 return;
23520             }
23521             if (this.black.indexOf(tag) > -1) {
23522                 return;
23523             }
23524             this.black.push(tag);
23525             
23526         }, this);
23527         
23528         
23529         w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite  : [];
23530         b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack :  [];
23531         
23532         this.cwhite = [];
23533         this.cblack = [];
23534         Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
23535             if (b.indexOf(tag) > -1) {
23536                 return;
23537             }
23538             this.cwhite.push(tag);
23539             
23540         }, this);
23541         
23542         Roo.each(w, function(tag) {
23543             if (b.indexOf(tag) > -1) {
23544                 return;
23545             }
23546             if (this.cwhite.indexOf(tag) > -1) {
23547                 return;
23548             }
23549             this.cwhite.push(tag);
23550             
23551         }, this);
23552         
23553         
23554         Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
23555             if (w.indexOf(tag) > -1) {
23556                 return;
23557             }
23558             this.cblack.push(tag);
23559             
23560         }, this);
23561         
23562         Roo.each(b, function(tag) {
23563             if (w.indexOf(tag) > -1) {
23564                 return;
23565             }
23566             if (this.cblack.indexOf(tag) > -1) {
23567                 return;
23568             }
23569             this.cblack.push(tag);
23570             
23571         }, this);
23572     },
23573     
23574     setStylesheets : function(stylesheets)
23575     {
23576         if(typeof(stylesheets) == 'string'){
23577             Roo.get(this.iframe.contentDocument.head).createChild({
23578                 tag : 'link',
23579                 rel : 'stylesheet',
23580                 type : 'text/css',
23581                 href : stylesheets
23582             });
23583             
23584             return;
23585         }
23586         var _this = this;
23587      
23588         Roo.each(stylesheets, function(s) {
23589             if(!s.length){
23590                 return;
23591             }
23592             
23593             Roo.get(_this.iframe.contentDocument.head).createChild({
23594                 tag : 'link',
23595                 rel : 'stylesheet',
23596                 type : 'text/css',
23597                 href : s
23598             });
23599         });
23600
23601         
23602     },
23603     
23604     removeStylesheets : function()
23605     {
23606         var _this = this;
23607         
23608         Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
23609             s.remove();
23610         });
23611     },
23612     
23613     setStyle : function(style)
23614     {
23615         Roo.get(this.iframe.contentDocument.head).createChild({
23616             tag : 'style',
23617             type : 'text/css',
23618             html : style
23619         });
23620
23621         return;
23622     }
23623     
23624     // hide stuff that is not compatible
23625     /**
23626      * @event blur
23627      * @hide
23628      */
23629     /**
23630      * @event change
23631      * @hide
23632      */
23633     /**
23634      * @event focus
23635      * @hide
23636      */
23637     /**
23638      * @event specialkey
23639      * @hide
23640      */
23641     /**
23642      * @cfg {String} fieldClass @hide
23643      */
23644     /**
23645      * @cfg {String} focusClass @hide
23646      */
23647     /**
23648      * @cfg {String} autoCreate @hide
23649      */
23650     /**
23651      * @cfg {String} inputType @hide
23652      */
23653     /**
23654      * @cfg {String} invalidClass @hide
23655      */
23656     /**
23657      * @cfg {String} invalidText @hide
23658      */
23659     /**
23660      * @cfg {String} msgFx @hide
23661      */
23662     /**
23663      * @cfg {String} validateOnBlur @hide
23664      */
23665 });
23666
23667 Roo.HtmlEditorCore.white = [
23668         'area', 'br', 'img', 'input', 'hr', 'wbr',
23669         
23670        'address', 'blockquote', 'center', 'dd',      'dir',       'div', 
23671        'dl',      'dt',         'h1',     'h2',      'h3',        'h4', 
23672        'h5',      'h6',         'hr',     'isindex', 'listing',   'marquee', 
23673        'menu',    'multicol',   'ol',     'p',       'plaintext', 'pre', 
23674        'table',   'ul',         'xmp', 
23675        
23676        'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th', 
23677       'thead',   'tr', 
23678      
23679       'dir', 'menu', 'ol', 'ul', 'dl',
23680        
23681       'embed',  'object'
23682 ];
23683
23684
23685 Roo.HtmlEditorCore.black = [
23686     //    'embed',  'object', // enable - backend responsiblity to clean thiese
23687         'applet', // 
23688         'base',   'basefont', 'bgsound', 'blink',  'body', 
23689         'frame',  'frameset', 'head',    'html',   'ilayer', 
23690         'iframe', 'layer',  'link',     'meta',    'object',   
23691         'script', 'style' ,'title',  'xml' // clean later..
23692 ];
23693 Roo.HtmlEditorCore.clean = [
23694     'script', 'style', 'title', 'xml'
23695 ];
23696 Roo.HtmlEditorCore.remove = [
23697     'font'
23698 ];
23699 // attributes..
23700
23701 Roo.HtmlEditorCore.ablack = [
23702     'on'
23703 ];
23704     
23705 Roo.HtmlEditorCore.aclean = [ 
23706     'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc' 
23707 ];
23708
23709 // protocols..
23710 Roo.HtmlEditorCore.pwhite= [
23711         'http',  'https',  'mailto'
23712 ];
23713
23714 // white listed style attributes.
23715 Roo.HtmlEditorCore.cwhite= [
23716       //  'text-align', /// default is to allow most things..
23717       
23718          
23719 //        'font-size'//??
23720 ];
23721
23722 // black listed style attributes.
23723 Roo.HtmlEditorCore.cblack= [
23724       //  'font-size' -- this can be set by the project 
23725 ];
23726
23727
23728 Roo.HtmlEditorCore.swapCodes   =[ 
23729     [    8211, "--" ], 
23730     [    8212, "--" ], 
23731     [    8216,  "'" ],  
23732     [    8217, "'" ],  
23733     [    8220, '"' ],  
23734     [    8221, '"' ],  
23735     [    8226, "*" ],  
23736     [    8230, "..." ]
23737 ]; 
23738
23739     /*
23740  * - LGPL
23741  *
23742  * HtmlEditor
23743  * 
23744  */
23745
23746 /**
23747  * @class Roo.bootstrap.HtmlEditor
23748  * @extends Roo.bootstrap.TextArea
23749  * Bootstrap HtmlEditor class
23750
23751  * @constructor
23752  * Create a new HtmlEditor
23753  * @param {Object} config The config object
23754  */
23755
23756 Roo.bootstrap.HtmlEditor = function(config){
23757     Roo.bootstrap.HtmlEditor.superclass.constructor.call(this, config);
23758     if (!this.toolbars) {
23759         this.toolbars = [];
23760     }
23761     
23762     this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
23763     this.addEvents({
23764             /**
23765              * @event initialize
23766              * Fires when the editor is fully initialized (including the iframe)
23767              * @param {HtmlEditor} this
23768              */
23769             initialize: true,
23770             /**
23771              * @event activate
23772              * Fires when the editor is first receives the focus. Any insertion must wait
23773              * until after this event.
23774              * @param {HtmlEditor} this
23775              */
23776             activate: true,
23777              /**
23778              * @event beforesync
23779              * Fires before the textarea is updated with content from the editor iframe. Return false
23780              * to cancel the sync.
23781              * @param {HtmlEditor} this
23782              * @param {String} html
23783              */
23784             beforesync: true,
23785              /**
23786              * @event beforepush
23787              * Fires before the iframe editor is updated with content from the textarea. Return false
23788              * to cancel the push.
23789              * @param {HtmlEditor} this
23790              * @param {String} html
23791              */
23792             beforepush: true,
23793              /**
23794              * @event sync
23795              * Fires when the textarea is updated with content from the editor iframe.
23796              * @param {HtmlEditor} this
23797              * @param {String} html
23798              */
23799             sync: true,
23800              /**
23801              * @event push
23802              * Fires when the iframe editor is updated with content from the textarea.
23803              * @param {HtmlEditor} this
23804              * @param {String} html
23805              */
23806             push: true,
23807              /**
23808              * @event editmodechange
23809              * Fires when the editor switches edit modes
23810              * @param {HtmlEditor} this
23811              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
23812              */
23813             editmodechange: true,
23814             /**
23815              * @event editorevent
23816              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
23817              * @param {HtmlEditor} this
23818              */
23819             editorevent: true,
23820             /**
23821              * @event firstfocus
23822              * Fires when on first focus - needed by toolbars..
23823              * @param {HtmlEditor} this
23824              */
23825             firstfocus: true,
23826             /**
23827              * @event autosave
23828              * Auto save the htmlEditor value as a file into Events
23829              * @param {HtmlEditor} this
23830              */
23831             autosave: true,
23832             /**
23833              * @event savedpreview
23834              * preview the saved version of htmlEditor
23835              * @param {HtmlEditor} this
23836              */
23837             savedpreview: true
23838         });
23839 };
23840
23841
23842 Roo.extend(Roo.bootstrap.HtmlEditor, Roo.bootstrap.TextArea,  {
23843     
23844     
23845       /**
23846      * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
23847      */
23848     toolbars : false,
23849     
23850      /**
23851     * @cfg {Array} buttons Array of toolbar's buttons. - defaults to empty
23852     */
23853     btns : [],
23854    
23855      /**
23856      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
23857      *                        Roo.resizable.
23858      */
23859     resizable : false,
23860      /**
23861      * @cfg {Number} height (in pixels)
23862      */   
23863     height: 300,
23864    /**
23865      * @cfg {Number} width (in pixels)
23866      */   
23867     width: false,
23868     
23869     /**
23870      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
23871      * 
23872      */
23873     stylesheets: false,
23874     
23875     // id of frame..
23876     frameId: false,
23877     
23878     // private properties
23879     validationEvent : false,
23880     deferHeight: true,
23881     initialized : false,
23882     activated : false,
23883     
23884     onFocus : Roo.emptyFn,
23885     iframePad:3,
23886     hideMode:'offsets',
23887     
23888     tbContainer : false,
23889     
23890     bodyCls : '',
23891     
23892     toolbarContainer :function() {
23893         return this.wrap.select('.x-html-editor-tb',true).first();
23894     },
23895
23896     /**
23897      * Protected method that will not generally be called directly. It
23898      * is called when the editor creates its toolbar. Override this method if you need to
23899      * add custom toolbar buttons.
23900      * @param {HtmlEditor} editor
23901      */
23902     createToolbar : function(){
23903         Roo.log('renewing');
23904         Roo.log("create toolbars");
23905         
23906         this.toolbars = [ new Roo.bootstrap.htmleditor.ToolbarStandard({editor: this} ) ];
23907         this.toolbars[0].render(this.toolbarContainer());
23908         
23909         return;
23910         
23911 //        if (!editor.toolbars || !editor.toolbars.length) {
23912 //            editor.toolbars = [ new Roo.bootstrap.HtmlEditor.ToolbarStandard() ]; // can be empty?
23913 //        }
23914 //        
23915 //        for (var i =0 ; i < editor.toolbars.length;i++) {
23916 //            editor.toolbars[i] = Roo.factory(
23917 //                    typeof(editor.toolbars[i]) == 'string' ?
23918 //                        { xtype: editor.toolbars[i]} : editor.toolbars[i],
23919 //                Roo.bootstrap.HtmlEditor);
23920 //            editor.toolbars[i].init(editor);
23921 //        }
23922     },
23923
23924      
23925     // private
23926     onRender : function(ct, position)
23927     {
23928        // Roo.log("Call onRender: " + this.xtype);
23929         var _t = this;
23930         Roo.bootstrap.HtmlEditor.superclass.onRender.call(this, ct, position);
23931       
23932         this.wrap = this.inputEl().wrap({
23933             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
23934         });
23935         
23936         this.editorcore.onRender(ct, position);
23937          
23938         if (this.resizable) {
23939             this.resizeEl = new Roo.Resizable(this.wrap, {
23940                 pinned : true,
23941                 wrap: true,
23942                 dynamic : true,
23943                 minHeight : this.height,
23944                 height: this.height,
23945                 handles : this.resizable,
23946                 width: this.width,
23947                 listeners : {
23948                     resize : function(r, w, h) {
23949                         _t.onResize(w,h); // -something
23950                     }
23951                 }
23952             });
23953             
23954         }
23955         this.createToolbar(this);
23956        
23957         
23958         if(!this.width && this.resizable){
23959             this.setSize(this.wrap.getSize());
23960         }
23961         if (this.resizeEl) {
23962             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
23963             // should trigger onReize..
23964         }
23965         
23966     },
23967
23968     // private
23969     onResize : function(w, h)
23970     {
23971         Roo.log('resize: ' +w + ',' + h );
23972         Roo.bootstrap.HtmlEditor.superclass.onResize.apply(this, arguments);
23973         var ew = false;
23974         var eh = false;
23975         
23976         if(this.inputEl() ){
23977             if(typeof w == 'number'){
23978                 var aw = w - this.wrap.getFrameWidth('lr');
23979                 this.inputEl().setWidth(this.adjustWidth('textarea', aw));
23980                 ew = aw;
23981             }
23982             if(typeof h == 'number'){
23983                  var tbh = -11;  // fixme it needs to tool bar size!
23984                 for (var i =0; i < this.toolbars.length;i++) {
23985                     // fixme - ask toolbars for heights?
23986                     tbh += this.toolbars[i].el.getHeight();
23987                     //if (this.toolbars[i].footer) {
23988                     //    tbh += this.toolbars[i].footer.el.getHeight();
23989                     //}
23990                 }
23991               
23992                 
23993                 
23994                 
23995                 
23996                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
23997                 ah -= 5; // knock a few pixes off for look..
23998                 this.inputEl().setHeight(this.adjustWidth('textarea', ah));
23999                 var eh = ah;
24000             }
24001         }
24002         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
24003         this.editorcore.onResize(ew,eh);
24004         
24005     },
24006
24007     /**
24008      * Toggles the editor between standard and source edit mode.
24009      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
24010      */
24011     toggleSourceEdit : function(sourceEditMode)
24012     {
24013         this.editorcore.toggleSourceEdit(sourceEditMode);
24014         
24015         if(this.editorcore.sourceEditMode){
24016             Roo.log('editor - showing textarea');
24017             
24018 //            Roo.log('in');
24019 //            Roo.log(this.syncValue());
24020             this.syncValue();
24021             this.inputEl().removeClass(['hide', 'x-hidden']);
24022             this.inputEl().dom.removeAttribute('tabIndex');
24023             this.inputEl().focus();
24024         }else{
24025             Roo.log('editor - hiding textarea');
24026 //            Roo.log('out')
24027 //            Roo.log(this.pushValue()); 
24028             this.pushValue();
24029             
24030             this.inputEl().addClass(['hide', 'x-hidden']);
24031             this.inputEl().dom.setAttribute('tabIndex', -1);
24032             //this.deferFocus();
24033         }
24034          
24035         if(this.resizable){
24036             this.setSize(this.wrap.getSize());
24037         }
24038         
24039         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
24040     },
24041  
24042     // private (for BoxComponent)
24043     adjustSize : Roo.BoxComponent.prototype.adjustSize,
24044
24045     // private (for BoxComponent)
24046     getResizeEl : function(){
24047         return this.wrap;
24048     },
24049
24050     // private (for BoxComponent)
24051     getPositionEl : function(){
24052         return this.wrap;
24053     },
24054
24055     // private
24056     initEvents : function(){
24057         this.originalValue = this.getValue();
24058     },
24059
24060 //    /**
24061 //     * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
24062 //     * @method
24063 //     */
24064 //    markInvalid : Roo.emptyFn,
24065 //    /**
24066 //     * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
24067 //     * @method
24068 //     */
24069 //    clearInvalid : Roo.emptyFn,
24070
24071     setValue : function(v){
24072         Roo.bootstrap.HtmlEditor.superclass.setValue.call(this, v);
24073         this.editorcore.pushValue();
24074     },
24075
24076      
24077     // private
24078     deferFocus : function(){
24079         this.focus.defer(10, this);
24080     },
24081
24082     // doc'ed in Field
24083     focus : function(){
24084         this.editorcore.focus();
24085         
24086     },
24087       
24088
24089     // private
24090     onDestroy : function(){
24091         
24092         
24093         
24094         if(this.rendered){
24095             
24096             for (var i =0; i < this.toolbars.length;i++) {
24097                 // fixme - ask toolbars for heights?
24098                 this.toolbars[i].onDestroy();
24099             }
24100             
24101             this.wrap.dom.innerHTML = '';
24102             this.wrap.remove();
24103         }
24104     },
24105
24106     // private
24107     onFirstFocus : function(){
24108         //Roo.log("onFirstFocus");
24109         this.editorcore.onFirstFocus();
24110          for (var i =0; i < this.toolbars.length;i++) {
24111             this.toolbars[i].onFirstFocus();
24112         }
24113         
24114     },
24115     
24116     // private
24117     syncValue : function()
24118     {   
24119         this.editorcore.syncValue();
24120     },
24121     
24122     pushValue : function()
24123     {   
24124         this.editorcore.pushValue();
24125     }
24126      
24127     
24128     // hide stuff that is not compatible
24129     /**
24130      * @event blur
24131      * @hide
24132      */
24133     /**
24134      * @event change
24135      * @hide
24136      */
24137     /**
24138      * @event focus
24139      * @hide
24140      */
24141     /**
24142      * @event specialkey
24143      * @hide
24144      */
24145     /**
24146      * @cfg {String} fieldClass @hide
24147      */
24148     /**
24149      * @cfg {String} focusClass @hide
24150      */
24151     /**
24152      * @cfg {String} autoCreate @hide
24153      */
24154     /**
24155      * @cfg {String} inputType @hide
24156      */
24157      
24158     /**
24159      * @cfg {String} invalidText @hide
24160      */
24161     /**
24162      * @cfg {String} msgFx @hide
24163      */
24164     /**
24165      * @cfg {String} validateOnBlur @hide
24166      */
24167 });
24168  
24169     
24170    
24171    
24172    
24173       
24174 Roo.namespace('Roo.bootstrap.htmleditor');
24175 /**
24176  * @class Roo.bootstrap.HtmlEditorToolbar1
24177  * Basic Toolbar
24178  * 
24179  * @example
24180  * Usage:
24181  *
24182  new Roo.bootstrap.HtmlEditor({
24183     ....
24184     toolbars : [
24185         new Roo.bootstrap.HtmlEditorToolbar1({
24186             disable : { fonts: 1 , format: 1, ..., ... , ...],
24187             btns : [ .... ]
24188         })
24189     }
24190      
24191  * 
24192  * @cfg {Object} disable List of elements to disable..
24193  * @cfg {Array} btns List of additional buttons.
24194  * 
24195  * 
24196  * NEEDS Extra CSS? 
24197  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
24198  */
24199  
24200 Roo.bootstrap.htmleditor.ToolbarStandard = function(config)
24201 {
24202     
24203     Roo.apply(this, config);
24204     
24205     // default disabled, based on 'good practice'..
24206     this.disable = this.disable || {};
24207     Roo.applyIf(this.disable, {
24208         fontSize : true,
24209         colors : true,
24210         specialElements : true
24211     });
24212     Roo.bootstrap.htmleditor.ToolbarStandard.superclass.constructor.call(this, config);
24213     
24214     this.editor = config.editor;
24215     this.editorcore = config.editor.editorcore;
24216     
24217     this.buttons   = new Roo.util.MixedCollection(false, function(o) { return o.cmd; });
24218     
24219     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
24220     // dont call parent... till later.
24221 }
24222 Roo.extend(Roo.bootstrap.htmleditor.ToolbarStandard, Roo.bootstrap.NavSimplebar,  {
24223      
24224     bar : true,
24225     
24226     editor : false,
24227     editorcore : false,
24228     
24229     
24230     formats : [
24231         "p" ,  
24232         "h1","h2","h3","h4","h5","h6", 
24233         "pre", "code", 
24234         "abbr", "acronym", "address", "cite", "samp", "var",
24235         'div','span'
24236     ],
24237     
24238     onRender : function(ct, position)
24239     {
24240        // Roo.log("Call onRender: " + this.xtype);
24241         
24242        Roo.bootstrap.htmleditor.ToolbarStandard.superclass.onRender.call(this, ct, position);
24243        Roo.log(this.el);
24244        this.el.dom.style.marginBottom = '0';
24245        var _this = this;
24246        var editorcore = this.editorcore;
24247        var editor= this.editor;
24248        
24249        var children = [];
24250        var btn = function(id,cmd , toggle, handler, html){
24251        
24252             var  event = toggle ? 'toggle' : 'click';
24253        
24254             var a = {
24255                 size : 'sm',
24256                 xtype: 'Button',
24257                 xns: Roo.bootstrap,
24258                 //glyphicon : id,
24259                 fa: id,
24260                 cmd : id || cmd,
24261                 enableToggle:toggle !== false,
24262                 html : html || '',
24263                 pressed : toggle ? false : null,
24264                 listeners : {}
24265             };
24266             a.listeners[toggle ? 'toggle' : 'click'] = function() {
24267                 handler ? handler.call(_this,this) :_this.onBtnClick.call(_this, cmd ||  id);
24268             };
24269             children.push(a);
24270             return a;
24271        }
24272        
24273     //    var cb_box = function...
24274         
24275         var style = {
24276                 xtype: 'Button',
24277                 size : 'sm',
24278                 xns: Roo.bootstrap,
24279                 fa : 'font',
24280                 //html : 'submit'
24281                 menu : {
24282                     xtype: 'Menu',
24283                     xns: Roo.bootstrap,
24284                     items:  []
24285                 }
24286         };
24287         Roo.each(this.formats, function(f) {
24288             style.menu.items.push({
24289                 xtype :'MenuItem',
24290                 xns: Roo.bootstrap,
24291                 html : '<'+ f+' style="margin:2px">'+f +'</'+ f+'>',
24292                 tagname : f,
24293                 listeners : {
24294                     click : function()
24295                     {
24296                         editorcore.insertTag(this.tagname);
24297                         editor.focus();
24298                     }
24299                 }
24300                 
24301             });
24302         });
24303         children.push(style);   
24304         
24305         btn('bold',false,true);
24306         btn('italic',false,true);
24307         btn('align-left', 'justifyleft',true);
24308         btn('align-center', 'justifycenter',true);
24309         btn('align-right' , 'justifyright',true);
24310         btn('link', false, false, function(btn) {
24311             //Roo.log("create link?");
24312             var url = prompt(this.createLinkText, this.defaultLinkValue);
24313             if(url && url != 'http:/'+'/'){
24314                 this.editorcore.relayCmd('createlink', url);
24315             }
24316         }),
24317         btn('list','insertunorderedlist',true);
24318         btn('pencil', false,true, function(btn){
24319                 Roo.log(this);
24320                 this.toggleSourceEdit(btn.pressed);
24321         });
24322         
24323         if (this.editor.btns.length > 0) {
24324             for (var i = 0; i<this.editor.btns.length; i++) {
24325                 children.push(this.editor.btns[i]);
24326             }
24327         }
24328         
24329         /*
24330         var cog = {
24331                 xtype: 'Button',
24332                 size : 'sm',
24333                 xns: Roo.bootstrap,
24334                 glyphicon : 'cog',
24335                 //html : 'submit'
24336                 menu : {
24337                     xtype: 'Menu',
24338                     xns: Roo.bootstrap,
24339                     items:  []
24340                 }
24341         };
24342         
24343         cog.menu.items.push({
24344             xtype :'MenuItem',
24345             xns: Roo.bootstrap,
24346             html : Clean styles,
24347             tagname : f,
24348             listeners : {
24349                 click : function()
24350                 {
24351                     editorcore.insertTag(this.tagname);
24352                     editor.focus();
24353                 }
24354             }
24355             
24356         });
24357        */
24358         
24359          
24360        this.xtype = 'NavSimplebar';
24361         
24362         for(var i=0;i< children.length;i++) {
24363             
24364             this.buttons.add(this.addxtypeChild(children[i]));
24365             
24366         }
24367         
24368         editor.on('editorevent', this.updateToolbar, this);
24369     },
24370     onBtnClick : function(id)
24371     {
24372        this.editorcore.relayCmd(id);
24373        this.editorcore.focus();
24374     },
24375     
24376     /**
24377      * Protected method that will not generally be called directly. It triggers
24378      * a toolbar update by reading the markup state of the current selection in the editor.
24379      */
24380     updateToolbar: function(){
24381
24382         if(!this.editorcore.activated){
24383             this.editor.onFirstFocus(); // is this neeed?
24384             return;
24385         }
24386
24387         var btns = this.buttons; 
24388         var doc = this.editorcore.doc;
24389         btns.get('bold').setActive(doc.queryCommandState('bold'));
24390         btns.get('italic').setActive(doc.queryCommandState('italic'));
24391         //btns.get('underline').setActive(doc.queryCommandState('underline'));
24392         
24393         btns.get('align-left').setActive(doc.queryCommandState('justifyleft'));
24394         btns.get('align-center').setActive(doc.queryCommandState('justifycenter'));
24395         btns.get('align-right').setActive(doc.queryCommandState('justifyright'));
24396         
24397         //btns[frameId + '-insertorderedlist').setActive(doc.queryCommandState('insertorderedlist'));
24398         btns.get('list').setActive(doc.queryCommandState('insertunorderedlist'));
24399          /*
24400         
24401         var ans = this.editorcore.getAllAncestors();
24402         if (this.formatCombo) {
24403             
24404             
24405             var store = this.formatCombo.store;
24406             this.formatCombo.setValue("");
24407             for (var i =0; i < ans.length;i++) {
24408                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
24409                     // select it..
24410                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
24411                     break;
24412                 }
24413             }
24414         }
24415         
24416         
24417         
24418         // hides menus... - so this cant be on a menu...
24419         Roo.bootstrap.MenuMgr.hideAll();
24420         */
24421         Roo.bootstrap.MenuMgr.hideAll();
24422         //this.editorsyncValue();
24423     },
24424     onFirstFocus: function() {
24425         this.buttons.each(function(item){
24426            item.enable();
24427         });
24428     },
24429     toggleSourceEdit : function(sourceEditMode){
24430         
24431           
24432         if(sourceEditMode){
24433             Roo.log("disabling buttons");
24434            this.buttons.each( function(item){
24435                 if(item.cmd != 'pencil'){
24436                     item.disable();
24437                 }
24438             });
24439           
24440         }else{
24441             Roo.log("enabling buttons");
24442             if(this.editorcore.initialized){
24443                 this.buttons.each( function(item){
24444                     item.enable();
24445                 });
24446             }
24447             
24448         }
24449         Roo.log("calling toggole on editor");
24450         // tell the editor that it's been pressed..
24451         this.editor.toggleSourceEdit(sourceEditMode);
24452        
24453     }
24454 });
24455
24456
24457
24458
24459
24460 /**
24461  * @class Roo.bootstrap.Table.AbstractSelectionModel
24462  * @extends Roo.util.Observable
24463  * Abstract base class for grid SelectionModels.  It provides the interface that should be
24464  * implemented by descendant classes.  This class should not be directly instantiated.
24465  * @constructor
24466  */
24467 Roo.bootstrap.Table.AbstractSelectionModel = function(){
24468     this.locked = false;
24469     Roo.bootstrap.Table.AbstractSelectionModel.superclass.constructor.call(this);
24470 };
24471
24472
24473 Roo.extend(Roo.bootstrap.Table.AbstractSelectionModel, Roo.util.Observable,  {
24474     /** @ignore Called by the grid automatically. Do not call directly. */
24475     init : function(grid){
24476         this.grid = grid;
24477         this.initEvents();
24478     },
24479
24480     /**
24481      * Locks the selections.
24482      */
24483     lock : function(){
24484         this.locked = true;
24485     },
24486
24487     /**
24488      * Unlocks the selections.
24489      */
24490     unlock : function(){
24491         this.locked = false;
24492     },
24493
24494     /**
24495      * Returns true if the selections are locked.
24496      * @return {Boolean}
24497      */
24498     isLocked : function(){
24499         return this.locked;
24500     }
24501 });
24502 /**
24503  * @extends Roo.bootstrap.Table.AbstractSelectionModel
24504  * @class Roo.bootstrap.Table.RowSelectionModel
24505  * The default SelectionModel used by {@link Roo.bootstrap.Table}.
24506  * It supports multiple selections and keyboard selection/navigation. 
24507  * @constructor
24508  * @param {Object} config
24509  */
24510
24511 Roo.bootstrap.Table.RowSelectionModel = function(config){
24512     Roo.apply(this, config);
24513     this.selections = new Roo.util.MixedCollection(false, function(o){
24514         return o.id;
24515     });
24516
24517     this.last = false;
24518     this.lastActive = false;
24519
24520     this.addEvents({
24521         /**
24522              * @event selectionchange
24523              * Fires when the selection changes
24524              * @param {SelectionModel} this
24525              */
24526             "selectionchange" : true,
24527         /**
24528              * @event afterselectionchange
24529              * Fires after the selection changes (eg. by key press or clicking)
24530              * @param {SelectionModel} this
24531              */
24532             "afterselectionchange" : true,
24533         /**
24534              * @event beforerowselect
24535              * Fires when a row is selected being selected, return false to cancel.
24536              * @param {SelectionModel} this
24537              * @param {Number} rowIndex The selected index
24538              * @param {Boolean} keepExisting False if other selections will be cleared
24539              */
24540             "beforerowselect" : true,
24541         /**
24542              * @event rowselect
24543              * Fires when a row is selected.
24544              * @param {SelectionModel} this
24545              * @param {Number} rowIndex The selected index
24546              * @param {Roo.data.Record} r The record
24547              */
24548             "rowselect" : true,
24549         /**
24550              * @event rowdeselect
24551              * Fires when a row is deselected.
24552              * @param {SelectionModel} this
24553              * @param {Number} rowIndex The selected index
24554              */
24555         "rowdeselect" : true
24556     });
24557     Roo.bootstrap.Table.RowSelectionModel.superclass.constructor.call(this);
24558     this.locked = false;
24559  };
24560
24561 Roo.extend(Roo.bootstrap.Table.RowSelectionModel, Roo.bootstrap.Table.AbstractSelectionModel,  {
24562     /**
24563      * @cfg {Boolean} singleSelect
24564      * True to allow selection of only one row at a time (defaults to false)
24565      */
24566     singleSelect : false,
24567
24568     // private
24569     initEvents : function()
24570     {
24571
24572         //if(!this.grid.enableDragDrop && !this.grid.enableDrag){
24573         //    this.growclickrid.on("mousedown", this.handleMouseDown, this);
24574         //}else{ // allow click to work like normal
24575          //   this.grid.on("rowclick", this.handleDragableRowClick, this);
24576         //}
24577         //this.grid.on("rowdblclick", this.handleMouseDBClick, this);
24578         this.grid.on("rowclick", this.handleMouseDown, this);
24579         
24580         this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
24581             "up" : function(e){
24582                 if(!e.shiftKey){
24583                     this.selectPrevious(e.shiftKey);
24584                 }else if(this.last !== false && this.lastActive !== false){
24585                     var last = this.last;
24586                     this.selectRange(this.last,  this.lastActive-1);
24587                     this.grid.getView().focusRow(this.lastActive);
24588                     if(last !== false){
24589                         this.last = last;
24590                     }
24591                 }else{
24592                     this.selectFirstRow();
24593                 }
24594                 this.fireEvent("afterselectionchange", this);
24595             },
24596             "down" : function(e){
24597                 if(!e.shiftKey){
24598                     this.selectNext(e.shiftKey);
24599                 }else if(this.last !== false && this.lastActive !== false){
24600                     var last = this.last;
24601                     this.selectRange(this.last,  this.lastActive+1);
24602                     this.grid.getView().focusRow(this.lastActive);
24603                     if(last !== false){
24604                         this.last = last;
24605                     }
24606                 }else{
24607                     this.selectFirstRow();
24608                 }
24609                 this.fireEvent("afterselectionchange", this);
24610             },
24611             scope: this
24612         });
24613         this.grid.store.on('load', function(){
24614             this.selections.clear();
24615         },this);
24616         /*
24617         var view = this.grid.view;
24618         view.on("refresh", this.onRefresh, this);
24619         view.on("rowupdated", this.onRowUpdated, this);
24620         view.on("rowremoved", this.onRemove, this);
24621         */
24622     },
24623
24624     // private
24625     onRefresh : function()
24626     {
24627         var ds = this.grid.store, i, v = this.grid.view;
24628         var s = this.selections;
24629         s.each(function(r){
24630             if((i = ds.indexOfId(r.id)) != -1){
24631                 v.onRowSelect(i);
24632             }else{
24633                 s.remove(r);
24634             }
24635         });
24636     },
24637
24638     // private
24639     onRemove : function(v, index, r){
24640         this.selections.remove(r);
24641     },
24642
24643     // private
24644     onRowUpdated : function(v, index, r){
24645         if(this.isSelected(r)){
24646             v.onRowSelect(index);
24647         }
24648     },
24649
24650     /**
24651      * Select records.
24652      * @param {Array} records The records to select
24653      * @param {Boolean} keepExisting (optional) True to keep existing selections
24654      */
24655     selectRecords : function(records, keepExisting)
24656     {
24657         if(!keepExisting){
24658             this.clearSelections();
24659         }
24660             var ds = this.grid.store;
24661         for(var i = 0, len = records.length; i < len; i++){
24662             this.selectRow(ds.indexOf(records[i]), true);
24663         }
24664     },
24665
24666     /**
24667      * Gets the number of selected rows.
24668      * @return {Number}
24669      */
24670     getCount : function(){
24671         return this.selections.length;
24672     },
24673
24674     /**
24675      * Selects the first row in the grid.
24676      */
24677     selectFirstRow : function(){
24678         this.selectRow(0);
24679     },
24680
24681     /**
24682      * Select the last row.
24683      * @param {Boolean} keepExisting (optional) True to keep existing selections
24684      */
24685     selectLastRow : function(keepExisting){
24686         //this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting);
24687         this.selectRow(this.grid.store.getCount() - 1, keepExisting);
24688     },
24689
24690     /**
24691      * Selects the row immediately following the last selected row.
24692      * @param {Boolean} keepExisting (optional) True to keep existing selections
24693      */
24694     selectNext : function(keepExisting)
24695     {
24696             if(this.last !== false && (this.last+1) < this.grid.store.getCount()){
24697             this.selectRow(this.last+1, keepExisting);
24698             this.grid.getView().focusRow(this.last);
24699         }
24700     },
24701
24702     /**
24703      * Selects the row that precedes the last selected row.
24704      * @param {Boolean} keepExisting (optional) True to keep existing selections
24705      */
24706     selectPrevious : function(keepExisting){
24707         if(this.last){
24708             this.selectRow(this.last-1, keepExisting);
24709             this.grid.getView().focusRow(this.last);
24710         }
24711     },
24712
24713     /**
24714      * Returns the selected records
24715      * @return {Array} Array of selected records
24716      */
24717     getSelections : function(){
24718         return [].concat(this.selections.items);
24719     },
24720
24721     /**
24722      * Returns the first selected record.
24723      * @return {Record}
24724      */
24725     getSelected : function(){
24726         return this.selections.itemAt(0);
24727     },
24728
24729
24730     /**
24731      * Clears all selections.
24732      */
24733     clearSelections : function(fast)
24734     {
24735         if(this.locked) {
24736             return;
24737         }
24738         if(fast !== true){
24739                 var ds = this.grid.store;
24740             var s = this.selections;
24741             s.each(function(r){
24742                 this.deselectRow(ds.indexOfId(r.id));
24743             }, this);
24744             s.clear();
24745         }else{
24746             this.selections.clear();
24747         }
24748         this.last = false;
24749     },
24750
24751
24752     /**
24753      * Selects all rows.
24754      */
24755     selectAll : function(){
24756         if(this.locked) {
24757             return;
24758         }
24759         this.selections.clear();
24760         for(var i = 0, len = this.grid.store.getCount(); i < len; i++){
24761             this.selectRow(i, true);
24762         }
24763     },
24764
24765     /**
24766      * Returns True if there is a selection.
24767      * @return {Boolean}
24768      */
24769     hasSelection : function(){
24770         return this.selections.length > 0;
24771     },
24772
24773     /**
24774      * Returns True if the specified row is selected.
24775      * @param {Number/Record} record The record or index of the record to check
24776      * @return {Boolean}
24777      */
24778     isSelected : function(index){
24779             var r = typeof index == "number" ? this.grid.store.getAt(index) : index;
24780         return (r && this.selections.key(r.id) ? true : false);
24781     },
24782
24783     /**
24784      * Returns True if the specified record id is selected.
24785      * @param {String} id The id of record to check
24786      * @return {Boolean}
24787      */
24788     isIdSelected : function(id){
24789         return (this.selections.key(id) ? true : false);
24790     },
24791
24792
24793     // private
24794     handleMouseDBClick : function(e, t){
24795         
24796     },
24797     // private
24798     handleMouseDown : function(e, t)
24799     {
24800             var rowIndex = this.grid.headerShow  ? t.dom.rowIndex - 1 : t.dom.rowIndex ; // first row is header???
24801         if(this.isLocked() || rowIndex < 0 ){
24802             return;
24803         };
24804         if(e.shiftKey && this.last !== false){
24805             var last = this.last;
24806             this.selectRange(last, rowIndex, e.ctrlKey);
24807             this.last = last; // reset the last
24808             t.focus();
24809     
24810         }else{
24811             var isSelected = this.isSelected(rowIndex);
24812             //Roo.log("select row:" + rowIndex);
24813             if(isSelected){
24814                 this.deselectRow(rowIndex);
24815             } else {
24816                         this.selectRow(rowIndex, true);
24817             }
24818     
24819             /*
24820                 if(e.button !== 0 && isSelected){
24821                 alert('rowIndex 2: ' + rowIndex);
24822                     view.focusRow(rowIndex);
24823                 }else if(e.ctrlKey && isSelected){
24824                     this.deselectRow(rowIndex);
24825                 }else if(!isSelected){
24826                     this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
24827                     view.focusRow(rowIndex);
24828                 }
24829             */
24830         }
24831         this.fireEvent("afterselectionchange", this);
24832     },
24833     // private
24834     handleDragableRowClick :  function(grid, rowIndex, e) 
24835     {
24836         if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
24837             this.selectRow(rowIndex, false);
24838             grid.view.focusRow(rowIndex);
24839              this.fireEvent("afterselectionchange", this);
24840         }
24841     },
24842     
24843     /**
24844      * Selects multiple rows.
24845      * @param {Array} rows Array of the indexes of the row to select
24846      * @param {Boolean} keepExisting (optional) True to keep existing selections
24847      */
24848     selectRows : function(rows, keepExisting){
24849         if(!keepExisting){
24850             this.clearSelections();
24851         }
24852         for(var i = 0, len = rows.length; i < len; i++){
24853             this.selectRow(rows[i], true);
24854         }
24855     },
24856
24857     /**
24858      * Selects a range of rows. All rows in between startRow and endRow are also selected.
24859      * @param {Number} startRow The index of the first row in the range
24860      * @param {Number} endRow The index of the last row in the range
24861      * @param {Boolean} keepExisting (optional) True to retain existing selections
24862      */
24863     selectRange : function(startRow, endRow, keepExisting){
24864         if(this.locked) {
24865             return;
24866         }
24867         if(!keepExisting){
24868             this.clearSelections();
24869         }
24870         if(startRow <= endRow){
24871             for(var i = startRow; i <= endRow; i++){
24872                 this.selectRow(i, true);
24873             }
24874         }else{
24875             for(var i = startRow; i >= endRow; i--){
24876                 this.selectRow(i, true);
24877             }
24878         }
24879     },
24880
24881     /**
24882      * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
24883      * @param {Number} startRow The index of the first row in the range
24884      * @param {Number} endRow The index of the last row in the range
24885      */
24886     deselectRange : function(startRow, endRow, preventViewNotify){
24887         if(this.locked) {
24888             return;
24889         }
24890         for(var i = startRow; i <= endRow; i++){
24891             this.deselectRow(i, preventViewNotify);
24892         }
24893     },
24894
24895     /**
24896      * Selects a row.
24897      * @param {Number} row The index of the row to select
24898      * @param {Boolean} keepExisting (optional) True to keep existing selections
24899      */
24900     selectRow : function(index, keepExisting, preventViewNotify)
24901     {
24902             if(this.locked || (index < 0 || index > this.grid.store.getCount())) {
24903             return;
24904         }
24905         if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
24906             if(!keepExisting || this.singleSelect){
24907                 this.clearSelections();
24908             }
24909             
24910             var r = this.grid.store.getAt(index);
24911             //console.log('selectRow - record id :' + r.id);
24912             
24913             this.selections.add(r);
24914             this.last = this.lastActive = index;
24915             if(!preventViewNotify){
24916                 var proxy = new Roo.Element(
24917                                 this.grid.getRowDom(index)
24918                 );
24919                 proxy.addClass('bg-info info');
24920             }
24921             this.fireEvent("rowselect", this, index, r);
24922             this.fireEvent("selectionchange", this);
24923         }
24924     },
24925
24926     /**
24927      * Deselects a row.
24928      * @param {Number} row The index of the row to deselect
24929      */
24930     deselectRow : function(index, preventViewNotify)
24931     {
24932         if(this.locked) {
24933             return;
24934         }
24935         if(this.last == index){
24936             this.last = false;
24937         }
24938         if(this.lastActive == index){
24939             this.lastActive = false;
24940         }
24941         
24942         var r = this.grid.store.getAt(index);
24943         if (!r) {
24944             return;
24945         }
24946         
24947         this.selections.remove(r);
24948         //.console.log('deselectRow - record id :' + r.id);
24949         if(!preventViewNotify){
24950         
24951             var proxy = new Roo.Element(
24952                 this.grid.getRowDom(index)
24953             );
24954             proxy.removeClass('bg-info info');
24955         }
24956         this.fireEvent("rowdeselect", this, index);
24957         this.fireEvent("selectionchange", this);
24958     },
24959
24960     // private
24961     restoreLast : function(){
24962         if(this._last){
24963             this.last = this._last;
24964         }
24965     },
24966
24967     // private
24968     acceptsNav : function(row, col, cm){
24969         return !cm.isHidden(col) && cm.isCellEditable(col, row);
24970     },
24971
24972     // private
24973     onEditorKey : function(field, e){
24974         var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
24975         if(k == e.TAB){
24976             e.stopEvent();
24977             ed.completeEdit();
24978             if(e.shiftKey){
24979                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
24980             }else{
24981                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
24982             }
24983         }else if(k == e.ENTER && !e.ctrlKey){
24984             e.stopEvent();
24985             ed.completeEdit();
24986             if(e.shiftKey){
24987                 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
24988             }else{
24989                 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
24990             }
24991         }else if(k == e.ESC){
24992             ed.cancelEdit();
24993         }
24994         if(newCell){
24995             g.startEditing(newCell[0], newCell[1]);
24996         }
24997     }
24998 });
24999 /*
25000  * Based on:
25001  * Ext JS Library 1.1.1
25002  * Copyright(c) 2006-2007, Ext JS, LLC.
25003  *
25004  * Originally Released Under LGPL - original licence link has changed is not relivant.
25005  *
25006  * Fork - LGPL
25007  * <script type="text/javascript">
25008  */
25009  
25010 /**
25011  * @class Roo.bootstrap.PagingToolbar
25012  * @extends Roo.bootstrap.NavSimplebar
25013  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
25014  * @constructor
25015  * Create a new PagingToolbar
25016  * @param {Object} config The config object
25017  * @param {Roo.data.Store} store
25018  */
25019 Roo.bootstrap.PagingToolbar = function(config)
25020 {
25021     // old args format still supported... - xtype is prefered..
25022         // created from xtype...
25023     
25024     this.ds = config.dataSource;
25025     
25026     if (config.store && !this.ds) {
25027         this.store= Roo.factory(config.store, Roo.data);
25028         this.ds = this.store;
25029         this.ds.xmodule = this.xmodule || false;
25030     }
25031     
25032     this.toolbarItems = [];
25033     if (config.items) {
25034         this.toolbarItems = config.items;
25035     }
25036     
25037     Roo.bootstrap.PagingToolbar.superclass.constructor.call(this, config);
25038     
25039     this.cursor = 0;
25040     
25041     if (this.ds) { 
25042         this.bind(this.ds);
25043     }
25044     
25045     if (Roo.bootstrap.version == 4) {
25046         this.navgroup = new Roo.bootstrap.ButtonGroup({ cls: 'pagination' });
25047     } else {
25048         this.navgroup = new Roo.bootstrap.NavGroup({ cls: 'pagination' });
25049     }
25050     
25051 };
25052
25053 Roo.extend(Roo.bootstrap.PagingToolbar, Roo.bootstrap.NavSimplebar, {
25054     /**
25055      * @cfg {Roo.data.Store} dataSource
25056      * The underlying data store providing the paged data
25057      */
25058     /**
25059      * @cfg {String/HTMLElement/Element} container
25060      * container The id or element that will contain the toolbar
25061      */
25062     /**
25063      * @cfg {Boolean} displayInfo
25064      * True to display the displayMsg (defaults to false)
25065      */
25066     /**
25067      * @cfg {Number} pageSize
25068      * The number of records to display per page (defaults to 20)
25069      */
25070     pageSize: 20,
25071     /**
25072      * @cfg {String} displayMsg
25073      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
25074      */
25075     displayMsg : 'Displaying {0} - {1} of {2}',
25076     /**
25077      * @cfg {String} emptyMsg
25078      * The message to display when no records are found (defaults to "No data to display")
25079      */
25080     emptyMsg : 'No data to display',
25081     /**
25082      * Customizable piece of the default paging text (defaults to "Page")
25083      * @type String
25084      */
25085     beforePageText : "Page",
25086     /**
25087      * Customizable piece of the default paging text (defaults to "of %0")
25088      * @type String
25089      */
25090     afterPageText : "of {0}",
25091     /**
25092      * Customizable piece of the default paging text (defaults to "First Page")
25093      * @type String
25094      */
25095     firstText : "First Page",
25096     /**
25097      * Customizable piece of the default paging text (defaults to "Previous Page")
25098      * @type String
25099      */
25100     prevText : "Previous Page",
25101     /**
25102      * Customizable piece of the default paging text (defaults to "Next Page")
25103      * @type String
25104      */
25105     nextText : "Next Page",
25106     /**
25107      * Customizable piece of the default paging text (defaults to "Last Page")
25108      * @type String
25109      */
25110     lastText : "Last Page",
25111     /**
25112      * Customizable piece of the default paging text (defaults to "Refresh")
25113      * @type String
25114      */
25115     refreshText : "Refresh",
25116
25117     buttons : false,
25118     // private
25119     onRender : function(ct, position) 
25120     {
25121         Roo.bootstrap.PagingToolbar.superclass.onRender.call(this, ct, position);
25122         this.navgroup.parentId = this.id;
25123         this.navgroup.onRender(this.el, null);
25124         // add the buttons to the navgroup
25125         
25126         if(this.displayInfo){
25127             this.el.select('ul.navbar-nav',true).first().createChild({cls:'x-paging-info'});
25128             this.displayEl = this.el.select('.x-paging-info', true).first();
25129 //            var navel = this.navgroup.addItem( { tagtype : 'span', html : '', cls : 'x-paging-info', preventDefault : true } );
25130 //            this.displayEl = navel.el.select('span',true).first();
25131         }
25132         
25133         var _this = this;
25134         
25135         if(this.buttons){
25136             Roo.each(_this.buttons, function(e){ // this might need to use render????
25137                Roo.factory(e).render(_this.el);
25138             });
25139         }
25140             
25141         Roo.each(_this.toolbarItems, function(e) {
25142             _this.navgroup.addItem(e);
25143         });
25144         
25145         
25146         this.first = this.navgroup.addItem({
25147             tooltip: this.firstText,
25148             cls: "prev btn-outline-secondary",
25149             html : ' <i class="fa fa-step-backward"></i>',
25150             disabled: true,
25151             preventDefault: true,
25152             listeners : { click : this.onClick.createDelegate(this, ["first"]) }
25153         });
25154         
25155         this.prev =  this.navgroup.addItem({
25156             tooltip: this.prevText,
25157             cls: "prev btn-outline-secondary",
25158             html : ' <i class="fa fa-backward"></i>',
25159             disabled: true,
25160             preventDefault: true,
25161             listeners : { click :  this.onClick.createDelegate(this, ["prev"]) }
25162         });
25163     //this.addSeparator();
25164         
25165         
25166         var field = this.navgroup.addItem( {
25167             tagtype : 'span',
25168             cls : 'x-paging-position  btn-outline-secondary',
25169              disabled: true,
25170             html : this.beforePageText  +
25171                 '<input type="text" size="3" value="1" class="x-grid-page-number">' +
25172                 '<span class="x-paging-after">' +  String.format(this.afterPageText, 1) + '</span>'
25173          } ); //?? escaped?
25174         
25175         this.field = field.el.select('input', true).first();
25176         this.field.on("keydown", this.onPagingKeydown, this);
25177         this.field.on("focus", function(){this.dom.select();});
25178     
25179     
25180         this.afterTextEl =  field.el.select('.x-paging-after',true).first();
25181         //this.field.setHeight(18);
25182         //this.addSeparator();
25183         this.next = this.navgroup.addItem({
25184             tooltip: this.nextText,
25185             cls: "next btn-outline-secondary",
25186             html : ' <i class="fa fa-forward"></i>',
25187             disabled: true,
25188             preventDefault: true,
25189             listeners : { click :  this.onClick.createDelegate(this, ["next"]) }
25190         });
25191         this.last = this.navgroup.addItem({
25192             tooltip: this.lastText,
25193             html : ' <i class="fa fa-step-forward"></i>',
25194             cls: "next btn-outline-secondary",
25195             disabled: true,
25196             preventDefault: true,
25197             listeners : { click :  this.onClick.createDelegate(this, ["last"]) }
25198         });
25199     //this.addSeparator();
25200         this.loading = this.navgroup.addItem({
25201             tooltip: this.refreshText,
25202             cls: "btn-outline-secondary",
25203             html : ' <i class="fa fa-refresh"></i>',
25204             preventDefault: true,
25205             listeners : { click : this.onClick.createDelegate(this, ["refresh"]) }
25206         });
25207         
25208     },
25209
25210     // private
25211     updateInfo : function(){
25212         if(this.displayEl){
25213             var count = (typeof(this.getCount) == 'undefined') ? this.ds.getCount() : this.getCount();
25214             var msg = count == 0 ?
25215                 this.emptyMsg :
25216                 String.format(
25217                     this.displayMsg,
25218                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
25219                 );
25220             this.displayEl.update(msg);
25221         }
25222     },
25223
25224     // private
25225     onLoad : function(ds, r, o)
25226     {
25227         this.cursor = o.params.start ? o.params.start : 0;
25228         
25229         var d = this.getPageData(),
25230             ap = d.activePage,
25231             ps = d.pages;
25232         
25233         
25234         this.afterTextEl.dom.innerHTML = String.format(this.afterPageText, d.pages);
25235         this.field.dom.value = ap;
25236         this.first.setDisabled(ap == 1);
25237         this.prev.setDisabled(ap == 1);
25238         this.next.setDisabled(ap == ps);
25239         this.last.setDisabled(ap == ps);
25240         this.loading.enable();
25241         this.updateInfo();
25242     },
25243
25244     // private
25245     getPageData : function(){
25246         var total = this.ds.getTotalCount();
25247         return {
25248             total : total,
25249             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
25250             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
25251         };
25252     },
25253
25254     // private
25255     onLoadError : function(){
25256         this.loading.enable();
25257     },
25258
25259     // private
25260     onPagingKeydown : function(e){
25261         var k = e.getKey();
25262         var d = this.getPageData();
25263         if(k == e.RETURN){
25264             var v = this.field.dom.value, pageNum;
25265             if(!v || isNaN(pageNum = parseInt(v, 10))){
25266                 this.field.dom.value = d.activePage;
25267                 return;
25268             }
25269             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
25270             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
25271             e.stopEvent();
25272         }
25273         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))
25274         {
25275           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
25276           this.field.dom.value = pageNum;
25277           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
25278           e.stopEvent();
25279         }
25280         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
25281         {
25282           var v = this.field.dom.value, pageNum; 
25283           var increment = (e.shiftKey) ? 10 : 1;
25284           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
25285                 increment *= -1;
25286           }
25287           if(!v || isNaN(pageNum = parseInt(v, 10))) {
25288             this.field.dom.value = d.activePage;
25289             return;
25290           }
25291           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
25292           {
25293             this.field.dom.value = parseInt(v, 10) + increment;
25294             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
25295             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
25296           }
25297           e.stopEvent();
25298         }
25299     },
25300
25301     // private
25302     beforeLoad : function(){
25303         if(this.loading){
25304             this.loading.disable();
25305         }
25306     },
25307
25308     // private
25309     onClick : function(which){
25310         
25311         var ds = this.ds;
25312         if (!ds) {
25313             return;
25314         }
25315         
25316         switch(which){
25317             case "first":
25318                 ds.load({params:{start: 0, limit: this.pageSize}});
25319             break;
25320             case "prev":
25321                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
25322             break;
25323             case "next":
25324                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
25325             break;
25326             case "last":
25327                 var total = ds.getTotalCount();
25328                 var extra = total % this.pageSize;
25329                 var lastStart = extra ? (total - extra) : total-this.pageSize;
25330                 ds.load({params:{start: lastStart, limit: this.pageSize}});
25331             break;
25332             case "refresh":
25333                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
25334             break;
25335         }
25336     },
25337
25338     /**
25339      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
25340      * @param {Roo.data.Store} store The data store to unbind
25341      */
25342     unbind : function(ds){
25343         ds.un("beforeload", this.beforeLoad, this);
25344         ds.un("load", this.onLoad, this);
25345         ds.un("loadexception", this.onLoadError, this);
25346         ds.un("remove", this.updateInfo, this);
25347         ds.un("add", this.updateInfo, this);
25348         this.ds = undefined;
25349     },
25350
25351     /**
25352      * Binds the paging toolbar to the specified {@link Roo.data.Store}
25353      * @param {Roo.data.Store} store The data store to bind
25354      */
25355     bind : function(ds){
25356         ds.on("beforeload", this.beforeLoad, this);
25357         ds.on("load", this.onLoad, this);
25358         ds.on("loadexception", this.onLoadError, this);
25359         ds.on("remove", this.updateInfo, this);
25360         ds.on("add", this.updateInfo, this);
25361         this.ds = ds;
25362     }
25363 });/*
25364  * - LGPL
25365  *
25366  * element
25367  * 
25368  */
25369
25370 /**
25371  * @class Roo.bootstrap.MessageBar
25372  * @extends Roo.bootstrap.Component
25373  * Bootstrap MessageBar class
25374  * @cfg {String} html contents of the MessageBar
25375  * @cfg {String} weight (info | success | warning | danger) default info
25376  * @cfg {String} beforeClass insert the bar before the given class
25377  * @cfg {Boolean} closable (true | false) default false
25378  * @cfg {Boolean} fixed (true | false) default false, fix the bar at the top
25379  * 
25380  * @constructor
25381  * Create a new Element
25382  * @param {Object} config The config object
25383  */
25384
25385 Roo.bootstrap.MessageBar = function(config){
25386     Roo.bootstrap.MessageBar.superclass.constructor.call(this, config);
25387 };
25388
25389 Roo.extend(Roo.bootstrap.MessageBar, Roo.bootstrap.Component,  {
25390     
25391     html: '',
25392     weight: 'info',
25393     closable: false,
25394     fixed: false,
25395     beforeClass: 'bootstrap-sticky-wrap',
25396     
25397     getAutoCreate : function(){
25398         
25399         var cfg = {
25400             tag: 'div',
25401             cls: 'alert alert-dismissable alert-' + this.weight,
25402             cn: [
25403                 {
25404                     tag: 'span',
25405                     cls: 'message',
25406                     html: this.html || ''
25407                 }
25408             ]
25409         };
25410         
25411         if(this.fixed){
25412             cfg.cls += ' alert-messages-fixed';
25413         }
25414         
25415         if(this.closable){
25416             cfg.cn.push({
25417                 tag: 'button',
25418                 cls: 'close',
25419                 html: 'x'
25420             });
25421         }
25422         
25423         return cfg;
25424     },
25425     
25426     onRender : function(ct, position)
25427     {
25428         Roo.bootstrap.Component.superclass.onRender.call(this, ct, position);
25429         
25430         if(!this.el){
25431             var cfg = Roo.apply({},  this.getAutoCreate());
25432             cfg.id = Roo.id();
25433             
25434             if (this.cls) {
25435                 cfg.cls += ' ' + this.cls;
25436             }
25437             if (this.style) {
25438                 cfg.style = this.style;
25439             }
25440             this.el = Roo.get(document.body).createChild(cfg, Roo.select('.'+this.beforeClass, true).first());
25441             
25442             this.el.setVisibilityMode(Roo.Element.DISPLAY);
25443         }
25444         
25445         this.el.select('>button.close').on('click', this.hide, this);
25446         
25447     },
25448     
25449     show : function()
25450     {
25451         if (!this.rendered) {
25452             this.render();
25453         }
25454         
25455         this.el.show();
25456         
25457         this.fireEvent('show', this);
25458         
25459     },
25460     
25461     hide : function()
25462     {
25463         if (!this.rendered) {
25464             this.render();
25465         }
25466         
25467         this.el.hide();
25468         
25469         this.fireEvent('hide', this);
25470     },
25471     
25472     update : function()
25473     {
25474 //        var e = this.el.dom.firstChild;
25475 //        
25476 //        if(this.closable){
25477 //            e = e.nextSibling;
25478 //        }
25479 //        
25480 //        e.data = this.html || '';
25481
25482         this.el.select('>.message', true).first().dom.innerHTML = this.html || '';
25483     }
25484    
25485 });
25486
25487  
25488
25489      /*
25490  * - LGPL
25491  *
25492  * Graph
25493  * 
25494  */
25495
25496
25497 /**
25498  * @class Roo.bootstrap.Graph
25499  * @extends Roo.bootstrap.Component
25500  * Bootstrap Graph class
25501 > Prameters
25502  -sm {number} sm 4
25503  -md {number} md 5
25504  @cfg {String} graphtype  bar | vbar | pie
25505  @cfg {number} g_x coodinator | centre x (pie)
25506  @cfg {number} g_y coodinator | centre y (pie)
25507  @cfg {number} g_r radius (pie)
25508  @cfg {number} g_height height of the chart (respected by all elements in the set)
25509  @cfg {number} g_width width of the chart (respected by all elements in the set)
25510  @cfg {Object} title The title of the chart
25511     
25512  -{Array}  values
25513  -opts (object) options for the chart 
25514      o {
25515      o type (string) type of endings of the bar. Default: 'square'. Other options are: 'round', 'sharp', 'soft'.
25516      o gutter (number)(string) default '20%' (WHAT DOES IT DO?)
25517      o vgutter (number)
25518      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.
25519      o stacked (boolean) whether or not to tread values as in a stacked bar chart
25520      o to
25521      o stretch (boolean)
25522      o }
25523  -opts (object) options for the pie
25524      o{
25525      o cut
25526      o startAngle (number)
25527      o endAngle (number)
25528      } 
25529  *
25530  * @constructor
25531  * Create a new Input
25532  * @param {Object} config The config object
25533  */
25534
25535 Roo.bootstrap.Graph = function(config){
25536     Roo.bootstrap.Graph.superclass.constructor.call(this, config);
25537     
25538     this.addEvents({
25539         // img events
25540         /**
25541          * @event click
25542          * The img click event for the img.
25543          * @param {Roo.EventObject} e
25544          */
25545         "click" : true
25546     });
25547 };
25548
25549 Roo.extend(Roo.bootstrap.Graph, Roo.bootstrap.Component,  {
25550     
25551     sm: 4,
25552     md: 5,
25553     graphtype: 'bar',
25554     g_height: 250,
25555     g_width: 400,
25556     g_x: 50,
25557     g_y: 50,
25558     g_r: 30,
25559     opts:{
25560         //g_colors: this.colors,
25561         g_type: 'soft',
25562         g_gutter: '20%'
25563
25564     },
25565     title : false,
25566
25567     getAutoCreate : function(){
25568         
25569         var cfg = {
25570             tag: 'div',
25571             html : null
25572         };
25573         
25574         
25575         return  cfg;
25576     },
25577
25578     onRender : function(ct,position){
25579         
25580         
25581         Roo.bootstrap.Graph.superclass.onRender.call(this,ct,position);
25582         
25583         if (typeof(Raphael) == 'undefined') {
25584             Roo.bootstrap.MessageBox.alert("Error","Raphael is not availabe");
25585             return;
25586         }
25587         
25588         this.raphael = Raphael(this.el.dom);
25589         
25590                     // data1 = [[55, 20, 13, 32, 5, 1, 2, 10], [10, 2, 1, 5, 32, 13, 20, 55], [12, 20, 30]],
25591                     // data2 = [[55, 20, 13, 32, 5, 1, 2, 10], [10, 2, 1, 5, 32, 13, 20, 55], [12, 20, 30]],
25592                     // data3 = [[55, 20, 13, 32, 5, 1, 2, 10], [10, 2, 1, 5, 32, 13, 20, 55], [12, 20, 30]],
25593                     // txtattr = { font: "12px 'Fontin Sans', Fontin-Sans, sans-serif" };
25594                 /*
25595                 r.text(160, 10, "Single Series Chart").attr(txtattr);
25596                 r.text(480, 10, "Multiline Series Chart").attr(txtattr);
25597                 r.text(160, 250, "Multiple Series Stacked Chart").attr(txtattr);
25598                 r.text(480, 250, 'Multiline Series Stacked Vertical Chart. Type "round"').attr(txtattr);
25599                 
25600                 r.barchart(10, 10, 300, 220, [[55, 20, 13, 32, 5, 1, 2, 10]], 0, {type: "sharp"});
25601                 r.barchart(330, 10, 300, 220, data1);
25602                 r.barchart(10, 250, 300, 220, data2, {stacked: true});
25603                 r.barchart(330, 250, 300, 220, data3, {stacked: true, type: "round"});
25604                 */
25605                 
25606                 // var xdata = [55, 20, 13, 32, 5, 1, 2, 10,5 , 10];
25607                 // r.barchart(30, 30, 560, 250,  xdata, {
25608                 //    labels : [55, 20, 13, 32, 5, 1, 2, 10,5 , 10],
25609                 //     axis : "0 0 1 1",
25610                 //     axisxlabels :  xdata
25611                 //     //yvalues : cols,
25612                    
25613                 // });
25614 //        var xdata = [55, 20, 13, 32, 5, 1, 2, 10,5 , 10];
25615 //        
25616 //        this.load(null,xdata,{
25617 //                axis : "0 0 1 1",
25618 //                axisxlabels :  xdata
25619 //                });
25620
25621     },
25622
25623     load : function(graphtype,xdata,opts)
25624     {
25625         this.raphael.clear();
25626         if(!graphtype) {
25627             graphtype = this.graphtype;
25628         }
25629         if(!opts){
25630             opts = this.opts;
25631         }
25632         var r = this.raphael,
25633             fin = function () {
25634                 this.flag = r.popup(this.bar.x, this.bar.y, this.bar.value || "0").insertBefore(this);
25635             },
25636             fout = function () {
25637                 this.flag.animate({opacity: 0}, 300, function () {this.remove();});
25638             },
25639             pfin = function() {
25640                 this.sector.stop();
25641                 this.sector.scale(1.1, 1.1, this.cx, this.cy);
25642
25643                 if (this.label) {
25644                     this.label[0].stop();
25645                     this.label[0].attr({ r: 7.5 });
25646                     this.label[1].attr({ "font-weight": 800 });
25647                 }
25648             },
25649             pfout = function() {
25650                 this.sector.animate({ transform: 's1 1 ' + this.cx + ' ' + this.cy }, 500, "bounce");
25651
25652                 if (this.label) {
25653                     this.label[0].animate({ r: 5 }, 500, "bounce");
25654                     this.label[1].attr({ "font-weight": 400 });
25655                 }
25656             };
25657
25658         switch(graphtype){
25659             case 'bar':
25660                 this.raphael.barchart(this.g_x,this.g_y,this.g_width,this.g_height,xdata,opts).hover(fin,fout);
25661                 break;
25662             case 'hbar':
25663                 this.raphael.hbarchart(this.g_x,this.g_y,this.g_width,this.g_height,xdata,opts).hover(fin,fout);
25664                 break;
25665             case 'pie':
25666 //                opts = { legend: ["%% - Enterprise Users", "% - ddd","Chrome Users"], legendpos: "west", 
25667 //                href: ["http://raphaeljs.com", "http://g.raphaeljs.com"]};
25668 //            
25669                 this.raphael.piechart(this.g_x,this.g_y,this.g_r,xdata,opts).hover(pfin, pfout);
25670                 
25671                 break;
25672
25673         }
25674         
25675         if(this.title){
25676             this.raphael.text(this.title.x, this.title.y, this.title.text).attr(this.title.attr);
25677         }
25678         
25679     },
25680     
25681     setTitle: function(o)
25682     {
25683         this.title = o;
25684     },
25685     
25686     initEvents: function() {
25687         
25688         if(!this.href){
25689             this.el.on('click', this.onClick, this);
25690         }
25691     },
25692     
25693     onClick : function(e)
25694     {
25695         Roo.log('img onclick');
25696         this.fireEvent('click', this, e);
25697     }
25698    
25699 });
25700
25701  
25702 /*
25703  * - LGPL
25704  *
25705  * numberBox
25706  * 
25707  */
25708 Roo.bootstrap.dash = Roo.bootstrap.dash || {};
25709
25710 /**
25711  * @class Roo.bootstrap.dash.NumberBox
25712  * @extends Roo.bootstrap.Component
25713  * Bootstrap NumberBox class
25714  * @cfg {String} headline Box headline
25715  * @cfg {String} content Box content
25716  * @cfg {String} icon Box icon
25717  * @cfg {String} footer Footer text
25718  * @cfg {String} fhref Footer href
25719  * 
25720  * @constructor
25721  * Create a new NumberBox
25722  * @param {Object} config The config object
25723  */
25724
25725
25726 Roo.bootstrap.dash.NumberBox = function(config){
25727     Roo.bootstrap.dash.NumberBox.superclass.constructor.call(this, config);
25728     
25729 };
25730
25731 Roo.extend(Roo.bootstrap.dash.NumberBox, Roo.bootstrap.Component,  {
25732     
25733     headline : '',
25734     content : '',
25735     icon : '',
25736     footer : '',
25737     fhref : '',
25738     ficon : '',
25739     
25740     getAutoCreate : function(){
25741         
25742         var cfg = {
25743             tag : 'div',
25744             cls : 'small-box ',
25745             cn : [
25746                 {
25747                     tag : 'div',
25748                     cls : 'inner',
25749                     cn :[
25750                         {
25751                             tag : 'h3',
25752                             cls : 'roo-headline',
25753                             html : this.headline
25754                         },
25755                         {
25756                             tag : 'p',
25757                             cls : 'roo-content',
25758                             html : this.content
25759                         }
25760                     ]
25761                 }
25762             ]
25763         };
25764         
25765         if(this.icon){
25766             cfg.cn.push({
25767                 tag : 'div',
25768                 cls : 'icon',
25769                 cn :[
25770                     {
25771                         tag : 'i',
25772                         cls : 'ion ' + this.icon
25773                     }
25774                 ]
25775             });
25776         }
25777         
25778         if(this.footer){
25779             var footer = {
25780                 tag : 'a',
25781                 cls : 'small-box-footer',
25782                 href : this.fhref || '#',
25783                 html : this.footer
25784             };
25785             
25786             cfg.cn.push(footer);
25787             
25788         }
25789         
25790         return  cfg;
25791     },
25792
25793     onRender : function(ct,position){
25794         Roo.bootstrap.dash.NumberBox.superclass.onRender.call(this,ct,position);
25795
25796
25797        
25798                 
25799     },
25800
25801     setHeadline: function (value)
25802     {
25803         this.el.select('.roo-headline',true).first().dom.innerHTML = value;
25804     },
25805     
25806     setFooter: function (value, href)
25807     {
25808         this.el.select('a.small-box-footer',true).first().dom.innerHTML = value;
25809         
25810         if(href){
25811             this.el.select('a.small-box-footer',true).first().attr('href', href);
25812         }
25813         
25814     },
25815
25816     setContent: function (value)
25817     {
25818         this.el.select('.roo-content',true).first().dom.innerHTML = value;
25819     },
25820
25821     initEvents: function() 
25822     {   
25823         
25824     }
25825     
25826 });
25827
25828  
25829 /*
25830  * - LGPL
25831  *
25832  * TabBox
25833  * 
25834  */
25835 Roo.bootstrap.dash = Roo.bootstrap.dash || {};
25836
25837 /**
25838  * @class Roo.bootstrap.dash.TabBox
25839  * @extends Roo.bootstrap.Component
25840  * Bootstrap TabBox class
25841  * @cfg {String} title Title of the TabBox
25842  * @cfg {String} icon Icon of the TabBox
25843  * @cfg {Boolean} showtabs (true|false) show the tabs default true
25844  * @cfg {Boolean} tabScrollable (true|false) tab scrollable when mobile view default false
25845  * 
25846  * @constructor
25847  * Create a new TabBox
25848  * @param {Object} config The config object
25849  */
25850
25851
25852 Roo.bootstrap.dash.TabBox = function(config){
25853     Roo.bootstrap.dash.TabBox.superclass.constructor.call(this, config);
25854     this.addEvents({
25855         // raw events
25856         /**
25857          * @event addpane
25858          * When a pane is added
25859          * @param {Roo.bootstrap.dash.TabPane} pane
25860          */
25861         "addpane" : true,
25862         /**
25863          * @event activatepane
25864          * When a pane is activated
25865          * @param {Roo.bootstrap.dash.TabPane} pane
25866          */
25867         "activatepane" : true
25868         
25869          
25870     });
25871     
25872     this.panes = [];
25873 };
25874
25875 Roo.extend(Roo.bootstrap.dash.TabBox, Roo.bootstrap.Component,  {
25876
25877     title : '',
25878     icon : false,
25879     showtabs : true,
25880     tabScrollable : false,
25881     
25882     getChildContainer : function()
25883     {
25884         return this.el.select('.tab-content', true).first();
25885     },
25886     
25887     getAutoCreate : function(){
25888         
25889         var header = {
25890             tag: 'li',
25891             cls: 'pull-left header',
25892             html: this.title,
25893             cn : []
25894         };
25895         
25896         if(this.icon){
25897             header.cn.push({
25898                 tag: 'i',
25899                 cls: 'fa ' + this.icon
25900             });
25901         }
25902         
25903         var h = {
25904             tag: 'ul',
25905             cls: 'nav nav-tabs pull-right',
25906             cn: [
25907                 header
25908             ]
25909         };
25910         
25911         if(this.tabScrollable){
25912             h = {
25913                 tag: 'div',
25914                 cls: 'tab-header',
25915                 cn: [
25916                     {
25917                         tag: 'ul',
25918                         cls: 'nav nav-tabs pull-right',
25919                         cn: [
25920                             header
25921                         ]
25922                     }
25923                 ]
25924             };
25925         }
25926         
25927         var cfg = {
25928             tag: 'div',
25929             cls: 'nav-tabs-custom',
25930             cn: [
25931                 h,
25932                 {
25933                     tag: 'div',
25934                     cls: 'tab-content no-padding',
25935                     cn: []
25936                 }
25937             ]
25938         };
25939
25940         return  cfg;
25941     },
25942     initEvents : function()
25943     {
25944         //Roo.log('add add pane handler');
25945         this.on('addpane', this.onAddPane, this);
25946     },
25947      /**
25948      * Updates the box title
25949      * @param {String} html to set the title to.
25950      */
25951     setTitle : function(value)
25952     {
25953         this.el.select('.nav-tabs .header', true).first().dom.innerHTML = value;
25954     },
25955     onAddPane : function(pane)
25956     {
25957         this.panes.push(pane);
25958         //Roo.log('addpane');
25959         //Roo.log(pane);
25960         // tabs are rendere left to right..
25961         if(!this.showtabs){
25962             return;
25963         }
25964         
25965         var ctr = this.el.select('.nav-tabs', true).first();
25966          
25967          
25968         var existing = ctr.select('.nav-tab',true);
25969         var qty = existing.getCount();;
25970         
25971         
25972         var tab = ctr.createChild({
25973             tag : 'li',
25974             cls : 'nav-tab' + (qty ? '' : ' active'),
25975             cn : [
25976                 {
25977                     tag : 'a',
25978                     href:'#',
25979                     html : pane.title
25980                 }
25981             ]
25982         }, qty ? existing.first().dom : ctr.select('.header', true).first().dom );
25983         pane.tab = tab;
25984         
25985         tab.on('click', this.onTabClick.createDelegate(this, [pane], true));
25986         if (!qty) {
25987             pane.el.addClass('active');
25988         }
25989         
25990                 
25991     },
25992     onTabClick : function(ev,un,ob,pane)
25993     {
25994         //Roo.log('tab - prev default');
25995         ev.preventDefault();
25996         
25997         
25998         this.el.select('.nav-tabs li.nav-tab', true).removeClass('active');
25999         pane.tab.addClass('active');
26000         //Roo.log(pane.title);
26001         this.getChildContainer().select('.tab-pane',true).removeClass('active');
26002         // technically we should have a deactivate event.. but maybe add later.
26003         // and it should not de-activate the selected tab...
26004         this.fireEvent('activatepane', pane);
26005         pane.el.addClass('active');
26006         pane.fireEvent('activate');
26007         
26008         
26009     },
26010     
26011     getActivePane : function()
26012     {
26013         var r = false;
26014         Roo.each(this.panes, function(p) {
26015             if(p.el.hasClass('active')){
26016                 r = p;
26017                 return false;
26018             }
26019             
26020             return;
26021         });
26022         
26023         return r;
26024     }
26025     
26026     
26027 });
26028
26029  
26030 /*
26031  * - LGPL
26032  *
26033  * Tab pane
26034  * 
26035  */
26036 Roo.bootstrap.dash = Roo.bootstrap.dash || {};
26037 /**
26038  * @class Roo.bootstrap.TabPane
26039  * @extends Roo.bootstrap.Component
26040  * Bootstrap TabPane class
26041  * @cfg {Boolean} active (false | true) Default false
26042  * @cfg {String} title title of panel
26043
26044  * 
26045  * @constructor
26046  * Create a new TabPane
26047  * @param {Object} config The config object
26048  */
26049
26050 Roo.bootstrap.dash.TabPane = function(config){
26051     Roo.bootstrap.dash.TabPane.superclass.constructor.call(this, config);
26052     
26053     this.addEvents({
26054         // raw events
26055         /**
26056          * @event activate
26057          * When a pane is activated
26058          * @param {Roo.bootstrap.dash.TabPane} pane
26059          */
26060         "activate" : true
26061          
26062     });
26063 };
26064
26065 Roo.extend(Roo.bootstrap.dash.TabPane, Roo.bootstrap.Component,  {
26066     
26067     active : false,
26068     title : '',
26069     
26070     // the tabBox that this is attached to.
26071     tab : false,
26072      
26073     getAutoCreate : function() 
26074     {
26075         var cfg = {
26076             tag: 'div',
26077             cls: 'tab-pane'
26078         };
26079         
26080         if(this.active){
26081             cfg.cls += ' active';
26082         }
26083         
26084         return cfg;
26085     },
26086     initEvents  : function()
26087     {
26088         //Roo.log('trigger add pane handler');
26089         this.parent().fireEvent('addpane', this)
26090     },
26091     
26092      /**
26093      * Updates the tab title 
26094      * @param {String} html to set the title to.
26095      */
26096     setTitle: function(str)
26097     {
26098         if (!this.tab) {
26099             return;
26100         }
26101         this.title = str;
26102         this.tab.select('a', true).first().dom.innerHTML = str;
26103         
26104     }
26105     
26106     
26107     
26108 });
26109
26110  
26111
26112
26113  /*
26114  * - LGPL
26115  *
26116  * menu
26117  * 
26118  */
26119 Roo.bootstrap.menu = Roo.bootstrap.menu || {};
26120
26121 /**
26122  * @class Roo.bootstrap.menu.Menu
26123  * @extends Roo.bootstrap.Component
26124  * Bootstrap Menu class - container for Menu
26125  * @cfg {String} html Text of the menu
26126  * @cfg {String} weight (default | primary | success | info | warning | danger | inverse)
26127  * @cfg {String} icon Font awesome icon
26128  * @cfg {String} pos Menu align to (top | bottom) default bottom
26129  * 
26130  * 
26131  * @constructor
26132  * Create a new Menu
26133  * @param {Object} config The config object
26134  */
26135
26136
26137 Roo.bootstrap.menu.Menu = function(config){
26138     Roo.bootstrap.menu.Menu.superclass.constructor.call(this, config);
26139     
26140     this.addEvents({
26141         /**
26142          * @event beforeshow
26143          * Fires before this menu is displayed
26144          * @param {Roo.bootstrap.menu.Menu} this
26145          */
26146         beforeshow : true,
26147         /**
26148          * @event beforehide
26149          * Fires before this menu is hidden
26150          * @param {Roo.bootstrap.menu.Menu} this
26151          */
26152         beforehide : true,
26153         /**
26154          * @event show
26155          * Fires after this menu is displayed
26156          * @param {Roo.bootstrap.menu.Menu} this
26157          */
26158         show : true,
26159         /**
26160          * @event hide
26161          * Fires after this menu is hidden
26162          * @param {Roo.bootstrap.menu.Menu} this
26163          */
26164         hide : true,
26165         /**
26166          * @event click
26167          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
26168          * @param {Roo.bootstrap.menu.Menu} this
26169          * @param {Roo.EventObject} e
26170          */
26171         click : true
26172     });
26173     
26174 };
26175
26176 Roo.extend(Roo.bootstrap.menu.Menu, Roo.bootstrap.Component,  {
26177     
26178     submenu : false,
26179     html : '',
26180     weight : 'default',
26181     icon : false,
26182     pos : 'bottom',
26183     
26184     
26185     getChildContainer : function() {
26186         if(this.isSubMenu){
26187             return this.el;
26188         }
26189         
26190         return this.el.select('ul.dropdown-menu', true).first();  
26191     },
26192     
26193     getAutoCreate : function()
26194     {
26195         var text = [
26196             {
26197                 tag : 'span',
26198                 cls : 'roo-menu-text',
26199                 html : this.html
26200             }
26201         ];
26202         
26203         if(this.icon){
26204             text.unshift({
26205                 tag : 'i',
26206                 cls : 'fa ' + this.icon
26207             })
26208         }
26209         
26210         
26211         var cfg = {
26212             tag : 'div',
26213             cls : 'btn-group',
26214             cn : [
26215                 {
26216                     tag : 'button',
26217                     cls : 'dropdown-button btn btn-' + this.weight,
26218                     cn : text
26219                 },
26220                 {
26221                     tag : 'button',
26222                     cls : 'dropdown-toggle btn btn-' + this.weight,
26223                     cn : [
26224                         {
26225                             tag : 'span',
26226                             cls : 'caret'
26227                         }
26228                     ]
26229                 },
26230                 {
26231                     tag : 'ul',
26232                     cls : 'dropdown-menu'
26233                 }
26234             ]
26235             
26236         };
26237         
26238         if(this.pos == 'top'){
26239             cfg.cls += ' dropup';
26240         }
26241         
26242         if(this.isSubMenu){
26243             cfg = {
26244                 tag : 'ul',
26245                 cls : 'dropdown-menu'
26246             }
26247         }
26248         
26249         return cfg;
26250     },
26251     
26252     onRender : function(ct, position)
26253     {
26254         this.isSubMenu = ct.hasClass('dropdown-submenu');
26255         
26256         Roo.bootstrap.menu.Menu.superclass.onRender.call(this, ct, position);
26257     },
26258     
26259     initEvents : function() 
26260     {
26261         if(this.isSubMenu){
26262             return;
26263         }
26264         
26265         this.hidden = true;
26266         
26267         this.triggerEl = this.el.select('button.dropdown-toggle', true).first();
26268         this.triggerEl.on('click', this.onTriggerPress, this);
26269         
26270         this.buttonEl = this.el.select('button.dropdown-button', true).first();
26271         this.buttonEl.on('click', this.onClick, this);
26272         
26273     },
26274     
26275     list : function()
26276     {
26277         if(this.isSubMenu){
26278             return this.el;
26279         }
26280         
26281         return this.el.select('ul.dropdown-menu', true).first();
26282     },
26283     
26284     onClick : function(e)
26285     {
26286         this.fireEvent("click", this, e);
26287     },
26288     
26289     onTriggerPress  : function(e)
26290     {   
26291         if (this.isVisible()) {
26292             this.hide();
26293         } else {
26294             this.show();
26295         }
26296     },
26297     
26298     isVisible : function(){
26299         return !this.hidden;
26300     },
26301     
26302     show : function()
26303     {
26304         this.fireEvent("beforeshow", this);
26305         
26306         this.hidden = false;
26307         this.el.addClass('open');
26308         
26309         Roo.get(document).on("mouseup", this.onMouseUp, this);
26310         
26311         this.fireEvent("show", this);
26312         
26313         
26314     },
26315     
26316     hide : function()
26317     {
26318         this.fireEvent("beforehide", this);
26319         
26320         this.hidden = true;
26321         this.el.removeClass('open');
26322         
26323         Roo.get(document).un("mouseup", this.onMouseUp);
26324         
26325         this.fireEvent("hide", this);
26326     },
26327     
26328     onMouseUp : function()
26329     {
26330         this.hide();
26331     }
26332     
26333 });
26334
26335  
26336  /*
26337  * - LGPL
26338  *
26339  * menu item
26340  * 
26341  */
26342 Roo.bootstrap.menu = Roo.bootstrap.menu || {};
26343
26344 /**
26345  * @class Roo.bootstrap.menu.Item
26346  * @extends Roo.bootstrap.Component
26347  * Bootstrap MenuItem class
26348  * @cfg {Boolean} submenu (true | false) default false
26349  * @cfg {String} html text of the item
26350  * @cfg {String} href the link
26351  * @cfg {Boolean} disable (true | false) default false
26352  * @cfg {Boolean} preventDefault (true | false) default true
26353  * @cfg {String} icon Font awesome icon
26354  * @cfg {String} pos Submenu align to (left | right) default right 
26355  * 
26356  * 
26357  * @constructor
26358  * Create a new Item
26359  * @param {Object} config The config object
26360  */
26361
26362
26363 Roo.bootstrap.menu.Item = function(config){
26364     Roo.bootstrap.menu.Item.superclass.constructor.call(this, config);
26365     this.addEvents({
26366         /**
26367          * @event mouseover
26368          * Fires when the mouse is hovering over this menu
26369          * @param {Roo.bootstrap.menu.Item} this
26370          * @param {Roo.EventObject} e
26371          */
26372         mouseover : true,
26373         /**
26374          * @event mouseout
26375          * Fires when the mouse exits this menu
26376          * @param {Roo.bootstrap.menu.Item} this
26377          * @param {Roo.EventObject} e
26378          */
26379         mouseout : true,
26380         // raw events
26381         /**
26382          * @event click
26383          * The raw click event for the entire grid.
26384          * @param {Roo.EventObject} e
26385          */
26386         click : true
26387     });
26388 };
26389
26390 Roo.extend(Roo.bootstrap.menu.Item, Roo.bootstrap.Component,  {
26391     
26392     submenu : false,
26393     href : '',
26394     html : '',
26395     preventDefault: true,
26396     disable : false,
26397     icon : false,
26398     pos : 'right',
26399     
26400     getAutoCreate : function()
26401     {
26402         var text = [
26403             {
26404                 tag : 'span',
26405                 cls : 'roo-menu-item-text',
26406                 html : this.html
26407             }
26408         ];
26409         
26410         if(this.icon){
26411             text.unshift({
26412                 tag : 'i',
26413                 cls : 'fa ' + this.icon
26414             })
26415         }
26416         
26417         var cfg = {
26418             tag : 'li',
26419             cn : [
26420                 {
26421                     tag : 'a',
26422                     href : this.href || '#',
26423                     cn : text
26424                 }
26425             ]
26426         };
26427         
26428         if(this.disable){
26429             cfg.cls = (typeof(cfg.cls) == 'undefined') ? 'disabled' : (cfg.cls + ' disabled');
26430         }
26431         
26432         if(this.submenu){
26433             cfg.cls = (typeof(cfg.cls) == 'undefined') ? 'dropdown-submenu' : (cfg.cls + ' dropdown-submenu');
26434             
26435             if(this.pos == 'left'){
26436                 cfg.cls = (typeof(cfg.cls) == 'undefined') ? 'pull-left' : (cfg.cls + ' pull-left');
26437             }
26438         }
26439         
26440         return cfg;
26441     },
26442     
26443     initEvents : function() 
26444     {
26445         this.el.on('mouseover', this.onMouseOver, this);
26446         this.el.on('mouseout', this.onMouseOut, this);
26447         
26448         this.el.select('a', true).first().on('click', this.onClick, this);
26449         
26450     },
26451     
26452     onClick : function(e)
26453     {
26454         if(this.preventDefault){
26455             e.preventDefault();
26456         }
26457         
26458         this.fireEvent("click", this, e);
26459     },
26460     
26461     onMouseOver : function(e)
26462     {
26463         if(this.submenu && this.pos == 'left'){
26464             this.el.select('ul.dropdown-menu', true).first().setLeft(this.el.select('ul.dropdown-menu', true).first().getWidth() * -1);
26465         }
26466         
26467         this.fireEvent("mouseover", this, e);
26468     },
26469     
26470     onMouseOut : function(e)
26471     {
26472         this.fireEvent("mouseout", this, e);
26473     }
26474 });
26475
26476  
26477
26478  /*
26479  * - LGPL
26480  *
26481  * menu separator
26482  * 
26483  */
26484 Roo.bootstrap.menu = Roo.bootstrap.menu || {};
26485
26486 /**
26487  * @class Roo.bootstrap.menu.Separator
26488  * @extends Roo.bootstrap.Component
26489  * Bootstrap Separator class
26490  * 
26491  * @constructor
26492  * Create a new Separator
26493  * @param {Object} config The config object
26494  */
26495
26496
26497 Roo.bootstrap.menu.Separator = function(config){
26498     Roo.bootstrap.menu.Separator.superclass.constructor.call(this, config);
26499 };
26500
26501 Roo.extend(Roo.bootstrap.menu.Separator, Roo.bootstrap.Component,  {
26502     
26503     getAutoCreate : function(){
26504         var cfg = {
26505             tag : 'li',
26506             cls: 'divider'
26507         };
26508         
26509         return cfg;
26510     }
26511    
26512 });
26513
26514  
26515
26516  /*
26517  * - LGPL
26518  *
26519  * Tooltip
26520  * 
26521  */
26522
26523 /**
26524  * @class Roo.bootstrap.Tooltip
26525  * Bootstrap Tooltip class
26526  * This is basic at present - all componets support it by default, however they should add tooltipEl() method
26527  * to determine which dom element triggers the tooltip.
26528  * 
26529  * It needs to add support for additional attributes like tooltip-position
26530  * 
26531  * @constructor
26532  * Create a new Toolti
26533  * @param {Object} config The config object
26534  */
26535
26536 Roo.bootstrap.Tooltip = function(config){
26537     Roo.bootstrap.Tooltip.superclass.constructor.call(this, config);
26538     
26539     this.alignment = Roo.bootstrap.Tooltip.alignment;
26540     
26541     if(typeof(config) != 'undefined' && typeof(config.alignment) != 'undefined'){
26542         this.alignment = config.alignment;
26543     }
26544     
26545 };
26546
26547 Roo.apply(Roo.bootstrap.Tooltip, {
26548     /**
26549      * @function init initialize tooltip monitoring.
26550      * @static
26551      */
26552     currentEl : false,
26553     currentTip : false,
26554     currentRegion : false,
26555     
26556     //  init : delay?
26557     
26558     init : function()
26559     {
26560         Roo.get(document).on('mouseover', this.enter ,this);
26561         Roo.get(document).on('mouseout', this.leave, this);
26562          
26563         
26564         this.currentTip = new Roo.bootstrap.Tooltip();
26565     },
26566     
26567     enter : function(ev)
26568     {
26569         var dom = ev.getTarget();
26570         
26571         //Roo.log(['enter',dom]);
26572         var el = Roo.fly(dom);
26573         if (this.currentEl) {
26574             //Roo.log(dom);
26575             //Roo.log(this.currentEl);
26576             //Roo.log(this.currentEl.contains(dom));
26577             if (this.currentEl == el) {
26578                 return;
26579             }
26580             if (dom != this.currentEl.dom && this.currentEl.contains(dom)) {
26581                 return;
26582             }
26583
26584         }
26585         
26586         if (this.currentTip.el) {
26587             this.currentTip.el.setVisibilityMode(Roo.Element.DISPLAY).hide(); // force hiding...
26588         }    
26589         //Roo.log(ev);
26590         
26591         if(!el || el.dom == document){
26592             return;
26593         }
26594         
26595         var bindEl = el;
26596         
26597         // you can not look for children, as if el is the body.. then everythign is the child..
26598         if (!el.attr('tooltip')) { //
26599             if (!el.select("[tooltip]").elements.length) {
26600                 return;
26601             }
26602             // is the mouse over this child...?
26603             bindEl = el.select("[tooltip]").first();
26604             var xy = ev.getXY();
26605             if (!bindEl.getRegion().contains( { top : xy[1] ,right : xy[0] , bottom : xy[1], left : xy[0]})) {
26606                 //Roo.log("not in region.");
26607                 return;
26608             }
26609             //Roo.log("child element over..");
26610             
26611         }
26612         this.currentEl = bindEl;
26613         this.currentTip.bind(bindEl);
26614         this.currentRegion = Roo.lib.Region.getRegion(dom);
26615         this.currentTip.enter();
26616         
26617     },
26618     leave : function(ev)
26619     {
26620         var dom = ev.getTarget();
26621         //Roo.log(['leave',dom]);
26622         if (!this.currentEl) {
26623             return;
26624         }
26625         
26626         
26627         if (dom != this.currentEl.dom) {
26628             return;
26629         }
26630         var xy = ev.getXY();
26631         if (this.currentRegion.contains( new Roo.lib.Region( xy[1], xy[0] ,xy[1], xy[0]  ))) {
26632             return;
26633         }
26634         // only activate leave if mouse cursor is outside... bounding box..
26635         
26636         
26637         
26638         
26639         if (this.currentTip) {
26640             this.currentTip.leave();
26641         }
26642         //Roo.log('clear currentEl');
26643         this.currentEl = false;
26644         
26645         
26646     },
26647     alignment : {
26648         'left' : ['r-l', [-2,0], 'right'],
26649         'right' : ['l-r', [2,0], 'left'],
26650         'bottom' : ['t-b', [0,2], 'top'],
26651         'top' : [ 'b-t', [0,-2], 'bottom']
26652     }
26653     
26654 });
26655
26656
26657 Roo.extend(Roo.bootstrap.Tooltip, Roo.bootstrap.Component,  {
26658     
26659     
26660     bindEl : false,
26661     
26662     delay : null, // can be { show : 300 , hide: 500}
26663     
26664     timeout : null,
26665     
26666     hoverState : null, //???
26667     
26668     placement : 'bottom', 
26669     
26670     alignment : false,
26671     
26672     getAutoCreate : function(){
26673     
26674         var cfg = {
26675            cls : 'tooltip',
26676            role : 'tooltip',
26677            cn : [
26678                 {
26679                     cls : 'tooltip-arrow'
26680                 },
26681                 {
26682                     cls : 'tooltip-inner'
26683                 }
26684            ]
26685         };
26686         
26687         return cfg;
26688     },
26689     bind : function(el)
26690     {
26691         this.bindEl = el;
26692     },
26693       
26694     
26695     enter : function () {
26696        
26697         if (this.timeout != null) {
26698             clearTimeout(this.timeout);
26699         }
26700         
26701         this.hoverState = 'in';
26702          //Roo.log("enter - show");
26703         if (!this.delay || !this.delay.show) {
26704             this.show();
26705             return;
26706         }
26707         var _t = this;
26708         this.timeout = setTimeout(function () {
26709             if (_t.hoverState == 'in') {
26710                 _t.show();
26711             }
26712         }, this.delay.show);
26713     },
26714     leave : function()
26715     {
26716         clearTimeout(this.timeout);
26717     
26718         this.hoverState = 'out';
26719          if (!this.delay || !this.delay.hide) {
26720             this.hide();
26721             return;
26722         }
26723        
26724         var _t = this;
26725         this.timeout = setTimeout(function () {
26726             //Roo.log("leave - timeout");
26727             
26728             if (_t.hoverState == 'out') {
26729                 _t.hide();
26730                 Roo.bootstrap.Tooltip.currentEl = false;
26731             }
26732         }, delay);
26733     },
26734     
26735     show : function (msg)
26736     {
26737         if (!this.el) {
26738             this.render(document.body);
26739         }
26740         // set content.
26741         //Roo.log([this.bindEl, this.bindEl.attr('tooltip')]);
26742         
26743         var tip = msg || this.bindEl.attr('tooltip') || this.bindEl.select("[tooltip]").first().attr('tooltip');
26744         
26745         this.el.select('.tooltip-inner',true).first().dom.innerHTML = tip;
26746         
26747         this.el.removeClass(['fade','top','bottom', 'left', 'right','in']);
26748         
26749         var placement = typeof this.placement == 'function' ?
26750             this.placement.call(this, this.el, on_el) :
26751             this.placement;
26752             
26753         var autoToken = /\s?auto?\s?/i;
26754         var autoPlace = autoToken.test(placement);
26755         if (autoPlace) {
26756             placement = placement.replace(autoToken, '') || 'top';
26757         }
26758         
26759         //this.el.detach()
26760         //this.el.setXY([0,0]);
26761         this.el.show();
26762         //this.el.dom.style.display='block';
26763         
26764         //this.el.appendTo(on_el);
26765         
26766         var p = this.getPosition();
26767         var box = this.el.getBox();
26768         
26769         if (autoPlace) {
26770             // fixme..
26771         }
26772         
26773         var align = this.alignment[placement];
26774         
26775         var xy = this.el.getAlignToXY(this.bindEl, align[0], align[1]);
26776         
26777         if(placement == 'top' || placement == 'bottom'){
26778             if(xy[0] < 0){
26779                 placement = 'right';
26780             }
26781             
26782             if(xy[0] + this.el.getWidth() > Roo.lib.Dom.getViewWidth()){
26783                 placement = 'left';
26784             }
26785             
26786             var scroll = Roo.select('body', true).first().getScroll();
26787             
26788             if(xy[1] > Roo.lib.Dom.getViewHeight() + scroll.top - this.el.getHeight()){
26789                 placement = 'top';
26790             }
26791             
26792             align = this.alignment[placement];
26793         }
26794         
26795         this.el.alignTo(this.bindEl, align[0],align[1]);
26796         //var arrow = this.el.select('.arrow',true).first();
26797         //arrow.set(align[2], 
26798         
26799         this.el.addClass(placement);
26800         
26801         this.el.addClass('in fade');
26802         
26803         this.hoverState = null;
26804         
26805         if (this.el.hasClass('fade')) {
26806             // fade it?
26807         }
26808         
26809     },
26810     hide : function()
26811     {
26812          
26813         if (!this.el) {
26814             return;
26815         }
26816         //this.el.setXY([0,0]);
26817         this.el.removeClass('in');
26818         //this.el.hide();
26819         
26820     }
26821     
26822 });
26823  
26824
26825  /*
26826  * - LGPL
26827  *
26828  * Location Picker
26829  * 
26830  */
26831
26832 /**
26833  * @class Roo.bootstrap.LocationPicker
26834  * @extends Roo.bootstrap.Component
26835  * Bootstrap LocationPicker class
26836  * @cfg {Number} latitude Position when init default 0
26837  * @cfg {Number} longitude Position when init default 0
26838  * @cfg {Number} zoom default 15
26839  * @cfg {String} mapTypeId default google.maps.MapTypeId.ROADMAP
26840  * @cfg {Boolean} mapTypeControl default false
26841  * @cfg {Boolean} disableDoubleClickZoom default false
26842  * @cfg {Boolean} scrollwheel default true
26843  * @cfg {Boolean} streetViewControl default false
26844  * @cfg {Number} radius default 0
26845  * @cfg {String} locationName
26846  * @cfg {Boolean} draggable default true
26847  * @cfg {Boolean} enableAutocomplete default false
26848  * @cfg {Boolean} enableReverseGeocode default true
26849  * @cfg {String} markerTitle
26850  * 
26851  * @constructor
26852  * Create a new LocationPicker
26853  * @param {Object} config The config object
26854  */
26855
26856
26857 Roo.bootstrap.LocationPicker = function(config){
26858     
26859     Roo.bootstrap.LocationPicker.superclass.constructor.call(this, config);
26860     
26861     this.addEvents({
26862         /**
26863          * @event initial
26864          * Fires when the picker initialized.
26865          * @param {Roo.bootstrap.LocationPicker} this
26866          * @param {Google Location} location
26867          */
26868         initial : true,
26869         /**
26870          * @event positionchanged
26871          * Fires when the picker position changed.
26872          * @param {Roo.bootstrap.LocationPicker} this
26873          * @param {Google Location} location
26874          */
26875         positionchanged : true,
26876         /**
26877          * @event resize
26878          * Fires when the map resize.
26879          * @param {Roo.bootstrap.LocationPicker} this
26880          */
26881         resize : true,
26882         /**
26883          * @event show
26884          * Fires when the map show.
26885          * @param {Roo.bootstrap.LocationPicker} this
26886          */
26887         show : true,
26888         /**
26889          * @event hide
26890          * Fires when the map hide.
26891          * @param {Roo.bootstrap.LocationPicker} this
26892          */
26893         hide : true,
26894         /**
26895          * @event mapClick
26896          * Fires when click the map.
26897          * @param {Roo.bootstrap.LocationPicker} this
26898          * @param {Map event} e
26899          */
26900         mapClick : true,
26901         /**
26902          * @event mapRightClick
26903          * Fires when right click the map.
26904          * @param {Roo.bootstrap.LocationPicker} this
26905          * @param {Map event} e
26906          */
26907         mapRightClick : true,
26908         /**
26909          * @event markerClick
26910          * Fires when click the marker.
26911          * @param {Roo.bootstrap.LocationPicker} this
26912          * @param {Map event} e
26913          */
26914         markerClick : true,
26915         /**
26916          * @event markerRightClick
26917          * Fires when right click the marker.
26918          * @param {Roo.bootstrap.LocationPicker} this
26919          * @param {Map event} e
26920          */
26921         markerRightClick : true,
26922         /**
26923          * @event OverlayViewDraw
26924          * Fires when OverlayView Draw
26925          * @param {Roo.bootstrap.LocationPicker} this
26926          */
26927         OverlayViewDraw : true,
26928         /**
26929          * @event OverlayViewOnAdd
26930          * Fires when OverlayView Draw
26931          * @param {Roo.bootstrap.LocationPicker} this
26932          */
26933         OverlayViewOnAdd : true,
26934         /**
26935          * @event OverlayViewOnRemove
26936          * Fires when OverlayView Draw
26937          * @param {Roo.bootstrap.LocationPicker} this
26938          */
26939         OverlayViewOnRemove : true,
26940         /**
26941          * @event OverlayViewShow
26942          * Fires when OverlayView Draw
26943          * @param {Roo.bootstrap.LocationPicker} this
26944          * @param {Pixel} cpx
26945          */
26946         OverlayViewShow : true,
26947         /**
26948          * @event OverlayViewHide
26949          * Fires when OverlayView Draw
26950          * @param {Roo.bootstrap.LocationPicker} this
26951          */
26952         OverlayViewHide : true,
26953         /**
26954          * @event loadexception
26955          * Fires when load google lib failed.
26956          * @param {Roo.bootstrap.LocationPicker} this
26957          */
26958         loadexception : true
26959     });
26960         
26961 };
26962
26963 Roo.extend(Roo.bootstrap.LocationPicker, Roo.bootstrap.Component,  {
26964     
26965     gMapContext: false,
26966     
26967     latitude: 0,
26968     longitude: 0,
26969     zoom: 15,
26970     mapTypeId: false,
26971     mapTypeControl: false,
26972     disableDoubleClickZoom: false,
26973     scrollwheel: true,
26974     streetViewControl: false,
26975     radius: 0,
26976     locationName: '',
26977     draggable: true,
26978     enableAutocomplete: false,
26979     enableReverseGeocode: true,
26980     markerTitle: '',
26981     
26982     getAutoCreate: function()
26983     {
26984
26985         var cfg = {
26986             tag: 'div',
26987             cls: 'roo-location-picker'
26988         };
26989         
26990         return cfg
26991     },
26992     
26993     initEvents: function(ct, position)
26994     {       
26995         if(!this.el.getWidth() || this.isApplied()){
26996             return;
26997         }
26998         
26999         this.el.setVisibilityMode(Roo.Element.DISPLAY);
27000         
27001         this.initial();
27002     },
27003     
27004     initial: function()
27005     {
27006         if(typeof(google) == 'undefined' || typeof(google.maps) == 'undefined'){
27007             this.fireEvent('loadexception', this);
27008             return;
27009         }
27010         
27011         if(!this.mapTypeId){
27012             this.mapTypeId = google.maps.MapTypeId.ROADMAP;
27013         }
27014         
27015         this.gMapContext = this.GMapContext();
27016         
27017         this.initOverlayView();
27018         
27019         this.OverlayView = new Roo.bootstrap.LocationPicker.OverlayView(this.gMapContext.map);
27020         
27021         var _this = this;
27022                 
27023         google.maps.event.addListener(this.gMapContext.marker, "dragend", function(event) {
27024             _this.setPosition(_this.gMapContext.marker.position);
27025         });
27026         
27027         google.maps.event.addListener(this.gMapContext.map, 'click', function(event){
27028             _this.fireEvent('mapClick', this, event);
27029             
27030         });
27031
27032         google.maps.event.addListener(this.gMapContext.map, 'rightclick', function(event){
27033             _this.fireEvent('mapRightClick', this, event);
27034             
27035         });
27036         
27037         google.maps.event.addListener(this.gMapContext.marker, 'click', function(event){
27038             _this.fireEvent('markerClick', this, event);
27039             
27040         });
27041
27042         google.maps.event.addListener(this.gMapContext.marker, 'rightclick', function(event){
27043             _this.fireEvent('markerRightClick', this, event);
27044             
27045         });
27046         
27047         this.setPosition(this.gMapContext.location);
27048         
27049         this.fireEvent('initial', this, this.gMapContext.location);
27050     },
27051     
27052     initOverlayView: function()
27053     {
27054         var _this = this;
27055         
27056         Roo.bootstrap.LocationPicker.OverlayView.prototype = Roo.apply(new google.maps.OverlayView(), {
27057             
27058             draw: function()
27059             {
27060                 _this.fireEvent('OverlayViewDraw', _this);
27061             },
27062             
27063             onAdd: function()
27064             {
27065                 _this.fireEvent('OverlayViewOnAdd', _this);
27066             },
27067             
27068             onRemove: function()
27069             {
27070                 _this.fireEvent('OverlayViewOnRemove', _this);
27071             },
27072             
27073             show: function(cpx)
27074             {
27075                 _this.fireEvent('OverlayViewShow', _this, cpx);
27076             },
27077             
27078             hide: function()
27079             {
27080                 _this.fireEvent('OverlayViewHide', _this);
27081             }
27082             
27083         });
27084     },
27085     
27086     fromLatLngToContainerPixel: function(event)
27087     {
27088         return this.OverlayView.getProjection().fromLatLngToContainerPixel(event.latLng);
27089     },
27090     
27091     isApplied: function() 
27092     {
27093         return this.getGmapContext() == false ? false : true;
27094     },
27095     
27096     getGmapContext: function() 
27097     {
27098         return (typeof(this.gMapContext) == 'undefined') ? false : this.gMapContext;
27099     },
27100     
27101     GMapContext: function() 
27102     {
27103         var position = new google.maps.LatLng(this.latitude, this.longitude);
27104         
27105         var _map = new google.maps.Map(this.el.dom, {
27106             center: position,
27107             zoom: this.zoom,
27108             mapTypeId: this.mapTypeId,
27109             mapTypeControl: this.mapTypeControl,
27110             disableDoubleClickZoom: this.disableDoubleClickZoom,
27111             scrollwheel: this.scrollwheel,
27112             streetViewControl: this.streetViewControl,
27113             locationName: this.locationName,
27114             draggable: this.draggable,
27115             enableAutocomplete: this.enableAutocomplete,
27116             enableReverseGeocode: this.enableReverseGeocode
27117         });
27118         
27119         var _marker = new google.maps.Marker({
27120             position: position,
27121             map: _map,
27122             title: this.markerTitle,
27123             draggable: this.draggable
27124         });
27125         
27126         return {
27127             map: _map,
27128             marker: _marker,
27129             circle: null,
27130             location: position,
27131             radius: this.radius,
27132             locationName: this.locationName,
27133             addressComponents: {
27134                 formatted_address: null,
27135                 addressLine1: null,
27136                 addressLine2: null,
27137                 streetName: null,
27138                 streetNumber: null,
27139                 city: null,
27140                 district: null,
27141                 state: null,
27142                 stateOrProvince: null
27143             },
27144             settings: this,
27145             domContainer: this.el.dom,
27146             geodecoder: new google.maps.Geocoder()
27147         };
27148     },
27149     
27150     drawCircle: function(center, radius, options) 
27151     {
27152         if (this.gMapContext.circle != null) {
27153             this.gMapContext.circle.setMap(null);
27154         }
27155         if (radius > 0) {
27156             radius *= 1;
27157             options = Roo.apply({}, options, {
27158                 strokeColor: "#0000FF",
27159                 strokeOpacity: .35,
27160                 strokeWeight: 2,
27161                 fillColor: "#0000FF",
27162                 fillOpacity: .2
27163             });
27164             
27165             options.map = this.gMapContext.map;
27166             options.radius = radius;
27167             options.center = center;
27168             this.gMapContext.circle = new google.maps.Circle(options);
27169             return this.gMapContext.circle;
27170         }
27171         
27172         return null;
27173     },
27174     
27175     setPosition: function(location) 
27176     {
27177         this.gMapContext.location = location;
27178         this.gMapContext.marker.setPosition(location);
27179         this.gMapContext.map.panTo(location);
27180         this.drawCircle(location, this.gMapContext.radius, {});
27181         
27182         var _this = this;
27183         
27184         if (this.gMapContext.settings.enableReverseGeocode) {
27185             this.gMapContext.geodecoder.geocode({
27186                 latLng: this.gMapContext.location
27187             }, function(results, status) {
27188                 
27189                 if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
27190                     _this.gMapContext.locationName = results[0].formatted_address;
27191                     _this.gMapContext.addressComponents = _this.address_component_from_google_geocode(results[0].address_components);
27192                     
27193                     _this.fireEvent('positionchanged', this, location);
27194                 }
27195             });
27196             
27197             return;
27198         }
27199         
27200         this.fireEvent('positionchanged', this, location);
27201     },
27202     
27203     resize: function()
27204     {
27205         google.maps.event.trigger(this.gMapContext.map, "resize");
27206         
27207         this.gMapContext.map.setCenter(this.gMapContext.marker.position);
27208         
27209         this.fireEvent('resize', this);
27210     },
27211     
27212     setPositionByLatLng: function(latitude, longitude)
27213     {
27214         this.setPosition(new google.maps.LatLng(latitude, longitude));
27215     },
27216     
27217     getCurrentPosition: function() 
27218     {
27219         return {
27220             latitude: this.gMapContext.location.lat(),
27221             longitude: this.gMapContext.location.lng()
27222         };
27223     },
27224     
27225     getAddressName: function() 
27226     {
27227         return this.gMapContext.locationName;
27228     },
27229     
27230     getAddressComponents: function() 
27231     {
27232         return this.gMapContext.addressComponents;
27233     },
27234     
27235     address_component_from_google_geocode: function(address_components) 
27236     {
27237         var result = {};
27238         
27239         for (var i = 0; i < address_components.length; i++) {
27240             var component = address_components[i];
27241             if (component.types.indexOf("postal_code") >= 0) {
27242                 result.postalCode = component.short_name;
27243             } else if (component.types.indexOf("street_number") >= 0) {
27244                 result.streetNumber = component.short_name;
27245             } else if (component.types.indexOf("route") >= 0) {
27246                 result.streetName = component.short_name;
27247             } else if (component.types.indexOf("neighborhood") >= 0) {
27248                 result.city = component.short_name;
27249             } else if (component.types.indexOf("locality") >= 0) {
27250                 result.city = component.short_name;
27251             } else if (component.types.indexOf("sublocality") >= 0) {
27252                 result.district = component.short_name;
27253             } else if (component.types.indexOf("administrative_area_level_1") >= 0) {
27254                 result.stateOrProvince = component.short_name;
27255             } else if (component.types.indexOf("country") >= 0) {
27256                 result.country = component.short_name;
27257             }
27258         }
27259         
27260         result.addressLine1 = [ result.streetNumber, result.streetName ].join(" ").trim();
27261         result.addressLine2 = "";
27262         return result;
27263     },
27264     
27265     setZoomLevel: function(zoom)
27266     {
27267         this.gMapContext.map.setZoom(zoom);
27268     },
27269     
27270     show: function()
27271     {
27272         if(!this.el){
27273             return;
27274         }
27275         
27276         this.el.show();
27277         
27278         this.resize();
27279         
27280         this.fireEvent('show', this);
27281     },
27282     
27283     hide: function()
27284     {
27285         if(!this.el){
27286             return;
27287         }
27288         
27289         this.el.hide();
27290         
27291         this.fireEvent('hide', this);
27292     }
27293     
27294 });
27295
27296 Roo.apply(Roo.bootstrap.LocationPicker, {
27297     
27298     OverlayView : function(map, options)
27299     {
27300         options = options || {};
27301         
27302         this.setMap(map);
27303     }
27304     
27305     
27306 });/**
27307  * @class Roo.bootstrap.Alert
27308  * @extends Roo.bootstrap.Component
27309  * Bootstrap Alert class - shows an alert area box
27310  * eg
27311  * <div class="alert alert-danger" role="alert"><span class="fa fa-exclamation-triangle"></span><span class="sr-only">Error:</span>
27312   Enter a valid email address
27313 </div>
27314  * @licence LGPL
27315  * @cfg {String} title The title of alert
27316  * @cfg {String} html The content of alert
27317  * @cfg {String} weight (  success | info | warning | danger )
27318  * @cfg {String} faicon font-awesomeicon
27319  * 
27320  * @constructor
27321  * Create a new alert
27322  * @param {Object} config The config object
27323  */
27324
27325
27326 Roo.bootstrap.Alert = function(config){
27327     Roo.bootstrap.Alert.superclass.constructor.call(this, config);
27328     
27329 };
27330
27331 Roo.extend(Roo.bootstrap.Alert, Roo.bootstrap.Component,  {
27332     
27333     title: '',
27334     html: '',
27335     weight: false,
27336     faicon: false,
27337     
27338     getAutoCreate : function()
27339     {
27340         
27341         var cfg = {
27342             tag : 'div',
27343             cls : 'alert',
27344             cn : [
27345                 {
27346                     tag : 'i',
27347                     cls : 'roo-alert-icon'
27348                     
27349                 },
27350                 {
27351                     tag : 'b',
27352                     cls : 'roo-alert-title',
27353                     html : this.title
27354                 },
27355                 {
27356                     tag : 'span',
27357                     cls : 'roo-alert-text',
27358                     html : this.html
27359                 }
27360             ]
27361         };
27362         
27363         if(this.faicon){
27364             cfg.cn[0].cls += ' fa ' + this.faicon;
27365         }
27366         
27367         if(this.weight){
27368             cfg.cls += ' alert-' + this.weight;
27369         }
27370         
27371         return cfg;
27372     },
27373     
27374     initEvents: function() 
27375     {
27376         this.el.setVisibilityMode(Roo.Element.DISPLAY);
27377     },
27378     
27379     setTitle : function(str)
27380     {
27381         this.el.select('.roo-alert-title',true).first().dom.innerHTML = str;
27382     },
27383     
27384     setText : function(str)
27385     {
27386         this.el.select('.roo-alert-text',true).first().dom.innerHTML = str;
27387     },
27388     
27389     setWeight : function(weight)
27390     {
27391         if(this.weight){
27392             this.el.select('.alert',true).first().removeClass('alert-' + this.weight);
27393         }
27394         
27395         this.weight = weight;
27396         
27397         this.el.select('.alert',true).first().addClass('alert-' + this.weight);
27398     },
27399     
27400     setIcon : function(icon)
27401     {
27402         if(this.faicon){
27403             this.el.select('.roo-alert-icon',true).first().removeClass(['fa', 'fa-' + this.faicon]);
27404         }
27405         
27406         this.faicon = icon;
27407         
27408         this.el.select('.roo-alert-icon',true).first().addClass(['fa', 'fa-' + this.faicon]);
27409     },
27410     
27411     hide: function() 
27412     {
27413         this.el.hide();   
27414     },
27415     
27416     show: function() 
27417     {  
27418         this.el.show();   
27419     }
27420     
27421 });
27422
27423  
27424 /*
27425 * Licence: LGPL
27426 */
27427
27428 /**
27429  * @class Roo.bootstrap.UploadCropbox
27430  * @extends Roo.bootstrap.Component
27431  * Bootstrap UploadCropbox class
27432  * @cfg {String} emptyText show when image has been loaded
27433  * @cfg {String} rotateNotify show when image too small to rotate
27434  * @cfg {Number} errorTimeout default 3000
27435  * @cfg {Number} minWidth default 300
27436  * @cfg {Number} minHeight default 300
27437  * @cfg {Array} buttons default ['rotateLeft', 'pictureBtn', 'rotateRight']
27438  * @cfg {Boolean} isDocument (true|false) default false
27439  * @cfg {String} url action url
27440  * @cfg {String} paramName default 'imageUpload'
27441  * @cfg {String} method default POST
27442  * @cfg {Boolean} loadMask (true|false) default true
27443  * @cfg {Boolean} loadingText default 'Loading...'
27444  * 
27445  * @constructor
27446  * Create a new UploadCropbox
27447  * @param {Object} config The config object
27448  */
27449
27450 Roo.bootstrap.UploadCropbox = function(config){
27451     Roo.bootstrap.UploadCropbox.superclass.constructor.call(this, config);
27452     
27453     this.addEvents({
27454         /**
27455          * @event beforeselectfile
27456          * Fire before select file
27457          * @param {Roo.bootstrap.UploadCropbox} this
27458          */
27459         "beforeselectfile" : true,
27460         /**
27461          * @event initial
27462          * Fire after initEvent
27463          * @param {Roo.bootstrap.UploadCropbox} this
27464          */
27465         "initial" : true,
27466         /**
27467          * @event crop
27468          * Fire after initEvent
27469          * @param {Roo.bootstrap.UploadCropbox} this
27470          * @param {String} data
27471          */
27472         "crop" : true,
27473         /**
27474          * @event prepare
27475          * Fire when preparing the file data
27476          * @param {Roo.bootstrap.UploadCropbox} this
27477          * @param {Object} file
27478          */
27479         "prepare" : true,
27480         /**
27481          * @event exception
27482          * Fire when get exception
27483          * @param {Roo.bootstrap.UploadCropbox} this
27484          * @param {XMLHttpRequest} xhr
27485          */
27486         "exception" : true,
27487         /**
27488          * @event beforeloadcanvas
27489          * Fire before load the canvas
27490          * @param {Roo.bootstrap.UploadCropbox} this
27491          * @param {String} src
27492          */
27493         "beforeloadcanvas" : true,
27494         /**
27495          * @event trash
27496          * Fire when trash image
27497          * @param {Roo.bootstrap.UploadCropbox} this
27498          */
27499         "trash" : true,
27500         /**
27501          * @event download
27502          * Fire when download the image
27503          * @param {Roo.bootstrap.UploadCropbox} this
27504          */
27505         "download" : true,
27506         /**
27507          * @event footerbuttonclick
27508          * Fire when footerbuttonclick
27509          * @param {Roo.bootstrap.UploadCropbox} this
27510          * @param {String} type
27511          */
27512         "footerbuttonclick" : true,
27513         /**
27514          * @event resize
27515          * Fire when resize
27516          * @param {Roo.bootstrap.UploadCropbox} this
27517          */
27518         "resize" : true,
27519         /**
27520          * @event rotate
27521          * Fire when rotate the image
27522          * @param {Roo.bootstrap.UploadCropbox} this
27523          * @param {String} pos
27524          */
27525         "rotate" : true,
27526         /**
27527          * @event inspect
27528          * Fire when inspect the file
27529          * @param {Roo.bootstrap.UploadCropbox} this
27530          * @param {Object} file
27531          */
27532         "inspect" : true,
27533         /**
27534          * @event upload
27535          * Fire when xhr upload the file
27536          * @param {Roo.bootstrap.UploadCropbox} this
27537          * @param {Object} data
27538          */
27539         "upload" : true,
27540         /**
27541          * @event arrange
27542          * Fire when arrange the file data
27543          * @param {Roo.bootstrap.UploadCropbox} this
27544          * @param {Object} formData
27545          */
27546         "arrange" : true
27547     });
27548     
27549     this.buttons = this.buttons || Roo.bootstrap.UploadCropbox.footer.STANDARD;
27550 };
27551
27552 Roo.extend(Roo.bootstrap.UploadCropbox, Roo.bootstrap.Component,  {
27553     
27554     emptyText : 'Click to upload image',
27555     rotateNotify : 'Image is too small to rotate',
27556     errorTimeout : 3000,
27557     scale : 0,
27558     baseScale : 1,
27559     rotate : 0,
27560     dragable : false,
27561     pinching : false,
27562     mouseX : 0,
27563     mouseY : 0,
27564     cropData : false,
27565     minWidth : 300,
27566     minHeight : 300,
27567     file : false,
27568     exif : {},
27569     baseRotate : 1,
27570     cropType : 'image/jpeg',
27571     buttons : false,
27572     canvasLoaded : false,
27573     isDocument : false,
27574     method : 'POST',
27575     paramName : 'imageUpload',
27576     loadMask : true,
27577     loadingText : 'Loading...',
27578     maskEl : false,
27579     
27580     getAutoCreate : function()
27581     {
27582         var cfg = {
27583             tag : 'div',
27584             cls : 'roo-upload-cropbox',
27585             cn : [
27586                 {
27587                     tag : 'input',
27588                     cls : 'roo-upload-cropbox-selector',
27589                     type : 'file'
27590                 },
27591                 {
27592                     tag : 'div',
27593                     cls : 'roo-upload-cropbox-body',
27594                     style : 'cursor:pointer',
27595                     cn : [
27596                         {
27597                             tag : 'div',
27598                             cls : 'roo-upload-cropbox-preview'
27599                         },
27600                         {
27601                             tag : 'div',
27602                             cls : 'roo-upload-cropbox-thumb'
27603                         },
27604                         {
27605                             tag : 'div',
27606                             cls : 'roo-upload-cropbox-empty-notify',
27607                             html : this.emptyText
27608                         },
27609                         {
27610                             tag : 'div',
27611                             cls : 'roo-upload-cropbox-error-notify alert alert-danger',
27612                             html : this.rotateNotify
27613                         }
27614                     ]
27615                 },
27616                 {
27617                     tag : 'div',
27618                     cls : 'roo-upload-cropbox-footer',
27619                     cn : {
27620                         tag : 'div',
27621                         cls : 'btn-group btn-group-justified roo-upload-cropbox-btn-group',
27622                         cn : []
27623                     }
27624                 }
27625             ]
27626         };
27627         
27628         return cfg;
27629     },
27630     
27631     onRender : function(ct, position)
27632     {
27633         Roo.bootstrap.UploadCropbox.superclass.onRender.call(this, ct, position);
27634         
27635         if (this.buttons.length) {
27636             
27637             Roo.each(this.buttons, function(bb) {
27638                 
27639                 var btn = this.el.select('.roo-upload-cropbox-footer div.roo-upload-cropbox-btn-group').first().createChild(bb);
27640                 
27641                 btn.on('click', this.onFooterButtonClick.createDelegate(this, [bb.action], true));
27642                 
27643             }, this);
27644         }
27645         
27646         if(this.loadMask){
27647             this.maskEl = this.el;
27648         }
27649     },
27650     
27651     initEvents : function()
27652     {
27653         this.urlAPI = (window.createObjectURL && window) || 
27654                                 (window.URL && URL.revokeObjectURL && URL) || 
27655                                 (window.webkitURL && webkitURL);
27656                         
27657         this.bodyEl = this.el.select('.roo-upload-cropbox-body', true).first();
27658         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
27659         
27660         this.selectorEl = this.el.select('.roo-upload-cropbox-selector', true).first();
27661         this.selectorEl.hide();
27662         
27663         this.previewEl = this.el.select('.roo-upload-cropbox-preview', true).first();
27664         this.previewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
27665         
27666         this.thumbEl = this.el.select('.roo-upload-cropbox-thumb', true).first();
27667         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
27668         this.thumbEl.hide();
27669         
27670         this.notifyEl = this.el.select('.roo-upload-cropbox-empty-notify', true).first();
27671         this.notifyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
27672         
27673         this.errorEl = this.el.select('.roo-upload-cropbox-error-notify', true).first();
27674         this.errorEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
27675         this.errorEl.hide();
27676         
27677         this.footerEl = this.el.select('.roo-upload-cropbox-footer', true).first();
27678         this.footerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
27679         this.footerEl.hide();
27680         
27681         this.setThumbBoxSize();
27682         
27683         this.bind();
27684         
27685         this.resize();
27686         
27687         this.fireEvent('initial', this);
27688     },
27689
27690     bind : function()
27691     {
27692         var _this = this;
27693         
27694         window.addEventListener("resize", function() { _this.resize(); } );
27695         
27696         this.bodyEl.on('click', this.beforeSelectFile, this);
27697         
27698         if(Roo.isTouch){
27699             this.bodyEl.on('touchstart', this.onTouchStart, this);
27700             this.bodyEl.on('touchmove', this.onTouchMove, this);
27701             this.bodyEl.on('touchend', this.onTouchEnd, this);
27702         }
27703         
27704         if(!Roo.isTouch){
27705             this.bodyEl.on('mousedown', this.onMouseDown, this);
27706             this.bodyEl.on('mousemove', this.onMouseMove, this);
27707             var mousewheel = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
27708             this.bodyEl.on(mousewheel, this.onMouseWheel, this);
27709             Roo.get(document).on('mouseup', this.onMouseUp, this);
27710         }
27711         
27712         this.selectorEl.on('change', this.onFileSelected, this);
27713     },
27714     
27715     reset : function()
27716     {    
27717         this.scale = 0;
27718         this.baseScale = 1;
27719         this.rotate = 0;
27720         this.baseRotate = 1;
27721         this.dragable = false;
27722         this.pinching = false;
27723         this.mouseX = 0;
27724         this.mouseY = 0;
27725         this.cropData = false;
27726         this.notifyEl.dom.innerHTML = this.emptyText;
27727         
27728         this.selectorEl.dom.value = '';
27729         
27730     },
27731     
27732     resize : function()
27733     {
27734         if(this.fireEvent('resize', this) != false){
27735             this.setThumbBoxPosition();
27736             this.setCanvasPosition();
27737         }
27738     },
27739     
27740     onFooterButtonClick : function(e, el, o, type)
27741     {
27742         switch (type) {
27743             case 'rotate-left' :
27744                 this.onRotateLeft(e);
27745                 break;
27746             case 'rotate-right' :
27747                 this.onRotateRight(e);
27748                 break;
27749             case 'picture' :
27750                 this.beforeSelectFile(e);
27751                 break;
27752             case 'trash' :
27753                 this.trash(e);
27754                 break;
27755             case 'crop' :
27756                 this.crop(e);
27757                 break;
27758             case 'download' :
27759                 this.download(e);
27760                 break;
27761             default :
27762                 break;
27763         }
27764         
27765         this.fireEvent('footerbuttonclick', this, type);
27766     },
27767     
27768     beforeSelectFile : function(e)
27769     {
27770         e.preventDefault();
27771         
27772         if(this.fireEvent('beforeselectfile', this) != false){
27773             this.selectorEl.dom.click();
27774         }
27775     },
27776     
27777     onFileSelected : function(e)
27778     {
27779         e.preventDefault();
27780         
27781         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
27782             return;
27783         }
27784         
27785         var file = this.selectorEl.dom.files[0];
27786         
27787         if(this.fireEvent('inspect', this, file) != false){
27788             this.prepare(file);
27789         }
27790         
27791     },
27792     
27793     trash : function(e)
27794     {
27795         this.fireEvent('trash', this);
27796     },
27797     
27798     download : function(e)
27799     {
27800         this.fireEvent('download', this);
27801     },
27802     
27803     loadCanvas : function(src)
27804     {   
27805         if(this.fireEvent('beforeloadcanvas', this, src) != false){
27806             
27807             this.reset();
27808             
27809             this.imageEl = document.createElement('img');
27810             
27811             var _this = this;
27812             
27813             this.imageEl.addEventListener("load", function(){ _this.onLoadCanvas(); });
27814             
27815             this.imageEl.src = src;
27816         }
27817     },
27818     
27819     onLoadCanvas : function()
27820     {   
27821         this.imageEl.OriginWidth = this.imageEl.naturalWidth || this.imageEl.width;
27822         this.imageEl.OriginHeight = this.imageEl.naturalHeight || this.imageEl.height;
27823         
27824         this.bodyEl.un('click', this.beforeSelectFile, this);
27825         
27826         this.notifyEl.hide();
27827         this.thumbEl.show();
27828         this.footerEl.show();
27829         
27830         this.baseRotateLevel();
27831         
27832         if(this.isDocument){
27833             this.setThumbBoxSize();
27834         }
27835         
27836         this.setThumbBoxPosition();
27837         
27838         this.baseScaleLevel();
27839         
27840         this.draw();
27841         
27842         this.resize();
27843         
27844         this.canvasLoaded = true;
27845         
27846         if(this.loadMask){
27847             this.maskEl.unmask();
27848         }
27849         
27850     },
27851     
27852     setCanvasPosition : function()
27853     {   
27854         if(!this.canvasEl){
27855             return;
27856         }
27857         
27858         var pw = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
27859         var ph = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
27860         
27861         this.previewEl.setLeft(pw);
27862         this.previewEl.setTop(ph);
27863         
27864     },
27865     
27866     onMouseDown : function(e)
27867     {   
27868         e.stopEvent();
27869         
27870         this.dragable = true;
27871         this.pinching = false;
27872         
27873         if(this.isDocument && (this.canvasEl.width < this.thumbEl.getWidth() || this.canvasEl.height < this.thumbEl.getHeight())){
27874             this.dragable = false;
27875             return;
27876         }
27877         
27878         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
27879         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
27880         
27881     },
27882     
27883     onMouseMove : function(e)
27884     {   
27885         e.stopEvent();
27886         
27887         if(!this.canvasLoaded){
27888             return;
27889         }
27890         
27891         if (!this.dragable){
27892             return;
27893         }
27894         
27895         var minX = Math.ceil(this.thumbEl.getLeft(true));
27896         var minY = Math.ceil(this.thumbEl.getTop(true));
27897         
27898         var maxX = Math.ceil(minX + this.thumbEl.getWidth() - this.canvasEl.width);
27899         var maxY = Math.ceil(minY + this.thumbEl.getHeight() - this.canvasEl.height);
27900         
27901         var x = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
27902         var y = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
27903         
27904         x = x - this.mouseX;
27905         y = y - this.mouseY;
27906         
27907         var bgX = Math.ceil(x + this.previewEl.getLeft(true));
27908         var bgY = Math.ceil(y + this.previewEl.getTop(true));
27909         
27910         bgX = (minX < bgX) ? minX : ((maxX > bgX) ? maxX : bgX);
27911         bgY = (minY < bgY) ? minY : ((maxY > bgY) ? maxY : bgY);
27912         
27913         this.previewEl.setLeft(bgX);
27914         this.previewEl.setTop(bgY);
27915         
27916         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
27917         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
27918     },
27919     
27920     onMouseUp : function(e)
27921     {   
27922         e.stopEvent();
27923         
27924         this.dragable = false;
27925     },
27926     
27927     onMouseWheel : function(e)
27928     {   
27929         e.stopEvent();
27930         
27931         this.startScale = this.scale;
27932         
27933         this.scale = (e.getWheelDelta() == 1) ? (this.scale + 1) : (this.scale - 1);
27934         
27935         if(!this.zoomable()){
27936             this.scale = this.startScale;
27937             return;
27938         }
27939         
27940         this.draw();
27941         
27942         return;
27943     },
27944     
27945     zoomable : function()
27946     {
27947         var minScale = this.thumbEl.getWidth() / this.minWidth;
27948         
27949         if(this.minWidth < this.minHeight){
27950             minScale = this.thumbEl.getHeight() / this.minHeight;
27951         }
27952         
27953         var width = Math.ceil(this.imageEl.OriginWidth * this.getScaleLevel() / minScale);
27954         var height = Math.ceil(this.imageEl.OriginHeight * this.getScaleLevel() / minScale);
27955         
27956         if(
27957                 this.isDocument &&
27958                 (this.rotate == 0 || this.rotate == 180) && 
27959                 (
27960                     width > this.imageEl.OriginWidth || 
27961                     height > this.imageEl.OriginHeight ||
27962                     (width < this.minWidth && height < this.minHeight)
27963                 )
27964         ){
27965             return false;
27966         }
27967         
27968         if(
27969                 this.isDocument &&
27970                 (this.rotate == 90 || this.rotate == 270) && 
27971                 (
27972                     width > this.imageEl.OriginWidth || 
27973                     height > this.imageEl.OriginHeight ||
27974                     (width < this.minHeight && height < this.minWidth)
27975                 )
27976         ){
27977             return false;
27978         }
27979         
27980         if(
27981                 !this.isDocument &&
27982                 (this.rotate == 0 || this.rotate == 180) && 
27983                 (
27984                     width < this.minWidth || 
27985                     width > this.imageEl.OriginWidth || 
27986                     height < this.minHeight || 
27987                     height > this.imageEl.OriginHeight
27988                 )
27989         ){
27990             return false;
27991         }
27992         
27993         if(
27994                 !this.isDocument &&
27995                 (this.rotate == 90 || this.rotate == 270) && 
27996                 (
27997                     width < this.minHeight || 
27998                     width > this.imageEl.OriginWidth || 
27999                     height < this.minWidth || 
28000                     height > this.imageEl.OriginHeight
28001                 )
28002         ){
28003             return false;
28004         }
28005         
28006         return true;
28007         
28008     },
28009     
28010     onRotateLeft : function(e)
28011     {   
28012         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
28013             
28014             var minScale = this.thumbEl.getWidth() / this.minWidth;
28015             
28016             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
28017             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
28018             
28019             this.startScale = this.scale;
28020             
28021             while (this.getScaleLevel() < minScale){
28022             
28023                 this.scale = this.scale + 1;
28024                 
28025                 if(!this.zoomable()){
28026                     break;
28027                 }
28028                 
28029                 if(
28030                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
28031                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
28032                 ){
28033                     continue;
28034                 }
28035                 
28036                 this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
28037
28038                 this.draw();
28039                 
28040                 return;
28041             }
28042             
28043             this.scale = this.startScale;
28044             
28045             this.onRotateFail();
28046             
28047             return false;
28048         }
28049         
28050         this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
28051
28052         if(this.isDocument){
28053             this.setThumbBoxSize();
28054             this.setThumbBoxPosition();
28055             this.setCanvasPosition();
28056         }
28057         
28058         this.draw();
28059         
28060         this.fireEvent('rotate', this, 'left');
28061         
28062     },
28063     
28064     onRotateRight : function(e)
28065     {
28066         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
28067             
28068             var minScale = this.thumbEl.getWidth() / this.minWidth;
28069         
28070             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
28071             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
28072             
28073             this.startScale = this.scale;
28074             
28075             while (this.getScaleLevel() < minScale){
28076             
28077                 this.scale = this.scale + 1;
28078                 
28079                 if(!this.zoomable()){
28080                     break;
28081                 }
28082                 
28083                 if(
28084                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
28085                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
28086                 ){
28087                     continue;
28088                 }
28089                 
28090                 this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
28091
28092                 this.draw();
28093                 
28094                 return;
28095             }
28096             
28097             this.scale = this.startScale;
28098             
28099             this.onRotateFail();
28100             
28101             return false;
28102         }
28103         
28104         this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
28105
28106         if(this.isDocument){
28107             this.setThumbBoxSize();
28108             this.setThumbBoxPosition();
28109             this.setCanvasPosition();
28110         }
28111         
28112         this.draw();
28113         
28114         this.fireEvent('rotate', this, 'right');
28115     },
28116     
28117     onRotateFail : function()
28118     {
28119         this.errorEl.show(true);
28120         
28121         var _this = this;
28122         
28123         (function() { _this.errorEl.hide(true); }).defer(this.errorTimeout);
28124     },
28125     
28126     draw : function()
28127     {
28128         this.previewEl.dom.innerHTML = '';
28129         
28130         var canvasEl = document.createElement("canvas");
28131         
28132         var contextEl = canvasEl.getContext("2d");
28133         
28134         canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
28135         canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
28136         var center = this.imageEl.OriginWidth / 2;
28137         
28138         if(this.imageEl.OriginWidth < this.imageEl.OriginHeight){
28139             canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
28140             canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
28141             center = this.imageEl.OriginHeight / 2;
28142         }
28143         
28144         contextEl.scale(this.getScaleLevel(), this.getScaleLevel());
28145         
28146         contextEl.translate(center, center);
28147         contextEl.rotate(this.rotate * Math.PI / 180);
28148
28149         contextEl.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
28150         
28151         this.canvasEl = document.createElement("canvas");
28152         
28153         this.contextEl = this.canvasEl.getContext("2d");
28154         
28155         switch (this.rotate) {
28156             case 0 :
28157                 
28158                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
28159                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
28160                 
28161                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
28162                 
28163                 break;
28164             case 90 : 
28165                 
28166                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
28167                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
28168                 
28169                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
28170                     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);
28171                     break;
28172                 }
28173                 
28174                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
28175                 
28176                 break;
28177             case 180 :
28178                 
28179                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
28180                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
28181                 
28182                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
28183                     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);
28184                     break;
28185                 }
28186                 
28187                 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);
28188                 
28189                 break;
28190             case 270 :
28191                 
28192                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
28193                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
28194         
28195                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
28196                     this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
28197                     break;
28198                 }
28199                 
28200                 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);
28201                 
28202                 break;
28203             default : 
28204                 break;
28205         }
28206         
28207         this.previewEl.appendChild(this.canvasEl);
28208         
28209         this.setCanvasPosition();
28210     },
28211     
28212     crop : function()
28213     {
28214         if(!this.canvasLoaded){
28215             return;
28216         }
28217         
28218         var imageCanvas = document.createElement("canvas");
28219         
28220         var imageContext = imageCanvas.getContext("2d");
28221         
28222         imageCanvas.width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
28223         imageCanvas.height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
28224         
28225         var center = imageCanvas.width / 2;
28226         
28227         imageContext.translate(center, center);
28228         
28229         imageContext.rotate(this.rotate * Math.PI / 180);
28230         
28231         imageContext.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
28232         
28233         var canvas = document.createElement("canvas");
28234         
28235         var context = canvas.getContext("2d");
28236                 
28237         canvas.width = this.minWidth;
28238         canvas.height = this.minHeight;
28239
28240         switch (this.rotate) {
28241             case 0 :
28242                 
28243                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
28244                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
28245                 
28246                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
28247                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
28248                 
28249                 var targetWidth = this.minWidth - 2 * x;
28250                 var targetHeight = this.minHeight - 2 * y;
28251                 
28252                 var scale = 1;
28253                 
28254                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
28255                     scale = targetWidth / width;
28256                 }
28257                 
28258                 if(x > 0 && y == 0){
28259                     scale = targetHeight / height;
28260                 }
28261                 
28262                 if(x > 0 && y > 0){
28263                     scale = targetWidth / width;
28264                     
28265                     if(width < height){
28266                         scale = targetHeight / height;
28267                     }
28268                 }
28269                 
28270                 context.scale(scale, scale);
28271                 
28272                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
28273                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
28274
28275                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
28276                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
28277
28278                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
28279                 
28280                 break;
28281             case 90 : 
28282                 
28283                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
28284                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
28285                 
28286                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
28287                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
28288                 
28289                 var targetWidth = this.minWidth - 2 * x;
28290                 var targetHeight = this.minHeight - 2 * y;
28291                 
28292                 var scale = 1;
28293                 
28294                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
28295                     scale = targetWidth / width;
28296                 }
28297                 
28298                 if(x > 0 && y == 0){
28299                     scale = targetHeight / height;
28300                 }
28301                 
28302                 if(x > 0 && y > 0){
28303                     scale = targetWidth / width;
28304                     
28305                     if(width < height){
28306                         scale = targetHeight / height;
28307                     }
28308                 }
28309                 
28310                 context.scale(scale, scale);
28311                 
28312                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
28313                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
28314
28315                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
28316                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
28317                 
28318                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
28319                 
28320                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
28321                 
28322                 break;
28323             case 180 :
28324                 
28325                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
28326                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
28327                 
28328                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
28329                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
28330                 
28331                 var targetWidth = this.minWidth - 2 * x;
28332                 var targetHeight = this.minHeight - 2 * y;
28333                 
28334                 var scale = 1;
28335                 
28336                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
28337                     scale = targetWidth / width;
28338                 }
28339                 
28340                 if(x > 0 && y == 0){
28341                     scale = targetHeight / height;
28342                 }
28343                 
28344                 if(x > 0 && y > 0){
28345                     scale = targetWidth / width;
28346                     
28347                     if(width < height){
28348                         scale = targetHeight / height;
28349                     }
28350                 }
28351                 
28352                 context.scale(scale, scale);
28353                 
28354                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
28355                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
28356
28357                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
28358                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
28359
28360                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
28361                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
28362                 
28363                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
28364                 
28365                 break;
28366             case 270 :
28367                 
28368                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
28369                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
28370                 
28371                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
28372                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
28373                 
28374                 var targetWidth = this.minWidth - 2 * x;
28375                 var targetHeight = this.minHeight - 2 * y;
28376                 
28377                 var scale = 1;
28378                 
28379                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
28380                     scale = targetWidth / width;
28381                 }
28382                 
28383                 if(x > 0 && y == 0){
28384                     scale = targetHeight / height;
28385                 }
28386                 
28387                 if(x > 0 && y > 0){
28388                     scale = targetWidth / width;
28389                     
28390                     if(width < height){
28391                         scale = targetHeight / height;
28392                     }
28393                 }
28394                 
28395                 context.scale(scale, scale);
28396                 
28397                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
28398                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
28399
28400                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
28401                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
28402                 
28403                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
28404                 
28405                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
28406                 
28407                 break;
28408             default : 
28409                 break;
28410         }
28411         
28412         this.cropData = canvas.toDataURL(this.cropType);
28413         
28414         if(this.fireEvent('crop', this, this.cropData) !== false){
28415             this.process(this.file, this.cropData);
28416         }
28417         
28418         return;
28419         
28420     },
28421     
28422     setThumbBoxSize : function()
28423     {
28424         var width, height;
28425         
28426         if(this.isDocument && typeof(this.imageEl) != 'undefined'){
28427             width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.max(this.minWidth, this.minHeight) : Math.min(this.minWidth, this.minHeight);
28428             height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.min(this.minWidth, this.minHeight) : Math.max(this.minWidth, this.minHeight);
28429             
28430             this.minWidth = width;
28431             this.minHeight = height;
28432             
28433             if(this.rotate == 90 || this.rotate == 270){
28434                 this.minWidth = height;
28435                 this.minHeight = width;
28436             }
28437         }
28438         
28439         height = 300;
28440         width = Math.ceil(this.minWidth * height / this.minHeight);
28441         
28442         if(this.minWidth > this.minHeight){
28443             width = 300;
28444             height = Math.ceil(this.minHeight * width / this.minWidth);
28445         }
28446         
28447         this.thumbEl.setStyle({
28448             width : width + 'px',
28449             height : height + 'px'
28450         });
28451
28452         return;
28453             
28454     },
28455     
28456     setThumbBoxPosition : function()
28457     {
28458         var x = Math.ceil((this.bodyEl.getWidth() - this.thumbEl.getWidth()) / 2 );
28459         var y = Math.ceil((this.bodyEl.getHeight() - this.thumbEl.getHeight()) / 2);
28460         
28461         this.thumbEl.setLeft(x);
28462         this.thumbEl.setTop(y);
28463         
28464     },
28465     
28466     baseRotateLevel : function()
28467     {
28468         this.baseRotate = 1;
28469         
28470         if(
28471                 typeof(this.exif) != 'undefined' &&
28472                 typeof(this.exif[Roo.bootstrap.UploadCropbox['tags']['Orientation']]) != 'undefined' &&
28473                 [1, 3, 6, 8].indexOf(this.exif[Roo.bootstrap.UploadCropbox['tags']['Orientation']]) != -1
28474         ){
28475             this.baseRotate = this.exif[Roo.bootstrap.UploadCropbox['tags']['Orientation']];
28476         }
28477         
28478         this.rotate = Roo.bootstrap.UploadCropbox['Orientation'][this.baseRotate];
28479         
28480     },
28481     
28482     baseScaleLevel : function()
28483     {
28484         var width, height;
28485         
28486         if(this.isDocument){
28487             
28488             if(this.baseRotate == 6 || this.baseRotate == 8){
28489             
28490                 height = this.thumbEl.getHeight();
28491                 this.baseScale = height / this.imageEl.OriginWidth;
28492
28493                 if(this.imageEl.OriginHeight * this.baseScale > this.thumbEl.getWidth()){
28494                     width = this.thumbEl.getWidth();
28495                     this.baseScale = width / this.imageEl.OriginHeight;
28496                 }
28497
28498                 return;
28499             }
28500
28501             height = this.thumbEl.getHeight();
28502             this.baseScale = height / this.imageEl.OriginHeight;
28503
28504             if(this.imageEl.OriginWidth * this.baseScale > this.thumbEl.getWidth()){
28505                 width = this.thumbEl.getWidth();
28506                 this.baseScale = width / this.imageEl.OriginWidth;
28507             }
28508
28509             return;
28510         }
28511         
28512         if(this.baseRotate == 6 || this.baseRotate == 8){
28513             
28514             width = this.thumbEl.getHeight();
28515             this.baseScale = width / this.imageEl.OriginHeight;
28516             
28517             if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getWidth()){
28518                 height = this.thumbEl.getWidth();
28519                 this.baseScale = height / this.imageEl.OriginHeight;
28520             }
28521             
28522             if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
28523                 height = this.thumbEl.getWidth();
28524                 this.baseScale = height / this.imageEl.OriginHeight;
28525                 
28526                 if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getHeight()){
28527                     width = this.thumbEl.getHeight();
28528                     this.baseScale = width / this.imageEl.OriginWidth;
28529                 }
28530             }
28531             
28532             return;
28533         }
28534         
28535         width = this.thumbEl.getWidth();
28536         this.baseScale = width / this.imageEl.OriginWidth;
28537         
28538         if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getHeight()){
28539             height = this.thumbEl.getHeight();
28540             this.baseScale = height / this.imageEl.OriginHeight;
28541         }
28542         
28543         if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
28544             
28545             height = this.thumbEl.getHeight();
28546             this.baseScale = height / this.imageEl.OriginHeight;
28547             
28548             if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getWidth()){
28549                 width = this.thumbEl.getWidth();
28550                 this.baseScale = width / this.imageEl.OriginWidth;
28551             }
28552             
28553         }
28554         
28555         return;
28556     },
28557     
28558     getScaleLevel : function()
28559     {
28560         return this.baseScale * Math.pow(1.1, this.scale);
28561     },
28562     
28563     onTouchStart : function(e)
28564     {
28565         if(!this.canvasLoaded){
28566             this.beforeSelectFile(e);
28567             return;
28568         }
28569         
28570         var touches = e.browserEvent.touches;
28571         
28572         if(!touches){
28573             return;
28574         }
28575         
28576         if(touches.length == 1){
28577             this.onMouseDown(e);
28578             return;
28579         }
28580         
28581         if(touches.length != 2){
28582             return;
28583         }
28584         
28585         var coords = [];
28586         
28587         for(var i = 0, finger; finger = touches[i]; i++){
28588             coords.push(finger.pageX, finger.pageY);
28589         }
28590         
28591         var x = Math.pow(coords[0] - coords[2], 2);
28592         var y = Math.pow(coords[1] - coords[3], 2);
28593         
28594         this.startDistance = Math.sqrt(x + y);
28595         
28596         this.startScale = this.scale;
28597         
28598         this.pinching = true;
28599         this.dragable = false;
28600         
28601     },
28602     
28603     onTouchMove : function(e)
28604     {
28605         if(!this.pinching && !this.dragable){
28606             return;
28607         }
28608         
28609         var touches = e.browserEvent.touches;
28610         
28611         if(!touches){
28612             return;
28613         }
28614         
28615         if(this.dragable){
28616             this.onMouseMove(e);
28617             return;
28618         }
28619         
28620         var coords = [];
28621         
28622         for(var i = 0, finger; finger = touches[i]; i++){
28623             coords.push(finger.pageX, finger.pageY);
28624         }
28625         
28626         var x = Math.pow(coords[0] - coords[2], 2);
28627         var y = Math.pow(coords[1] - coords[3], 2);
28628         
28629         this.endDistance = Math.sqrt(x + y);
28630         
28631         this.scale = this.startScale + Math.floor(Math.log(this.endDistance / this.startDistance) / Math.log(1.1));
28632         
28633         if(!this.zoomable()){
28634             this.scale = this.startScale;
28635             return;
28636         }
28637         
28638         this.draw();
28639         
28640     },
28641     
28642     onTouchEnd : function(e)
28643     {
28644         this.pinching = false;
28645         this.dragable = false;
28646         
28647     },
28648     
28649     process : function(file, crop)
28650     {
28651         if(this.loadMask){
28652             this.maskEl.mask(this.loadingText);
28653         }
28654         
28655         this.xhr = new XMLHttpRequest();
28656         
28657         file.xhr = this.xhr;
28658
28659         this.xhr.open(this.method, this.url, true);
28660         
28661         var headers = {
28662             "Accept": "application/json",
28663             "Cache-Control": "no-cache",
28664             "X-Requested-With": "XMLHttpRequest"
28665         };
28666         
28667         for (var headerName in headers) {
28668             var headerValue = headers[headerName];
28669             if (headerValue) {
28670                 this.xhr.setRequestHeader(headerName, headerValue);
28671             }
28672         }
28673         
28674         var _this = this;
28675         
28676         this.xhr.onload = function()
28677         {
28678             _this.xhrOnLoad(_this.xhr);
28679         }
28680         
28681         this.xhr.onerror = function()
28682         {
28683             _this.xhrOnError(_this.xhr);
28684         }
28685         
28686         var formData = new FormData();
28687
28688         formData.append('returnHTML', 'NO');
28689         
28690         if(crop){
28691             formData.append('crop', crop);
28692         }
28693         
28694         if(typeof(file) != 'undefined' && (typeof(file.id) == 'undefined' || file.id * 1 < 1)){
28695             formData.append(this.paramName, file, file.name);
28696         }
28697         
28698         if(typeof(file.filename) != 'undefined'){
28699             formData.append('filename', file.filename);
28700         }
28701         
28702         if(typeof(file.mimetype) != 'undefined'){
28703             formData.append('mimetype', file.mimetype);
28704         }
28705         
28706         if(this.fireEvent('arrange', this, formData) != false){
28707             this.xhr.send(formData);
28708         };
28709     },
28710     
28711     xhrOnLoad : function(xhr)
28712     {
28713         if(this.loadMask){
28714             this.maskEl.unmask();
28715         }
28716         
28717         if (xhr.readyState !== 4) {
28718             this.fireEvent('exception', this, xhr);
28719             return;
28720         }
28721
28722         var response = Roo.decode(xhr.responseText);
28723         
28724         if(!response.success){
28725             this.fireEvent('exception', this, xhr);
28726             return;
28727         }
28728         
28729         var response = Roo.decode(xhr.responseText);
28730         
28731         this.fireEvent('upload', this, response);
28732         
28733     },
28734     
28735     xhrOnError : function()
28736     {
28737         if(this.loadMask){
28738             this.maskEl.unmask();
28739         }
28740         
28741         Roo.log('xhr on error');
28742         
28743         var response = Roo.decode(xhr.responseText);
28744           
28745         Roo.log(response);
28746         
28747     },
28748     
28749     prepare : function(file)
28750     {   
28751         if(this.loadMask){
28752             this.maskEl.mask(this.loadingText);
28753         }
28754         
28755         this.file = false;
28756         this.exif = {};
28757         
28758         if(typeof(file) === 'string'){
28759             this.loadCanvas(file);
28760             return;
28761         }
28762         
28763         if(!file || !this.urlAPI){
28764             return;
28765         }
28766         
28767         this.file = file;
28768         this.cropType = file.type;
28769         
28770         var _this = this;
28771         
28772         if(this.fireEvent('prepare', this, this.file) != false){
28773             
28774             var reader = new FileReader();
28775             
28776             reader.onload = function (e) {
28777                 if (e.target.error) {
28778                     Roo.log(e.target.error);
28779                     return;
28780                 }
28781                 
28782                 var buffer = e.target.result,
28783                     dataView = new DataView(buffer),
28784                     offset = 2,
28785                     maxOffset = dataView.byteLength - 4,
28786                     markerBytes,
28787                     markerLength;
28788                 
28789                 if (dataView.getUint16(0) === 0xffd8) {
28790                     while (offset < maxOffset) {
28791                         markerBytes = dataView.getUint16(offset);
28792                         
28793                         if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) {
28794                             markerLength = dataView.getUint16(offset + 2) + 2;
28795                             if (offset + markerLength > dataView.byteLength) {
28796                                 Roo.log('Invalid meta data: Invalid segment size.');
28797                                 break;
28798                             }
28799                             
28800                             if(markerBytes == 0xffe1){
28801                                 _this.parseExifData(
28802                                     dataView,
28803                                     offset,
28804                                     markerLength
28805                                 );
28806                             }
28807                             
28808                             offset += markerLength;
28809                             
28810                             continue;
28811                         }
28812                         
28813                         break;
28814                     }
28815                     
28816                 }
28817                 
28818                 var url = _this.urlAPI.createObjectURL(_this.file);
28819                 
28820                 _this.loadCanvas(url);
28821                 
28822                 return;
28823             }
28824             
28825             reader.readAsArrayBuffer(this.file);
28826             
28827         }
28828         
28829     },
28830     
28831     parseExifData : function(dataView, offset, length)
28832     {
28833         var tiffOffset = offset + 10,
28834             littleEndian,
28835             dirOffset;
28836     
28837         if (dataView.getUint32(offset + 4) !== 0x45786966) {
28838             // No Exif data, might be XMP data instead
28839             return;
28840         }
28841         
28842         // Check for the ASCII code for "Exif" (0x45786966):
28843         if (dataView.getUint32(offset + 4) !== 0x45786966) {
28844             // No Exif data, might be XMP data instead
28845             return;
28846         }
28847         if (tiffOffset + 8 > dataView.byteLength) {
28848             Roo.log('Invalid Exif data: Invalid segment size.');
28849             return;
28850         }
28851         // Check for the two null bytes:
28852         if (dataView.getUint16(offset + 8) !== 0x0000) {
28853             Roo.log('Invalid Exif data: Missing byte alignment offset.');
28854             return;
28855         }
28856         // Check the byte alignment:
28857         switch (dataView.getUint16(tiffOffset)) {
28858         case 0x4949:
28859             littleEndian = true;
28860             break;
28861         case 0x4D4D:
28862             littleEndian = false;
28863             break;
28864         default:
28865             Roo.log('Invalid Exif data: Invalid byte alignment marker.');
28866             return;
28867         }
28868         // Check for the TIFF tag marker (0x002A):
28869         if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
28870             Roo.log('Invalid Exif data: Missing TIFF marker.');
28871             return;
28872         }
28873         // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
28874         dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
28875         
28876         this.parseExifTags(
28877             dataView,
28878             tiffOffset,
28879             tiffOffset + dirOffset,
28880             littleEndian
28881         );
28882     },
28883     
28884     parseExifTags : function(dataView, tiffOffset, dirOffset, littleEndian)
28885     {
28886         var tagsNumber,
28887             dirEndOffset,
28888             i;
28889         if (dirOffset + 6 > dataView.byteLength) {
28890             Roo.log('Invalid Exif data: Invalid directory offset.');
28891             return;
28892         }
28893         tagsNumber = dataView.getUint16(dirOffset, littleEndian);
28894         dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
28895         if (dirEndOffset + 4 > dataView.byteLength) {
28896             Roo.log('Invalid Exif data: Invalid directory size.');
28897             return;
28898         }
28899         for (i = 0; i < tagsNumber; i += 1) {
28900             this.parseExifTag(
28901                 dataView,
28902                 tiffOffset,
28903                 dirOffset + 2 + 12 * i, // tag offset
28904                 littleEndian
28905             );
28906         }
28907         // Return the offset to the next directory:
28908         return dataView.getUint32(dirEndOffset, littleEndian);
28909     },
28910     
28911     parseExifTag : function (dataView, tiffOffset, offset, littleEndian) 
28912     {
28913         var tag = dataView.getUint16(offset, littleEndian);
28914         
28915         this.exif[tag] = this.getExifValue(
28916             dataView,
28917             tiffOffset,
28918             offset,
28919             dataView.getUint16(offset + 2, littleEndian), // tag type
28920             dataView.getUint32(offset + 4, littleEndian), // tag length
28921             littleEndian
28922         );
28923     },
28924     
28925     getExifValue : function (dataView, tiffOffset, offset, type, length, littleEndian)
28926     {
28927         var tagType = Roo.bootstrap.UploadCropbox.exifTagTypes[type],
28928             tagSize,
28929             dataOffset,
28930             values,
28931             i,
28932             str,
28933             c;
28934     
28935         if (!tagType) {
28936             Roo.log('Invalid Exif data: Invalid tag type.');
28937             return;
28938         }
28939         
28940         tagSize = tagType.size * length;
28941         // Determine if the value is contained in the dataOffset bytes,
28942         // or if the value at the dataOffset is a pointer to the actual data:
28943         dataOffset = tagSize > 4 ?
28944                 tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8);
28945         if (dataOffset + tagSize > dataView.byteLength) {
28946             Roo.log('Invalid Exif data: Invalid data offset.');
28947             return;
28948         }
28949         if (length === 1) {
28950             return tagType.getValue(dataView, dataOffset, littleEndian);
28951         }
28952         values = [];
28953         for (i = 0; i < length; i += 1) {
28954             values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian);
28955         }
28956         
28957         if (tagType.ascii) {
28958             str = '';
28959             // Concatenate the chars:
28960             for (i = 0; i < values.length; i += 1) {
28961                 c = values[i];
28962                 // Ignore the terminating NULL byte(s):
28963                 if (c === '\u0000') {
28964                     break;
28965                 }
28966                 str += c;
28967             }
28968             return str;
28969         }
28970         return values;
28971     }
28972     
28973 });
28974
28975 Roo.apply(Roo.bootstrap.UploadCropbox, {
28976     tags : {
28977         'Orientation': 0x0112
28978     },
28979     
28980     Orientation: {
28981             1: 0, //'top-left',
28982 //            2: 'top-right',
28983             3: 180, //'bottom-right',
28984 //            4: 'bottom-left',
28985 //            5: 'left-top',
28986             6: 90, //'right-top',
28987 //            7: 'right-bottom',
28988             8: 270 //'left-bottom'
28989     },
28990     
28991     exifTagTypes : {
28992         // byte, 8-bit unsigned int:
28993         1: {
28994             getValue: function (dataView, dataOffset) {
28995                 return dataView.getUint8(dataOffset);
28996             },
28997             size: 1
28998         },
28999         // ascii, 8-bit byte:
29000         2: {
29001             getValue: function (dataView, dataOffset) {
29002                 return String.fromCharCode(dataView.getUint8(dataOffset));
29003             },
29004             size: 1,
29005             ascii: true
29006         },
29007         // short, 16 bit int:
29008         3: {
29009             getValue: function (dataView, dataOffset, littleEndian) {
29010                 return dataView.getUint16(dataOffset, littleEndian);
29011             },
29012             size: 2
29013         },
29014         // long, 32 bit int:
29015         4: {
29016             getValue: function (dataView, dataOffset, littleEndian) {
29017                 return dataView.getUint32(dataOffset, littleEndian);
29018             },
29019             size: 4
29020         },
29021         // rational = two long values, first is numerator, second is denominator:
29022         5: {
29023             getValue: function (dataView, dataOffset, littleEndian) {
29024                 return dataView.getUint32(dataOffset, littleEndian) /
29025                     dataView.getUint32(dataOffset + 4, littleEndian);
29026             },
29027             size: 8
29028         },
29029         // slong, 32 bit signed int:
29030         9: {
29031             getValue: function (dataView, dataOffset, littleEndian) {
29032                 return dataView.getInt32(dataOffset, littleEndian);
29033             },
29034             size: 4
29035         },
29036         // srational, two slongs, first is numerator, second is denominator:
29037         10: {
29038             getValue: function (dataView, dataOffset, littleEndian) {
29039                 return dataView.getInt32(dataOffset, littleEndian) /
29040                     dataView.getInt32(dataOffset + 4, littleEndian);
29041             },
29042             size: 8
29043         }
29044     },
29045     
29046     footer : {
29047         STANDARD : [
29048             {
29049                 tag : 'div',
29050                 cls : 'btn-group roo-upload-cropbox-rotate-left',
29051                 action : 'rotate-left',
29052                 cn : [
29053                     {
29054                         tag : 'button',
29055                         cls : 'btn btn-default',
29056                         html : '<i class="fa fa-undo"></i>'
29057                     }
29058                 ]
29059             },
29060             {
29061                 tag : 'div',
29062                 cls : 'btn-group roo-upload-cropbox-picture',
29063                 action : 'picture',
29064                 cn : [
29065                     {
29066                         tag : 'button',
29067                         cls : 'btn btn-default',
29068                         html : '<i class="fa fa-picture-o"></i>'
29069                     }
29070                 ]
29071             },
29072             {
29073                 tag : 'div',
29074                 cls : 'btn-group roo-upload-cropbox-rotate-right',
29075                 action : 'rotate-right',
29076                 cn : [
29077                     {
29078                         tag : 'button',
29079                         cls : 'btn btn-default',
29080                         html : '<i class="fa fa-repeat"></i>'
29081                     }
29082                 ]
29083             }
29084         ],
29085         DOCUMENT : [
29086             {
29087                 tag : 'div',
29088                 cls : 'btn-group roo-upload-cropbox-rotate-left',
29089                 action : 'rotate-left',
29090                 cn : [
29091                     {
29092                         tag : 'button',
29093                         cls : 'btn btn-default',
29094                         html : '<i class="fa fa-undo"></i>'
29095                     }
29096                 ]
29097             },
29098             {
29099                 tag : 'div',
29100                 cls : 'btn-group roo-upload-cropbox-download',
29101                 action : 'download',
29102                 cn : [
29103                     {
29104                         tag : 'button',
29105                         cls : 'btn btn-default',
29106                         html : '<i class="fa fa-download"></i>'
29107                     }
29108                 ]
29109             },
29110             {
29111                 tag : 'div',
29112                 cls : 'btn-group roo-upload-cropbox-crop',
29113                 action : 'crop',
29114                 cn : [
29115                     {
29116                         tag : 'button',
29117                         cls : 'btn btn-default',
29118                         html : '<i class="fa fa-crop"></i>'
29119                     }
29120                 ]
29121             },
29122             {
29123                 tag : 'div',
29124                 cls : 'btn-group roo-upload-cropbox-trash',
29125                 action : 'trash',
29126                 cn : [
29127                     {
29128                         tag : 'button',
29129                         cls : 'btn btn-default',
29130                         html : '<i class="fa fa-trash"></i>'
29131                     }
29132                 ]
29133             },
29134             {
29135                 tag : 'div',
29136                 cls : 'btn-group roo-upload-cropbox-rotate-right',
29137                 action : 'rotate-right',
29138                 cn : [
29139                     {
29140                         tag : 'button',
29141                         cls : 'btn btn-default',
29142                         html : '<i class="fa fa-repeat"></i>'
29143                     }
29144                 ]
29145             }
29146         ],
29147         ROTATOR : [
29148             {
29149                 tag : 'div',
29150                 cls : 'btn-group roo-upload-cropbox-rotate-left',
29151                 action : 'rotate-left',
29152                 cn : [
29153                     {
29154                         tag : 'button',
29155                         cls : 'btn btn-default',
29156                         html : '<i class="fa fa-undo"></i>'
29157                     }
29158                 ]
29159             },
29160             {
29161                 tag : 'div',
29162                 cls : 'btn-group roo-upload-cropbox-rotate-right',
29163                 action : 'rotate-right',
29164                 cn : [
29165                     {
29166                         tag : 'button',
29167                         cls : 'btn btn-default',
29168                         html : '<i class="fa fa-repeat"></i>'
29169                     }
29170                 ]
29171             }
29172         ]
29173     }
29174 });
29175
29176 /*
29177 * Licence: LGPL
29178 */
29179
29180 /**
29181  * @class Roo.bootstrap.DocumentManager
29182  * @extends Roo.bootstrap.Component
29183  * Bootstrap DocumentManager class
29184  * @cfg {String} paramName default 'imageUpload'
29185  * @cfg {String} toolTipName default 'filename'
29186  * @cfg {String} method default POST
29187  * @cfg {String} url action url
29188  * @cfg {Number} boxes number of boxes, 0 is no limit.. default 0
29189  * @cfg {Boolean} multiple multiple upload default true
29190  * @cfg {Number} thumbSize default 300
29191  * @cfg {String} fieldLabel
29192  * @cfg {Number} labelWidth default 4
29193  * @cfg {String} labelAlign (left|top) default left
29194  * @cfg {Boolean} editable (true|false) allow edit when upload a image default true
29195 * @cfg {Number} labellg set the width of label (1-12)
29196  * @cfg {Number} labelmd set the width of label (1-12)
29197  * @cfg {Number} labelsm set the width of label (1-12)
29198  * @cfg {Number} labelxs set the width of label (1-12)
29199  * 
29200  * @constructor
29201  * Create a new DocumentManager
29202  * @param {Object} config The config object
29203  */
29204
29205 Roo.bootstrap.DocumentManager = function(config){
29206     Roo.bootstrap.DocumentManager.superclass.constructor.call(this, config);
29207     
29208     this.files = [];
29209     this.delegates = [];
29210     
29211     this.addEvents({
29212         /**
29213          * @event initial
29214          * Fire when initial the DocumentManager
29215          * @param {Roo.bootstrap.DocumentManager} this
29216          */
29217         "initial" : true,
29218         /**
29219          * @event inspect
29220          * inspect selected file
29221          * @param {Roo.bootstrap.DocumentManager} this
29222          * @param {File} file
29223          */
29224         "inspect" : true,
29225         /**
29226          * @event exception
29227          * Fire when xhr load exception
29228          * @param {Roo.bootstrap.DocumentManager} this
29229          * @param {XMLHttpRequest} xhr
29230          */
29231         "exception" : true,
29232         /**
29233          * @event afterupload
29234          * Fire when xhr load exception
29235          * @param {Roo.bootstrap.DocumentManager} this
29236          * @param {XMLHttpRequest} xhr
29237          */
29238         "afterupload" : true,
29239         /**
29240          * @event prepare
29241          * prepare the form data
29242          * @param {Roo.bootstrap.DocumentManager} this
29243          * @param {Object} formData
29244          */
29245         "prepare" : true,
29246         /**
29247          * @event remove
29248          * Fire when remove the file
29249          * @param {Roo.bootstrap.DocumentManager} this
29250          * @param {Object} file
29251          */
29252         "remove" : true,
29253         /**
29254          * @event refresh
29255          * Fire after refresh the file
29256          * @param {Roo.bootstrap.DocumentManager} this
29257          */
29258         "refresh" : true,
29259         /**
29260          * @event click
29261          * Fire after click the image
29262          * @param {Roo.bootstrap.DocumentManager} this
29263          * @param {Object} file
29264          */
29265         "click" : true,
29266         /**
29267          * @event edit
29268          * Fire when upload a image and editable set to true
29269          * @param {Roo.bootstrap.DocumentManager} this
29270          * @param {Object} file
29271          */
29272         "edit" : true,
29273         /**
29274          * @event beforeselectfile
29275          * Fire before select file
29276          * @param {Roo.bootstrap.DocumentManager} this
29277          */
29278         "beforeselectfile" : true,
29279         /**
29280          * @event process
29281          * Fire before process file
29282          * @param {Roo.bootstrap.DocumentManager} this
29283          * @param {Object} file
29284          */
29285         "process" : true,
29286         /**
29287          * @event previewrendered
29288          * Fire when preview rendered
29289          * @param {Roo.bootstrap.DocumentManager} this
29290          * @param {Object} file
29291          */
29292         "previewrendered" : true,
29293         /**
29294          */
29295         "previewResize" : true
29296         
29297     });
29298 };
29299
29300 Roo.extend(Roo.bootstrap.DocumentManager, Roo.bootstrap.Component,  {
29301     
29302     boxes : 0,
29303     inputName : '',
29304     thumbSize : 300,
29305     multiple : true,
29306     files : false,
29307     method : 'POST',
29308     url : '',
29309     paramName : 'imageUpload',
29310     toolTipName : 'filename',
29311     fieldLabel : '',
29312     labelWidth : 4,
29313     labelAlign : 'left',
29314     editable : true,
29315     delegates : false,
29316     xhr : false, 
29317     
29318     labellg : 0,
29319     labelmd : 0,
29320     labelsm : 0,
29321     labelxs : 0,
29322     
29323     getAutoCreate : function()
29324     {   
29325         var managerWidget = {
29326             tag : 'div',
29327             cls : 'roo-document-manager',
29328             cn : [
29329                 {
29330                     tag : 'input',
29331                     cls : 'roo-document-manager-selector',
29332                     type : 'file'
29333                 },
29334                 {
29335                     tag : 'div',
29336                     cls : 'roo-document-manager-uploader',
29337                     cn : [
29338                         {
29339                             tag : 'div',
29340                             cls : 'roo-document-manager-upload-btn',
29341                             html : '<i class="fa fa-plus"></i>'
29342                         }
29343                     ]
29344                     
29345                 }
29346             ]
29347         };
29348         
29349         var content = [
29350             {
29351                 tag : 'div',
29352                 cls : 'column col-md-12',
29353                 cn : managerWidget
29354             }
29355         ];
29356         
29357         if(this.fieldLabel.length){
29358             
29359             content = [
29360                 {
29361                     tag : 'div',
29362                     cls : 'column col-md-12',
29363                     html : this.fieldLabel
29364                 },
29365                 {
29366                     tag : 'div',
29367                     cls : 'column col-md-12',
29368                     cn : managerWidget
29369                 }
29370             ];
29371
29372             if(this.labelAlign == 'left'){
29373                 content = [
29374                     {
29375                         tag : 'div',
29376                         cls : 'column',
29377                         html : this.fieldLabel
29378                     },
29379                     {
29380                         tag : 'div',
29381                         cls : 'column',
29382                         cn : managerWidget
29383                     }
29384                 ];
29385                 
29386                 if(this.labelWidth > 12){
29387                     content[0].style = "width: " + this.labelWidth + 'px';
29388                 }
29389
29390                 if(this.labelWidth < 13 && this.labelmd == 0){
29391                     this.labelmd = this.labelWidth;
29392                 }
29393
29394                 if(this.labellg > 0){
29395                     content[0].cls += ' col-lg-' + this.labellg;
29396                     content[1].cls += ' col-lg-' + (12 - this.labellg);
29397                 }
29398
29399                 if(this.labelmd > 0){
29400                     content[0].cls += ' col-md-' + this.labelmd;
29401                     content[1].cls += ' col-md-' + (12 - this.labelmd);
29402                 }
29403
29404                 if(this.labelsm > 0){
29405                     content[0].cls += ' col-sm-' + this.labelsm;
29406                     content[1].cls += ' col-sm-' + (12 - this.labelsm);
29407                 }
29408
29409                 if(this.labelxs > 0){
29410                     content[0].cls += ' col-xs-' + this.labelxs;
29411                     content[1].cls += ' col-xs-' + (12 - this.labelxs);
29412                 }
29413                 
29414             }
29415         }
29416         
29417         var cfg = {
29418             tag : 'div',
29419             cls : 'row clearfix',
29420             cn : content
29421         };
29422         
29423         return cfg;
29424         
29425     },
29426     
29427     initEvents : function()
29428     {
29429         this.managerEl = this.el.select('.roo-document-manager', true).first();
29430         this.managerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
29431         
29432         this.selectorEl = this.el.select('.roo-document-manager-selector', true).first();
29433         this.selectorEl.hide();
29434         
29435         if(this.multiple){
29436             this.selectorEl.attr('multiple', 'multiple');
29437         }
29438         
29439         this.selectorEl.on('change', this.onFileSelected, this);
29440         
29441         this.uploader = this.el.select('.roo-document-manager-uploader', true).first();
29442         this.uploader.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
29443         
29444         this.uploader.on('click', this.onUploaderClick, this);
29445         
29446         this.renderProgressDialog();
29447         
29448         var _this = this;
29449         
29450         window.addEventListener("resize", function() { _this.refresh(); } );
29451         
29452         this.fireEvent('initial', this);
29453     },
29454     
29455     renderProgressDialog : function()
29456     {
29457         var _this = this;
29458         
29459         this.progressDialog = new Roo.bootstrap.Modal({
29460             cls : 'roo-document-manager-progress-dialog',
29461             allow_close : false,
29462             animate : false,
29463             title : '',
29464             buttons : [
29465                 {
29466                     name  :'cancel',
29467                     weight : 'danger',
29468                     html : 'Cancel'
29469                 }
29470             ], 
29471             listeners : { 
29472                 btnclick : function() {
29473                     _this.uploadCancel();
29474                     this.hide();
29475                 }
29476             }
29477         });
29478          
29479         this.progressDialog.render(Roo.get(document.body));
29480          
29481         this.progress = new Roo.bootstrap.Progress({
29482             cls : 'roo-document-manager-progress',
29483             active : true,
29484             striped : true
29485         });
29486         
29487         this.progress.render(this.progressDialog.getChildContainer());
29488         
29489         this.progressBar = new Roo.bootstrap.ProgressBar({
29490             cls : 'roo-document-manager-progress-bar',
29491             aria_valuenow : 0,
29492             aria_valuemin : 0,
29493             aria_valuemax : 12,
29494             panel : 'success'
29495         });
29496         
29497         this.progressBar.render(this.progress.getChildContainer());
29498     },
29499     
29500     onUploaderClick : function(e)
29501     {
29502         e.preventDefault();
29503      
29504         if(this.fireEvent('beforeselectfile', this) != false){
29505             this.selectorEl.dom.click();
29506         }
29507         
29508     },
29509     
29510     onFileSelected : function(e)
29511     {
29512         e.preventDefault();
29513         
29514         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
29515             return;
29516         }
29517         
29518         Roo.each(this.selectorEl.dom.files, function(file){
29519             if(this.fireEvent('inspect', this, file) != false){
29520                 this.files.push(file);
29521             }
29522         }, this);
29523         
29524         this.queue();
29525         
29526     },
29527     
29528     queue : function()
29529     {
29530         this.selectorEl.dom.value = '';
29531         
29532         if(!this.files || !this.files.length){
29533             return;
29534         }
29535         
29536         if(this.boxes > 0 && this.files.length > this.boxes){
29537             this.files = this.files.slice(0, this.boxes);
29538         }
29539         
29540         this.uploader.show();
29541         
29542         if(this.boxes > 0 && this.files.length > this.boxes - 1){
29543             this.uploader.hide();
29544         }
29545         
29546         var _this = this;
29547         
29548         var files = [];
29549         
29550         var docs = [];
29551         
29552         Roo.each(this.files, function(file){
29553             
29554             if(typeof(file.id) != 'undefined' && file.id * 1 > 0){
29555                 var f = this.renderPreview(file);
29556                 files.push(f);
29557                 return;
29558             }
29559             
29560             if(file.type.indexOf('image') != -1){
29561                 this.delegates.push(
29562                     (function(){
29563                         _this.process(file);
29564                     }).createDelegate(this)
29565                 );
29566         
29567                 return;
29568             }
29569             
29570             docs.push(
29571                 (function(){
29572                     _this.process(file);
29573                 }).createDelegate(this)
29574             );
29575             
29576         }, this);
29577         
29578         this.files = files;
29579         
29580         this.delegates = this.delegates.concat(docs);
29581         
29582         if(!this.delegates.length){
29583             this.refresh();
29584             return;
29585         }
29586         
29587         this.progressBar.aria_valuemax = this.delegates.length;
29588         
29589         this.arrange();
29590         
29591         return;
29592     },
29593     
29594     arrange : function()
29595     {
29596         if(!this.delegates.length){
29597             this.progressDialog.hide();
29598             this.refresh();
29599             return;
29600         }
29601         
29602         var delegate = this.delegates.shift();
29603         
29604         this.progressDialog.show();
29605         
29606         this.progressDialog.setTitle((this.progressBar.aria_valuemax - this.delegates.length) + ' / ' + this.progressBar.aria_valuemax);
29607         
29608         this.progressBar.update(this.progressBar.aria_valuemax - this.delegates.length);
29609         
29610         delegate();
29611     },
29612     
29613     refresh : function()
29614     {
29615         this.uploader.show();
29616         
29617         if(this.boxes > 0 && this.files.length > this.boxes - 1){
29618             this.uploader.hide();
29619         }
29620         
29621         Roo.isTouch ? this.closable(false) : this.closable(true);
29622         
29623         this.fireEvent('refresh', this);
29624     },
29625     
29626     onRemove : function(e, el, o)
29627     {
29628         e.preventDefault();
29629         
29630         this.fireEvent('remove', this, o);
29631         
29632     },
29633     
29634     remove : function(o)
29635     {
29636         var files = [];
29637         
29638         Roo.each(this.files, function(file){
29639             if(typeof(file.id) == 'undefined' || file.id * 1 < 1 || file.id != o.id){
29640                 files.push(file);
29641                 return;
29642             }
29643
29644             o.target.remove();
29645
29646         }, this);
29647         
29648         this.files = files;
29649         
29650         this.refresh();
29651     },
29652     
29653     clear : function()
29654     {
29655         Roo.each(this.files, function(file){
29656             if(!file.target){
29657                 return;
29658             }
29659             
29660             file.target.remove();
29661
29662         }, this);
29663         
29664         this.files = [];
29665         
29666         this.refresh();
29667     },
29668     
29669     onClick : function(e, el, o)
29670     {
29671         e.preventDefault();
29672         
29673         this.fireEvent('click', this, o);
29674         
29675     },
29676     
29677     closable : function(closable)
29678     {
29679         Roo.each(this.managerEl.select('.roo-document-manager-preview > button.close', true).elements, function(el){
29680             
29681             el.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
29682             
29683             if(closable){
29684                 el.show();
29685                 return;
29686             }
29687             
29688             el.hide();
29689             
29690         }, this);
29691     },
29692     
29693     xhrOnLoad : function(xhr)
29694     {
29695         Roo.each(this.managerEl.select('.roo-document-manager-loading', true).elements, function(el){
29696             el.remove();
29697         }, this);
29698         
29699         if (xhr.readyState !== 4) {
29700             this.arrange();
29701             this.fireEvent('exception', this, xhr);
29702             return;
29703         }
29704
29705         var response = Roo.decode(xhr.responseText);
29706         
29707         if(!response.success){
29708             this.arrange();
29709             this.fireEvent('exception', this, xhr);
29710             return;
29711         }
29712         
29713         var file = this.renderPreview(response.data);
29714         
29715         this.files.push(file);
29716         
29717         this.arrange();
29718         
29719         this.fireEvent('afterupload', this, xhr);
29720         
29721     },
29722     
29723     xhrOnError : function(xhr)
29724     {
29725         Roo.log('xhr on error');
29726         
29727         var response = Roo.decode(xhr.responseText);
29728           
29729         Roo.log(response);
29730         
29731         this.arrange();
29732     },
29733     
29734     process : function(file)
29735     {
29736         if(this.fireEvent('process', this, file) !== false){
29737             if(this.editable && file.type.indexOf('image') != -1){
29738                 this.fireEvent('edit', this, file);
29739                 return;
29740             }
29741
29742             this.uploadStart(file, false);
29743
29744             return;
29745         }
29746         
29747     },
29748     
29749     uploadStart : function(file, crop)
29750     {
29751         this.xhr = new XMLHttpRequest();
29752         
29753         if(typeof(file.id) != 'undefined' && file.id * 1 > 0){
29754             this.arrange();
29755             return;
29756         }
29757         
29758         file.xhr = this.xhr;
29759             
29760         this.managerEl.createChild({
29761             tag : 'div',
29762             cls : 'roo-document-manager-loading',
29763             cn : [
29764                 {
29765                     tag : 'div',
29766                     tooltip : file.name,
29767                     cls : 'roo-document-manager-thumb',
29768                     html : '<i class="fa fa-circle-o-notch fa-spin"></i>'
29769                 }
29770             ]
29771
29772         });
29773
29774         this.xhr.open(this.method, this.url, true);
29775         
29776         var headers = {
29777             "Accept": "application/json",
29778             "Cache-Control": "no-cache",
29779             "X-Requested-With": "XMLHttpRequest"
29780         };
29781         
29782         for (var headerName in headers) {
29783             var headerValue = headers[headerName];
29784             if (headerValue) {
29785                 this.xhr.setRequestHeader(headerName, headerValue);
29786             }
29787         }
29788         
29789         var _this = this;
29790         
29791         this.xhr.onload = function()
29792         {
29793             _this.xhrOnLoad(_this.xhr);
29794         }
29795         
29796         this.xhr.onerror = function()
29797         {
29798             _this.xhrOnError(_this.xhr);
29799         }
29800         
29801         var formData = new FormData();
29802
29803         formData.append('returnHTML', 'NO');
29804         
29805         if(crop){
29806             formData.append('crop', crop);
29807         }
29808         
29809         formData.append(this.paramName, file, file.name);
29810         
29811         var options = {
29812             file : file, 
29813             manually : false
29814         };
29815         
29816         if(this.fireEvent('prepare', this, formData, options) != false){
29817             
29818             if(options.manually){
29819                 return;
29820             }
29821             
29822             this.xhr.send(formData);
29823             return;
29824         };
29825         
29826         this.uploadCancel();
29827     },
29828     
29829     uploadCancel : function()
29830     {
29831         if (this.xhr) {
29832             this.xhr.abort();
29833         }
29834         
29835         this.delegates = [];
29836         
29837         Roo.each(this.managerEl.select('.roo-document-manager-loading', true).elements, function(el){
29838             el.remove();
29839         }, this);
29840         
29841         this.arrange();
29842     },
29843     
29844     renderPreview : function(file)
29845     {
29846         if(typeof(file.target) != 'undefined' && file.target){
29847             return file;
29848         }
29849         
29850         var img_src = encodeURI(baseURL +'/Images/Thumb/' + this.thumbSize + '/' + file.id + '/' + file.filename);
29851         
29852         var previewEl = this.managerEl.createChild({
29853             tag : 'div',
29854             cls : 'roo-document-manager-preview',
29855             cn : [
29856                 {
29857                     tag : 'div',
29858                     tooltip : file[this.toolTipName],
29859                     cls : 'roo-document-manager-thumb',
29860                     html : '<img tooltip="' + file[this.toolTipName] + '" src="' + img_src + '">'
29861                 },
29862                 {
29863                     tag : 'button',
29864                     cls : 'close',
29865                     html : '<i class="fa fa-times-circle"></i>'
29866                 }
29867             ]
29868         });
29869
29870         var close = previewEl.select('button.close', true).first();
29871
29872         close.on('click', this.onRemove, this, file);
29873
29874         file.target = previewEl;
29875
29876         var image = previewEl.select('img', true).first();
29877         
29878         var _this = this;
29879         
29880         image.dom.addEventListener("load", function(){ _this.onPreviewLoad(file, image); });
29881         
29882         image.on('click', this.onClick, this, file);
29883         
29884         this.fireEvent('previewrendered', this, file);
29885         
29886         return file;
29887         
29888     },
29889     
29890     onPreviewLoad : function(file, image)
29891     {
29892         if(typeof(file.target) == 'undefined' || !file.target){
29893             return;
29894         }
29895         
29896         var width = image.dom.naturalWidth || image.dom.width;
29897         var height = image.dom.naturalHeight || image.dom.height;
29898         
29899         if(!this.previewResize) {
29900             return;
29901         }
29902         
29903         if(width > height){
29904             file.target.addClass('wide');
29905             return;
29906         }
29907         
29908         file.target.addClass('tall');
29909         return;
29910         
29911     },
29912     
29913     uploadFromSource : function(file, crop)
29914     {
29915         this.xhr = new XMLHttpRequest();
29916         
29917         this.managerEl.createChild({
29918             tag : 'div',
29919             cls : 'roo-document-manager-loading',
29920             cn : [
29921                 {
29922                     tag : 'div',
29923                     tooltip : file.name,
29924                     cls : 'roo-document-manager-thumb',
29925                     html : '<i class="fa fa-circle-o-notch fa-spin"></i>'
29926                 }
29927             ]
29928
29929         });
29930
29931         this.xhr.open(this.method, this.url, true);
29932         
29933         var headers = {
29934             "Accept": "application/json",
29935             "Cache-Control": "no-cache",
29936             "X-Requested-With": "XMLHttpRequest"
29937         };
29938         
29939         for (var headerName in headers) {
29940             var headerValue = headers[headerName];
29941             if (headerValue) {
29942                 this.xhr.setRequestHeader(headerName, headerValue);
29943             }
29944         }
29945         
29946         var _this = this;
29947         
29948         this.xhr.onload = function()
29949         {
29950             _this.xhrOnLoad(_this.xhr);
29951         }
29952         
29953         this.xhr.onerror = function()
29954         {
29955             _this.xhrOnError(_this.xhr);
29956         }
29957         
29958         var formData = new FormData();
29959
29960         formData.append('returnHTML', 'NO');
29961         
29962         formData.append('crop', crop);
29963         
29964         if(typeof(file.filename) != 'undefined'){
29965             formData.append('filename', file.filename);
29966         }
29967         
29968         if(typeof(file.mimetype) != 'undefined'){
29969             formData.append('mimetype', file.mimetype);
29970         }
29971         
29972         Roo.log(formData);
29973         
29974         if(this.fireEvent('prepare', this, formData) != false){
29975             this.xhr.send(formData);
29976         };
29977     }
29978 });
29979
29980 /*
29981 * Licence: LGPL
29982 */
29983
29984 /**
29985  * @class Roo.bootstrap.DocumentViewer
29986  * @extends Roo.bootstrap.Component
29987  * Bootstrap DocumentViewer class
29988  * @cfg {Boolean} showDownload (true|false) show download button (default true)
29989  * @cfg {Boolean} showTrash (true|false) show trash button (default true)
29990  * 
29991  * @constructor
29992  * Create a new DocumentViewer
29993  * @param {Object} config The config object
29994  */
29995
29996 Roo.bootstrap.DocumentViewer = function(config){
29997     Roo.bootstrap.DocumentViewer.superclass.constructor.call(this, config);
29998     
29999     this.addEvents({
30000         /**
30001          * @event initial
30002          * Fire after initEvent
30003          * @param {Roo.bootstrap.DocumentViewer} this
30004          */
30005         "initial" : true,
30006         /**
30007          * @event click
30008          * Fire after click
30009          * @param {Roo.bootstrap.DocumentViewer} this
30010          */
30011         "click" : true,
30012         /**
30013          * @event download
30014          * Fire after download button
30015          * @param {Roo.bootstrap.DocumentViewer} this
30016          */
30017         "download" : true,
30018         /**
30019          * @event trash
30020          * Fire after trash button
30021          * @param {Roo.bootstrap.DocumentViewer} this
30022          */
30023         "trash" : true
30024         
30025     });
30026 };
30027
30028 Roo.extend(Roo.bootstrap.DocumentViewer, Roo.bootstrap.Component,  {
30029     
30030     showDownload : true,
30031     
30032     showTrash : true,
30033     
30034     getAutoCreate : function()
30035     {
30036         var cfg = {
30037             tag : 'div',
30038             cls : 'roo-document-viewer',
30039             cn : [
30040                 {
30041                     tag : 'div',
30042                     cls : 'roo-document-viewer-body',
30043                     cn : [
30044                         {
30045                             tag : 'div',
30046                             cls : 'roo-document-viewer-thumb',
30047                             cn : [
30048                                 {
30049                                     tag : 'img',
30050                                     cls : 'roo-document-viewer-image'
30051                                 }
30052                             ]
30053                         }
30054                     ]
30055                 },
30056                 {
30057                     tag : 'div',
30058                     cls : 'roo-document-viewer-footer',
30059                     cn : {
30060                         tag : 'div',
30061                         cls : 'btn-group btn-group-justified roo-document-viewer-btn-group',
30062                         cn : [
30063                             {
30064                                 tag : 'div',
30065                                 cls : 'btn-group roo-document-viewer-download',
30066                                 cn : [
30067                                     {
30068                                         tag : 'button',
30069                                         cls : 'btn btn-default',
30070                                         html : '<i class="fa fa-download"></i>'
30071                                     }
30072                                 ]
30073                             },
30074                             {
30075                                 tag : 'div',
30076                                 cls : 'btn-group roo-document-viewer-trash',
30077                                 cn : [
30078                                     {
30079                                         tag : 'button',
30080                                         cls : 'btn btn-default',
30081                                         html : '<i class="fa fa-trash"></i>'
30082                                     }
30083                                 ]
30084                             }
30085                         ]
30086                     }
30087                 }
30088             ]
30089         };
30090         
30091         return cfg;
30092     },
30093     
30094     initEvents : function()
30095     {
30096         this.bodyEl = this.el.select('.roo-document-viewer-body', true).first();
30097         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY);
30098         
30099         this.thumbEl = this.el.select('.roo-document-viewer-thumb', true).first();
30100         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY);
30101         
30102         this.imageEl = this.el.select('.roo-document-viewer-image', true).first();
30103         this.imageEl.setVisibilityMode(Roo.Element.DISPLAY);
30104         
30105         this.footerEl = this.el.select('.roo-document-viewer-footer', true).first();
30106         this.footerEl.setVisibilityMode(Roo.Element.DISPLAY);
30107         
30108         this.downloadBtn = this.el.select('.roo-document-viewer-download', true).first();
30109         this.downloadBtn.setVisibilityMode(Roo.Element.DISPLAY);
30110         
30111         this.trashBtn = this.el.select('.roo-document-viewer-trash', true).first();
30112         this.trashBtn.setVisibilityMode(Roo.Element.DISPLAY);
30113         
30114         this.bodyEl.on('click', this.onClick, this);
30115         this.downloadBtn.on('click', this.onDownload, this);
30116         this.trashBtn.on('click', this.onTrash, this);
30117         
30118         this.downloadBtn.hide();
30119         this.trashBtn.hide();
30120         
30121         if(this.showDownload){
30122             this.downloadBtn.show();
30123         }
30124         
30125         if(this.showTrash){
30126             this.trashBtn.show();
30127         }
30128         
30129         if(!this.showDownload && !this.showTrash) {
30130             this.footerEl.hide();
30131         }
30132         
30133     },
30134     
30135     initial : function()
30136     {
30137         this.fireEvent('initial', this);
30138         
30139     },
30140     
30141     onClick : function(e)
30142     {
30143         e.preventDefault();
30144         
30145         this.fireEvent('click', this);
30146     },
30147     
30148     onDownload : function(e)
30149     {
30150         e.preventDefault();
30151         
30152         this.fireEvent('download', this);
30153     },
30154     
30155     onTrash : function(e)
30156     {
30157         e.preventDefault();
30158         
30159         this.fireEvent('trash', this);
30160     }
30161     
30162 });
30163 /*
30164  * - LGPL
30165  *
30166  * nav progress bar
30167  * 
30168  */
30169
30170 /**
30171  * @class Roo.bootstrap.NavProgressBar
30172  * @extends Roo.bootstrap.Component
30173  * Bootstrap NavProgressBar class
30174  * 
30175  * @constructor
30176  * Create a new nav progress bar
30177  * @param {Object} config The config object
30178  */
30179
30180 Roo.bootstrap.NavProgressBar = function(config){
30181     Roo.bootstrap.NavProgressBar.superclass.constructor.call(this, config);
30182
30183     this.bullets = this.bullets || [];
30184    
30185 //    Roo.bootstrap.NavProgressBar.register(this);
30186      this.addEvents({
30187         /**
30188              * @event changed
30189              * Fires when the active item changes
30190              * @param {Roo.bootstrap.NavProgressBar} this
30191              * @param {Roo.bootstrap.NavProgressItem} selected The item selected
30192              * @param {Roo.bootstrap.NavProgressItem} prev The previously selected item 
30193          */
30194         'changed': true
30195      });
30196     
30197 };
30198
30199 Roo.extend(Roo.bootstrap.NavProgressBar, Roo.bootstrap.Component,  {
30200     
30201     bullets : [],
30202     barItems : [],
30203     
30204     getAutoCreate : function()
30205     {
30206         var cfg = Roo.apply({}, Roo.bootstrap.NavProgressBar.superclass.getAutoCreate.call(this));
30207         
30208         cfg = {
30209             tag : 'div',
30210             cls : 'roo-navigation-bar-group',
30211             cn : [
30212                 {
30213                     tag : 'div',
30214                     cls : 'roo-navigation-top-bar'
30215                 },
30216                 {
30217                     tag : 'div',
30218                     cls : 'roo-navigation-bullets-bar',
30219                     cn : [
30220                         {
30221                             tag : 'ul',
30222                             cls : 'roo-navigation-bar'
30223                         }
30224                     ]
30225                 },
30226                 
30227                 {
30228                     tag : 'div',
30229                     cls : 'roo-navigation-bottom-bar'
30230                 }
30231             ]
30232             
30233         };
30234         
30235         return cfg;
30236         
30237     },
30238     
30239     initEvents: function() 
30240     {
30241         
30242     },
30243     
30244     onRender : function(ct, position) 
30245     {
30246         Roo.bootstrap.NavProgressBar.superclass.onRender.call(this, ct, position);
30247         
30248         if(this.bullets.length){
30249             Roo.each(this.bullets, function(b){
30250                this.addItem(b);
30251             }, this);
30252         }
30253         
30254         this.format();
30255         
30256     },
30257     
30258     addItem : function(cfg)
30259     {
30260         var item = new Roo.bootstrap.NavProgressItem(cfg);
30261         
30262         item.parentId = this.id;
30263         item.render(this.el.select('.roo-navigation-bar', true).first(), null);
30264         
30265         if(cfg.html){
30266             var top = new Roo.bootstrap.Element({
30267                 tag : 'div',
30268                 cls : 'roo-navigation-bar-text'
30269             });
30270             
30271             var bottom = new Roo.bootstrap.Element({
30272                 tag : 'div',
30273                 cls : 'roo-navigation-bar-text'
30274             });
30275             
30276             top.onRender(this.el.select('.roo-navigation-top-bar', true).first(), null);
30277             bottom.onRender(this.el.select('.roo-navigation-bottom-bar', true).first(), null);
30278             
30279             var topText = new Roo.bootstrap.Element({
30280                 tag : 'span',
30281                 html : (typeof(cfg.position) != 'undefined' && cfg.position == 'top') ? cfg.html : ''
30282             });
30283             
30284             var bottomText = new Roo.bootstrap.Element({
30285                 tag : 'span',
30286                 html : (typeof(cfg.position) != 'undefined' && cfg.position == 'top') ? '' : cfg.html
30287             });
30288             
30289             topText.onRender(top.el, null);
30290             bottomText.onRender(bottom.el, null);
30291             
30292             item.topEl = top;
30293             item.bottomEl = bottom;
30294         }
30295         
30296         this.barItems.push(item);
30297         
30298         return item;
30299     },
30300     
30301     getActive : function()
30302     {
30303         var active = false;
30304         
30305         Roo.each(this.barItems, function(v){
30306             
30307             if (!v.isActive()) {
30308                 return;
30309             }
30310             
30311             active = v;
30312             return false;
30313             
30314         });
30315         
30316         return active;
30317     },
30318     
30319     setActiveItem : function(item)
30320     {
30321         var prev = false;
30322         
30323         Roo.each(this.barItems, function(v){
30324             if (v.rid == item.rid) {
30325                 return ;
30326             }
30327             
30328             if (v.isActive()) {
30329                 v.setActive(false);
30330                 prev = v;
30331             }
30332         });
30333
30334         item.setActive(true);
30335         
30336         this.fireEvent('changed', this, item, prev);
30337     },
30338     
30339     getBarItem: function(rid)
30340     {
30341         var ret = false;
30342         
30343         Roo.each(this.barItems, function(e) {
30344             if (e.rid != rid) {
30345                 return;
30346             }
30347             
30348             ret =  e;
30349             return false;
30350         });
30351         
30352         return ret;
30353     },
30354     
30355     indexOfItem : function(item)
30356     {
30357         var index = false;
30358         
30359         Roo.each(this.barItems, function(v, i){
30360             
30361             if (v.rid != item.rid) {
30362                 return;
30363             }
30364             
30365             index = i;
30366             return false
30367         });
30368         
30369         return index;
30370     },
30371     
30372     setActiveNext : function()
30373     {
30374         var i = this.indexOfItem(this.getActive());
30375         
30376         if (i > this.barItems.length) {
30377             return;
30378         }
30379         
30380         this.setActiveItem(this.barItems[i+1]);
30381     },
30382     
30383     setActivePrev : function()
30384     {
30385         var i = this.indexOfItem(this.getActive());
30386         
30387         if (i  < 1) {
30388             return;
30389         }
30390         
30391         this.setActiveItem(this.barItems[i-1]);
30392     },
30393     
30394     format : function()
30395     {
30396         if(!this.barItems.length){
30397             return;
30398         }
30399      
30400         var width = 100 / this.barItems.length;
30401         
30402         Roo.each(this.barItems, function(i){
30403             i.el.setStyle('width', width + '%');
30404             i.topEl.el.setStyle('width', width + '%');
30405             i.bottomEl.el.setStyle('width', width + '%');
30406         }, this);
30407         
30408     }
30409     
30410 });
30411 /*
30412  * - LGPL
30413  *
30414  * Nav Progress Item
30415  * 
30416  */
30417
30418 /**
30419  * @class Roo.bootstrap.NavProgressItem
30420  * @extends Roo.bootstrap.Component
30421  * Bootstrap NavProgressItem class
30422  * @cfg {String} rid the reference id
30423  * @cfg {Boolean} active (true|false) Is item active default false
30424  * @cfg {Boolean} disabled (true|false) Is item active default false
30425  * @cfg {String} html
30426  * @cfg {String} position (top|bottom) text position default bottom
30427  * @cfg {String} icon show icon instead of number
30428  * 
30429  * @constructor
30430  * Create a new NavProgressItem
30431  * @param {Object} config The config object
30432  */
30433 Roo.bootstrap.NavProgressItem = function(config){
30434     Roo.bootstrap.NavProgressItem.superclass.constructor.call(this, config);
30435     this.addEvents({
30436         // raw events
30437         /**
30438          * @event click
30439          * The raw click event for the entire grid.
30440          * @param {Roo.bootstrap.NavProgressItem} this
30441          * @param {Roo.EventObject} e
30442          */
30443         "click" : true
30444     });
30445    
30446 };
30447
30448 Roo.extend(Roo.bootstrap.NavProgressItem, Roo.bootstrap.Component,  {
30449     
30450     rid : '',
30451     active : false,
30452     disabled : false,
30453     html : '',
30454     position : 'bottom',
30455     icon : false,
30456     
30457     getAutoCreate : function()
30458     {
30459         var iconCls = 'roo-navigation-bar-item-icon';
30460         
30461         iconCls += ((this.icon) ? (' ' + this.icon) : (' step-number')) ;
30462         
30463         var cfg = {
30464             tag: 'li',
30465             cls: 'roo-navigation-bar-item',
30466             cn : [
30467                 {
30468                     tag : 'i',
30469                     cls : iconCls
30470                 }
30471             ]
30472         };
30473         
30474         if(this.active){
30475             cfg.cls += ' active';
30476         }
30477         if(this.disabled){
30478             cfg.cls += ' disabled';
30479         }
30480         
30481         return cfg;
30482     },
30483     
30484     disable : function()
30485     {
30486         this.setDisabled(true);
30487     },
30488     
30489     enable : function()
30490     {
30491         this.setDisabled(false);
30492     },
30493     
30494     initEvents: function() 
30495     {
30496         this.iconEl = this.el.select('.roo-navigation-bar-item-icon', true).first();
30497         
30498         this.iconEl.on('click', this.onClick, this);
30499     },
30500     
30501     onClick : function(e)
30502     {
30503         e.preventDefault();
30504         
30505         if(this.disabled){
30506             return;
30507         }
30508         
30509         if(this.fireEvent('click', this, e) === false){
30510             return;
30511         };
30512         
30513         this.parent().setActiveItem(this);
30514     },
30515     
30516     isActive: function () 
30517     {
30518         return this.active;
30519     },
30520     
30521     setActive : function(state)
30522     {
30523         if(this.active == state){
30524             return;
30525         }
30526         
30527         this.active = state;
30528         
30529         if (state) {
30530             this.el.addClass('active');
30531             return;
30532         }
30533         
30534         this.el.removeClass('active');
30535         
30536         return;
30537     },
30538     
30539     setDisabled : function(state)
30540     {
30541         if(this.disabled == state){
30542             return;
30543         }
30544         
30545         this.disabled = state;
30546         
30547         if (state) {
30548             this.el.addClass('disabled');
30549             return;
30550         }
30551         
30552         this.el.removeClass('disabled');
30553     },
30554     
30555     tooltipEl : function()
30556     {
30557         return this.el.select('.roo-navigation-bar-item-icon', true).first();;
30558     }
30559 });
30560  
30561
30562  /*
30563  * - LGPL
30564  *
30565  * FieldLabel
30566  * 
30567  */
30568
30569 /**
30570  * @class Roo.bootstrap.FieldLabel
30571  * @extends Roo.bootstrap.Component
30572  * Bootstrap FieldLabel class
30573  * @cfg {String} html contents of the element
30574  * @cfg {String} tag tag of the element default label
30575  * @cfg {String} cls class of the element
30576  * @cfg {String} target label target 
30577  * @cfg {Boolean} allowBlank (true|false) target allowBlank default true
30578  * @cfg {String} invalidClass DEPRICATED - BS4 uses is-invalid
30579  * @cfg {String} validClass DEPRICATED - BS4 uses is-valid
30580  * @cfg {String} iconTooltip default "This field is required"
30581  * @cfg {String} indicatorpos (left|right) default left
30582  * 
30583  * @constructor
30584  * Create a new FieldLabel
30585  * @param {Object} config The config object
30586  */
30587
30588 Roo.bootstrap.FieldLabel = function(config){
30589     Roo.bootstrap.Element.superclass.constructor.call(this, config);
30590     
30591     this.addEvents({
30592             /**
30593              * @event invalid
30594              * Fires after the field has been marked as invalid.
30595              * @param {Roo.form.FieldLabel} this
30596              * @param {String} msg The validation message
30597              */
30598             invalid : true,
30599             /**
30600              * @event valid
30601              * Fires after the field has been validated with no errors.
30602              * @param {Roo.form.FieldLabel} this
30603              */
30604             valid : true
30605         });
30606 };
30607
30608 Roo.extend(Roo.bootstrap.FieldLabel, Roo.bootstrap.Component,  {
30609     
30610     tag: 'label',
30611     cls: '',
30612     html: '',
30613     target: '',
30614     allowBlank : true,
30615     invalidClass : 'has-warning',
30616     validClass : 'has-success',
30617     iconTooltip : 'This field is required',
30618     indicatorpos : 'left',
30619     
30620     getAutoCreate : function(){
30621         
30622         var cls = "";
30623         if (!this.allowBlank) {
30624             cls  = "visible";
30625         }
30626         
30627         var cfg = {
30628             tag : this.tag,
30629             cls : 'roo-bootstrap-field-label ' + this.cls,
30630             for : this.target,
30631             cn : [
30632                 {
30633                     tag : 'i',
30634                     cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star ' + cls,
30635                     tooltip : this.iconTooltip
30636                 },
30637                 {
30638                     tag : 'span',
30639                     html : this.html
30640                 }
30641             ] 
30642         };
30643         
30644         if(this.indicatorpos == 'right'){
30645             var cfg = {
30646                 tag : this.tag,
30647                 cls : 'roo-bootstrap-field-label ' + this.cls,
30648                 for : this.target,
30649                 cn : [
30650                     {
30651                         tag : 'span',
30652                         html : this.html
30653                     },
30654                     {
30655                         tag : 'i',
30656                         cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star '+ cls,
30657                         tooltip : this.iconTooltip
30658                     }
30659                 ] 
30660             };
30661         }
30662         
30663         return cfg;
30664     },
30665     
30666     initEvents: function() 
30667     {
30668         Roo.bootstrap.Element.superclass.initEvents.call(this);
30669         
30670         this.indicator = this.indicatorEl();
30671         
30672         if(this.indicator){
30673             this.indicator.removeClass('visible');
30674             this.indicator.addClass('invisible');
30675         }
30676         
30677         Roo.bootstrap.FieldLabel.register(this);
30678     },
30679     
30680     indicatorEl : function()
30681     {
30682         var indicator = this.el.select('i.roo-required-indicator',true).first();
30683         
30684         if(!indicator){
30685             return false;
30686         }
30687         
30688         return indicator;
30689         
30690     },
30691     
30692     /**
30693      * Mark this field as valid
30694      */
30695     markValid : function()
30696     {
30697         if(this.indicator){
30698             this.indicator.removeClass('visible');
30699             this.indicator.addClass('invisible');
30700         }
30701         if (Roo.bootstrap.version == 3) {
30702             this.el.removeClass(this.invalidClass);
30703             this.el.addClass(this.validClass);
30704         } else {
30705             this.el.removeClass('is-invalid');
30706             this.el.addClass('is-valid');
30707         }
30708         
30709         
30710         this.fireEvent('valid', this);
30711     },
30712     
30713     /**
30714      * Mark this field as invalid
30715      * @param {String} msg The validation message
30716      */
30717     markInvalid : function(msg)
30718     {
30719         if(this.indicator){
30720             this.indicator.removeClass('invisible');
30721             this.indicator.addClass('visible');
30722         }
30723           if (Roo.bootstrap.version == 3) {
30724             this.el.removeClass(this.validClass);
30725             this.el.addClass(this.invalidClass);
30726         } else {
30727             this.el.removeClass('is-valid');
30728             this.el.addClass('is-invalid');
30729         }
30730         
30731         
30732         this.fireEvent('invalid', this, msg);
30733     }
30734     
30735    
30736 });
30737
30738 Roo.apply(Roo.bootstrap.FieldLabel, {
30739     
30740     groups: {},
30741     
30742      /**
30743     * register a FieldLabel Group
30744     * @param {Roo.bootstrap.FieldLabel} the FieldLabel to add
30745     */
30746     register : function(label)
30747     {
30748         if(this.groups.hasOwnProperty(label.target)){
30749             return;
30750         }
30751      
30752         this.groups[label.target] = label;
30753         
30754     },
30755     /**
30756     * fetch a FieldLabel Group based on the target
30757     * @param {string} target
30758     * @returns {Roo.bootstrap.FieldLabel} the CheckBox group
30759     */
30760     get: function(target) {
30761         if (typeof(this.groups[target]) == 'undefined') {
30762             return false;
30763         }
30764         
30765         return this.groups[target] ;
30766     }
30767 });
30768
30769  
30770
30771  /*
30772  * - LGPL
30773  *
30774  * page DateSplitField.
30775  * 
30776  */
30777
30778
30779 /**
30780  * @class Roo.bootstrap.DateSplitField
30781  * @extends Roo.bootstrap.Component
30782  * Bootstrap DateSplitField class
30783  * @cfg {string} fieldLabel - the label associated
30784  * @cfg {Number} labelWidth set the width of label (0-12)
30785  * @cfg {String} labelAlign (top|left)
30786  * @cfg {Boolean} dayAllowBlank (true|false) default false
30787  * @cfg {Boolean} monthAllowBlank (true|false) default false
30788  * @cfg {Boolean} yearAllowBlank (true|false) default false
30789  * @cfg {string} dayPlaceholder 
30790  * @cfg {string} monthPlaceholder
30791  * @cfg {string} yearPlaceholder
30792  * @cfg {string} dayFormat default 'd'
30793  * @cfg {string} monthFormat default 'm'
30794  * @cfg {string} yearFormat default 'Y'
30795  * @cfg {Number} labellg set the width of label (1-12)
30796  * @cfg {Number} labelmd set the width of label (1-12)
30797  * @cfg {Number} labelsm set the width of label (1-12)
30798  * @cfg {Number} labelxs set the width of label (1-12)
30799
30800  *     
30801  * @constructor
30802  * Create a new DateSplitField
30803  * @param {Object} config The config object
30804  */
30805
30806 Roo.bootstrap.DateSplitField = function(config){
30807     Roo.bootstrap.DateSplitField.superclass.constructor.call(this, config);
30808     
30809     this.addEvents({
30810         // raw events
30811          /**
30812          * @event years
30813          * getting the data of years
30814          * @param {Roo.bootstrap.DateSplitField} this
30815          * @param {Object} years
30816          */
30817         "years" : true,
30818         /**
30819          * @event days
30820          * getting the data of days
30821          * @param {Roo.bootstrap.DateSplitField} this
30822          * @param {Object} days
30823          */
30824         "days" : true,
30825         /**
30826          * @event invalid
30827          * Fires after the field has been marked as invalid.
30828          * @param {Roo.form.Field} this
30829          * @param {String} msg The validation message
30830          */
30831         invalid : true,
30832        /**
30833          * @event valid
30834          * Fires after the field has been validated with no errors.
30835          * @param {Roo.form.Field} this
30836          */
30837         valid : true
30838     });
30839 };
30840
30841 Roo.extend(Roo.bootstrap.DateSplitField, Roo.bootstrap.Component,  {
30842     
30843     fieldLabel : '',
30844     labelAlign : 'top',
30845     labelWidth : 3,
30846     dayAllowBlank : false,
30847     monthAllowBlank : false,
30848     yearAllowBlank : false,
30849     dayPlaceholder : '',
30850     monthPlaceholder : '',
30851     yearPlaceholder : '',
30852     dayFormat : 'd',
30853     monthFormat : 'm',
30854     yearFormat : 'Y',
30855     isFormField : true,
30856     labellg : 0,
30857     labelmd : 0,
30858     labelsm : 0,
30859     labelxs : 0,
30860     
30861     getAutoCreate : function()
30862     {
30863         var cfg = {
30864             tag : 'div',
30865             cls : 'row roo-date-split-field-group',
30866             cn : [
30867                 {
30868                     tag : 'input',
30869                     type : 'hidden',
30870                     cls : 'form-hidden-field roo-date-split-field-group-value',
30871                     name : this.name
30872                 }
30873             ]
30874         };
30875         
30876         var labelCls = 'col-md-12';
30877         var contentCls = 'col-md-4';
30878         
30879         if(this.fieldLabel){
30880             
30881             var label = {
30882                 tag : 'div',
30883                 cls : 'column roo-date-split-field-label col-md-' + ((this.labelAlign == 'top') ? '12' : this.labelWidth),
30884                 cn : [
30885                     {
30886                         tag : 'label',
30887                         html : this.fieldLabel
30888                     }
30889                 ]
30890             };
30891             
30892             if(this.labelAlign == 'left'){
30893             
30894                 if(this.labelWidth > 12){
30895                     label.style = "width: " + this.labelWidth + 'px';
30896                 }
30897
30898                 if(this.labelWidth < 13 && this.labelmd == 0){
30899                     this.labelmd = this.labelWidth;
30900                 }
30901
30902                 if(this.labellg > 0){
30903                     labelCls = ' col-lg-' + this.labellg;
30904                     contentCls = ' col-lg-' + ((12 - this.labellg) / 3);
30905                 }
30906
30907                 if(this.labelmd > 0){
30908                     labelCls = ' col-md-' + this.labelmd;
30909                     contentCls = ' col-md-' + ((12 - this.labelmd) / 3);
30910                 }
30911
30912                 if(this.labelsm > 0){
30913                     labelCls = ' col-sm-' + this.labelsm;
30914                     contentCls = ' col-sm-' + ((12 - this.labelsm) / 3);
30915                 }
30916
30917                 if(this.labelxs > 0){
30918                     labelCls = ' col-xs-' + this.labelxs;
30919                     contentCls = ' col-xs-' + ((12 - this.labelxs) / 3);
30920                 }
30921             }
30922             
30923             label.cls += ' ' + labelCls;
30924             
30925             cfg.cn.push(label);
30926         }
30927         
30928         Roo.each(['day', 'month', 'year'], function(t){
30929             cfg.cn.push({
30930                 tag : 'div',
30931                 cls : 'column roo-date-split-field-' + t + ' ' + contentCls
30932             });
30933         }, this);
30934         
30935         return cfg;
30936     },
30937     
30938     inputEl: function ()
30939     {
30940         return this.el.select('.roo-date-split-field-group-value', true).first();
30941     },
30942     
30943     onRender : function(ct, position) 
30944     {
30945         var _this = this;
30946         
30947         Roo.bootstrap.NavProgressBar.superclass.onRender.call(this, ct, position);
30948         
30949         this.inputEl = this.el.select('.roo-date-split-field-group-value', true).first();
30950         
30951         this.dayField = new Roo.bootstrap.ComboBox({
30952             allowBlank : this.dayAllowBlank,
30953             alwaysQuery : true,
30954             displayField : 'value',
30955             editable : false,
30956             fieldLabel : '',
30957             forceSelection : true,
30958             mode : 'local',
30959             placeholder : this.dayPlaceholder,
30960             selectOnFocus : true,
30961             tpl : '<div class="roo-select2-result"><b>{value}</b></div>',
30962             triggerAction : 'all',
30963             typeAhead : true,
30964             valueField : 'value',
30965             store : new Roo.data.SimpleStore({
30966                 data : (function() {    
30967                     var days = [];
30968                     _this.fireEvent('days', _this, days);
30969                     return days;
30970                 })(),
30971                 fields : [ 'value' ]
30972             }),
30973             listeners : {
30974                 select : function (_self, record, index)
30975                 {
30976                     _this.setValue(_this.getValue());
30977                 }
30978             }
30979         });
30980
30981         this.dayField.render(this.el.select('.roo-date-split-field-day', true).first(), null);
30982         
30983         this.monthField = new Roo.bootstrap.MonthField({
30984             after : '<i class=\"fa fa-calendar\"></i>',
30985             allowBlank : this.monthAllowBlank,
30986             placeholder : this.monthPlaceholder,
30987             readOnly : true,
30988             listeners : {
30989                 render : function (_self)
30990                 {
30991                     this.el.select('span.input-group-addon', true).first().on('click', function(e){
30992                         e.preventDefault();
30993                         _self.focus();
30994                     });
30995                 },
30996                 select : function (_self, oldvalue, newvalue)
30997                 {
30998                     _this.setValue(_this.getValue());
30999                 }
31000             }
31001         });
31002         
31003         this.monthField.render(this.el.select('.roo-date-split-field-month', true).first(), null);
31004         
31005         this.yearField = new Roo.bootstrap.ComboBox({
31006             allowBlank : this.yearAllowBlank,
31007             alwaysQuery : true,
31008             displayField : 'value',
31009             editable : false,
31010             fieldLabel : '',
31011             forceSelection : true,
31012             mode : 'local',
31013             placeholder : this.yearPlaceholder,
31014             selectOnFocus : true,
31015             tpl : '<div class="roo-select2-result"><b>{value}</b></div>',
31016             triggerAction : 'all',
31017             typeAhead : true,
31018             valueField : 'value',
31019             store : new Roo.data.SimpleStore({
31020                 data : (function() {
31021                     var years = [];
31022                     _this.fireEvent('years', _this, years);
31023                     return years;
31024                 })(),
31025                 fields : [ 'value' ]
31026             }),
31027             listeners : {
31028                 select : function (_self, record, index)
31029                 {
31030                     _this.setValue(_this.getValue());
31031                 }
31032             }
31033         });
31034
31035         this.yearField.render(this.el.select('.roo-date-split-field-year', true).first(), null);
31036     },
31037     
31038     setValue : function(v, format)
31039     {
31040         this.inputEl.dom.value = v;
31041         
31042         var f = format || (this.yearFormat + '-' + this.monthFormat + '-' + this.dayFormat);
31043         
31044         var d = Date.parseDate(v, f);
31045         
31046         if(!d){
31047             this.validate();
31048             return;
31049         }
31050         
31051         this.setDay(d.format(this.dayFormat));
31052         this.setMonth(d.format(this.monthFormat));
31053         this.setYear(d.format(this.yearFormat));
31054         
31055         this.validate();
31056         
31057         return;
31058     },
31059     
31060     setDay : function(v)
31061     {
31062         this.dayField.setValue(v);
31063         this.inputEl.dom.value = this.getValue();
31064         this.validate();
31065         return;
31066     },
31067     
31068     setMonth : function(v)
31069     {
31070         this.monthField.setValue(v, true);
31071         this.inputEl.dom.value = this.getValue();
31072         this.validate();
31073         return;
31074     },
31075     
31076     setYear : function(v)
31077     {
31078         this.yearField.setValue(v);
31079         this.inputEl.dom.value = this.getValue();
31080         this.validate();
31081         return;
31082     },
31083     
31084     getDay : function()
31085     {
31086         return this.dayField.getValue();
31087     },
31088     
31089     getMonth : function()
31090     {
31091         return this.monthField.getValue();
31092     },
31093     
31094     getYear : function()
31095     {
31096         return this.yearField.getValue();
31097     },
31098     
31099     getValue : function()
31100     {
31101         var f = this.yearFormat + '-' + this.monthFormat + '-' + this.dayFormat;
31102         
31103         var date = this.yearField.getValue() + '-' + this.monthField.getValue() + '-' + this.dayField.getValue();
31104         
31105         return date;
31106     },
31107     
31108     reset : function()
31109     {
31110         this.setDay('');
31111         this.setMonth('');
31112         this.setYear('');
31113         this.inputEl.dom.value = '';
31114         this.validate();
31115         return;
31116     },
31117     
31118     validate : function()
31119     {
31120         var d = this.dayField.validate();
31121         var m = this.monthField.validate();
31122         var y = this.yearField.validate();
31123         
31124         var valid = true;
31125         
31126         if(
31127                 (!this.dayAllowBlank && !d) ||
31128                 (!this.monthAllowBlank && !m) ||
31129                 (!this.yearAllowBlank && !y)
31130         ){
31131             valid = false;
31132         }
31133         
31134         if(this.dayAllowBlank && this.monthAllowBlank && this.yearAllowBlank){
31135             return valid;
31136         }
31137         
31138         if(valid){
31139             this.markValid();
31140             return valid;
31141         }
31142         
31143         this.markInvalid();
31144         
31145         return valid;
31146     },
31147     
31148     markValid : function()
31149     {
31150         
31151         var label = this.el.select('label', true).first();
31152         var icon = this.el.select('i.fa-star', true).first();
31153
31154         if(label && icon){
31155             icon.remove();
31156         }
31157         
31158         this.fireEvent('valid', this);
31159     },
31160     
31161      /**
31162      * Mark this field as invalid
31163      * @param {String} msg The validation message
31164      */
31165     markInvalid : function(msg)
31166     {
31167         
31168         var label = this.el.select('label', true).first();
31169         var icon = this.el.select('i.fa-star', true).first();
31170
31171         if(label && !icon){
31172             this.el.select('.roo-date-split-field-label', true).createChild({
31173                 tag : 'i',
31174                 cls : 'text-danger fa fa-lg fa-star',
31175                 tooltip : 'This field is required',
31176                 style : 'margin-right:5px;'
31177             }, label, true);
31178         }
31179         
31180         this.fireEvent('invalid', this, msg);
31181     },
31182     
31183     clearInvalid : function()
31184     {
31185         var label = this.el.select('label', true).first();
31186         var icon = this.el.select('i.fa-star', true).first();
31187
31188         if(label && icon){
31189             icon.remove();
31190         }
31191         
31192         this.fireEvent('valid', this);
31193     },
31194     
31195     getName: function()
31196     {
31197         return this.name;
31198     }
31199     
31200 });
31201
31202  /**
31203  *
31204  * This is based on 
31205  * http://masonry.desandro.com
31206  *
31207  * The idea is to render all the bricks based on vertical width...
31208  *
31209  * The original code extends 'outlayer' - we might need to use that....
31210  * 
31211  */
31212
31213
31214 /**
31215  * @class Roo.bootstrap.LayoutMasonry
31216  * @extends Roo.bootstrap.Component
31217  * Bootstrap Layout Masonry class
31218  * 
31219  * @constructor
31220  * Create a new Element
31221  * @param {Object} config The config object
31222  */
31223
31224 Roo.bootstrap.LayoutMasonry = function(config){
31225     
31226     Roo.bootstrap.LayoutMasonry.superclass.constructor.call(this, config);
31227     
31228     this.bricks = [];
31229     
31230     Roo.bootstrap.LayoutMasonry.register(this);
31231     
31232     this.addEvents({
31233         // raw events
31234         /**
31235          * @event layout
31236          * Fire after layout the items
31237          * @param {Roo.bootstrap.LayoutMasonry} this
31238          * @param {Roo.EventObject} e
31239          */
31240         "layout" : true
31241     });
31242     
31243 };
31244
31245 Roo.extend(Roo.bootstrap.LayoutMasonry, Roo.bootstrap.Component,  {
31246     
31247     /**
31248      * @cfg {Boolean} isLayoutInstant = no animation?
31249      */   
31250     isLayoutInstant : false, // needed?
31251    
31252     /**
31253      * @cfg {Number} boxWidth  width of the columns
31254      */   
31255     boxWidth : 450,
31256     
31257       /**
31258      * @cfg {Number} boxHeight  - 0 for square, or fix it at a certian height
31259      */   
31260     boxHeight : 0,
31261     
31262     /**
31263      * @cfg {Number} padWidth padding below box..
31264      */   
31265     padWidth : 10, 
31266     
31267     /**
31268      * @cfg {Number} gutter gutter width..
31269      */   
31270     gutter : 10,
31271     
31272      /**
31273      * @cfg {Number} maxCols maximum number of columns
31274      */   
31275     
31276     maxCols: 0,
31277     
31278     /**
31279      * @cfg {Boolean} isAutoInitial defalut true
31280      */   
31281     isAutoInitial : true, 
31282     
31283     containerWidth: 0,
31284     
31285     /**
31286      * @cfg {Boolean} isHorizontal defalut false
31287      */   
31288     isHorizontal : false, 
31289
31290     currentSize : null,
31291     
31292     tag: 'div',
31293     
31294     cls: '',
31295     
31296     bricks: null, //CompositeElement
31297     
31298     cols : 1,
31299     
31300     _isLayoutInited : false,
31301     
31302 //    isAlternative : false, // only use for vertical layout...
31303     
31304     /**
31305      * @cfg {Number} alternativePadWidth padding below box..
31306      */   
31307     alternativePadWidth : 50,
31308     
31309     selectedBrick : [],
31310     
31311     getAutoCreate : function(){
31312         
31313         var cfg = Roo.apply({}, Roo.bootstrap.LayoutMasonry.superclass.getAutoCreate.call(this));
31314         
31315         var cfg = {
31316             tag: this.tag,
31317             cls: 'blog-masonary-wrapper ' + this.cls,
31318             cn : {
31319                 cls : 'mas-boxes masonary'
31320             }
31321         };
31322         
31323         return cfg;
31324     },
31325     
31326     getChildContainer: function( )
31327     {
31328         if (this.boxesEl) {
31329             return this.boxesEl;
31330         }
31331         
31332         this.boxesEl = this.el.select('.mas-boxes').first();
31333         
31334         return this.boxesEl;
31335     },
31336     
31337     
31338     initEvents : function()
31339     {
31340         var _this = this;
31341         
31342         if(this.isAutoInitial){
31343             Roo.log('hook children rendered');
31344             this.on('childrenrendered', function() {
31345                 Roo.log('children rendered');
31346                 _this.initial();
31347             } ,this);
31348         }
31349     },
31350     
31351     initial : function()
31352     {
31353         this.selectedBrick = [];
31354         
31355         this.currentSize = this.el.getBox(true);
31356         
31357         Roo.EventManager.onWindowResize(this.resize, this); 
31358
31359         if(!this.isAutoInitial){
31360             this.layout();
31361             return;
31362         }
31363         
31364         this.layout();
31365         
31366         return;
31367         //this.layout.defer(500,this);
31368         
31369     },
31370     
31371     resize : function()
31372     {
31373         var cs = this.el.getBox(true);
31374         
31375         if (
31376                 this.currentSize.width == cs.width && 
31377                 this.currentSize.x == cs.x && 
31378                 this.currentSize.height == cs.height && 
31379                 this.currentSize.y == cs.y 
31380         ) {
31381             Roo.log("no change in with or X or Y");
31382             return;
31383         }
31384         
31385         this.currentSize = cs;
31386         
31387         this.layout();
31388         
31389     },
31390     
31391     layout : function()
31392     {   
31393         this._resetLayout();
31394         
31395         var isInstant = this.isLayoutInstant !== undefined ? this.isLayoutInstant : !this._isLayoutInited;
31396         
31397         this.layoutItems( isInstant );
31398       
31399         this._isLayoutInited = true;
31400         
31401         this.fireEvent('layout', this);
31402         
31403     },
31404     
31405     _resetLayout : function()
31406     {
31407         if(this.isHorizontal){
31408             this.horizontalMeasureColumns();
31409             return;
31410         }
31411         
31412         this.verticalMeasureColumns();
31413         
31414     },
31415     
31416     verticalMeasureColumns : function()
31417     {
31418         this.getContainerWidth();
31419         
31420 //        if(Roo.lib.Dom.getViewWidth() < 768 && this.isAlternative){
31421 //            this.colWidth = Math.floor(this.containerWidth * 0.8);
31422 //            return;
31423 //        }
31424         
31425         var boxWidth = this.boxWidth + this.padWidth;
31426         
31427         if(this.containerWidth < this.boxWidth){
31428             boxWidth = this.containerWidth
31429         }
31430         
31431         var containerWidth = this.containerWidth;
31432         
31433         var cols = Math.floor(containerWidth / boxWidth);
31434         
31435         this.cols = Math.max( cols, 1 );
31436         
31437         this.cols = this.maxCols > 0 ? Math.min( this.cols, this.maxCols ) : this.cols;
31438         
31439         var totalBoxWidth = this.cols * boxWidth - this.padWidth;
31440         
31441         var avail = Math.floor((containerWidth - totalBoxWidth) / this.cols);
31442         
31443         this.colWidth = boxWidth + avail - this.padWidth;
31444         
31445         this.unitWidth = Math.round((this.colWidth - (this.gutter * 2)) / 3);
31446         this.unitHeight = this.boxHeight > 0 ? this.boxHeight  : this.unitWidth;
31447     },
31448     
31449     horizontalMeasureColumns : function()
31450     {
31451         this.getContainerWidth();
31452         
31453         var boxWidth = this.boxWidth;
31454         
31455         if(this.containerWidth < boxWidth){
31456             boxWidth = this.containerWidth;
31457         }
31458         
31459         this.unitWidth = Math.floor((boxWidth - (this.gutter * 2)) / 3);
31460         
31461         this.el.setHeight(boxWidth);
31462         
31463     },
31464     
31465     getContainerWidth : function()
31466     {
31467         this.containerWidth = this.el.getBox(true).width;  //maybe use getComputedWidth
31468     },
31469     
31470     layoutItems : function( isInstant )
31471     {
31472         Roo.log(this.bricks);
31473         
31474         var items = Roo.apply([], this.bricks);
31475         
31476         if(this.isHorizontal){
31477             this._horizontalLayoutItems( items , isInstant );
31478             return;
31479         }
31480         
31481 //        if(Roo.lib.Dom.getViewWidth() < 768 && this.isAlternative){
31482 //            this._verticalAlternativeLayoutItems( items , isInstant );
31483 //            return;
31484 //        }
31485         
31486         this._verticalLayoutItems( items , isInstant );
31487         
31488     },
31489     
31490     _verticalLayoutItems : function ( items , isInstant)
31491     {
31492         if ( !items || !items.length ) {
31493             return;
31494         }
31495         
31496         var standard = [
31497             ['xs', 'xs', 'xs', 'tall'],
31498             ['xs', 'xs', 'tall'],
31499             ['xs', 'xs', 'sm'],
31500             ['xs', 'xs', 'xs'],
31501             ['xs', 'tall'],
31502             ['xs', 'sm'],
31503             ['xs', 'xs'],
31504             ['xs'],
31505             
31506             ['sm', 'xs', 'xs'],
31507             ['sm', 'xs'],
31508             ['sm'],
31509             
31510             ['tall', 'xs', 'xs', 'xs'],
31511             ['tall', 'xs', 'xs'],
31512             ['tall', 'xs'],
31513             ['tall']
31514             
31515         ];
31516         
31517         var queue = [];
31518         
31519         var boxes = [];
31520         
31521         var box = [];
31522         
31523         Roo.each(items, function(item, k){
31524             
31525             switch (item.size) {
31526                 // these layouts take up a full box,
31527                 case 'md' :
31528                 case 'md-left' :
31529                 case 'md-right' :
31530                 case 'wide' :
31531                     
31532                     if(box.length){
31533                         boxes.push(box);
31534                         box = [];
31535                     }
31536                     
31537                     boxes.push([item]);
31538                     
31539                     break;
31540                     
31541                 case 'xs' :
31542                 case 'sm' :
31543                 case 'tall' :
31544                     
31545                     box.push(item);
31546                     
31547                     break;
31548                 default :
31549                     break;
31550                     
31551             }
31552             
31553         }, this);
31554         
31555         if(box.length){
31556             boxes.push(box);
31557             box = [];
31558         }
31559         
31560         var filterPattern = function(box, length)
31561         {
31562             if(!box.length){
31563                 return;
31564             }
31565             
31566             var match = false;
31567             
31568             var pattern = box.slice(0, length);
31569             
31570             var format = [];
31571             
31572             Roo.each(pattern, function(i){
31573                 format.push(i.size);
31574             }, this);
31575             
31576             Roo.each(standard, function(s){
31577                 
31578                 if(String(s) != String(format)){
31579                     return;
31580                 }
31581                 
31582                 match = true;
31583                 return false;
31584                 
31585             }, this);
31586             
31587             if(!match && length == 1){
31588                 return;
31589             }
31590             
31591             if(!match){
31592                 filterPattern(box, length - 1);
31593                 return;
31594             }
31595                 
31596             queue.push(pattern);
31597
31598             box = box.slice(length, box.length);
31599
31600             filterPattern(box, 4);
31601
31602             return;
31603             
31604         }
31605         
31606         Roo.each(boxes, function(box, k){
31607             
31608             if(!box.length){
31609                 return;
31610             }
31611             
31612             if(box.length == 1){
31613                 queue.push(box);
31614                 return;
31615             }
31616             
31617             filterPattern(box, 4);
31618             
31619         }, this);
31620         
31621         this._processVerticalLayoutQueue( queue, isInstant );
31622         
31623     },
31624     
31625 //    _verticalAlternativeLayoutItems : function( items , isInstant )
31626 //    {
31627 //        if ( !items || !items.length ) {
31628 //            return;
31629 //        }
31630 //
31631 //        this._processVerticalAlternativeLayoutQueue( items, isInstant );
31632 //        
31633 //    },
31634     
31635     _horizontalLayoutItems : function ( items , isInstant)
31636     {
31637         if ( !items || !items.length || items.length < 3) {
31638             return;
31639         }
31640         
31641         items.reverse();
31642         
31643         var eItems = items.slice(0, 3);
31644         
31645         items = items.slice(3, items.length);
31646         
31647         var standard = [
31648             ['xs', 'xs', 'xs', 'wide'],
31649             ['xs', 'xs', 'wide'],
31650             ['xs', 'xs', 'sm'],
31651             ['xs', 'xs', 'xs'],
31652             ['xs', 'wide'],
31653             ['xs', 'sm'],
31654             ['xs', 'xs'],
31655             ['xs'],
31656             
31657             ['sm', 'xs', 'xs'],
31658             ['sm', 'xs'],
31659             ['sm'],
31660             
31661             ['wide', 'xs', 'xs', 'xs'],
31662             ['wide', 'xs', 'xs'],
31663             ['wide', 'xs'],
31664             ['wide'],
31665             
31666             ['wide-thin']
31667         ];
31668         
31669         var queue = [];
31670         
31671         var boxes = [];
31672         
31673         var box = [];
31674         
31675         Roo.each(items, function(item, k){
31676             
31677             switch (item.size) {
31678                 case 'md' :
31679                 case 'md-left' :
31680                 case 'md-right' :
31681                 case 'tall' :
31682                     
31683                     if(box.length){
31684                         boxes.push(box);
31685                         box = [];
31686                     }
31687                     
31688                     boxes.push([item]);
31689                     
31690                     break;
31691                     
31692                 case 'xs' :
31693                 case 'sm' :
31694                 case 'wide' :
31695                 case 'wide-thin' :
31696                     
31697                     box.push(item);
31698                     
31699                     break;
31700                 default :
31701                     break;
31702                     
31703             }
31704             
31705         }, this);
31706         
31707         if(box.length){
31708             boxes.push(box);
31709             box = [];
31710         }
31711         
31712         var filterPattern = function(box, length)
31713         {
31714             if(!box.length){
31715                 return;
31716             }
31717             
31718             var match = false;
31719             
31720             var pattern = box.slice(0, length);
31721             
31722             var format = [];
31723             
31724             Roo.each(pattern, function(i){
31725                 format.push(i.size);
31726             }, this);
31727             
31728             Roo.each(standard, function(s){
31729                 
31730                 if(String(s) != String(format)){
31731                     return;
31732                 }
31733                 
31734                 match = true;
31735                 return false;
31736                 
31737             }, this);
31738             
31739             if(!match && length == 1){
31740                 return;
31741             }
31742             
31743             if(!match){
31744                 filterPattern(box, length - 1);
31745                 return;
31746             }
31747                 
31748             queue.push(pattern);
31749
31750             box = box.slice(length, box.length);
31751
31752             filterPattern(box, 4);
31753
31754             return;
31755             
31756         }
31757         
31758         Roo.each(boxes, function(box, k){
31759             
31760             if(!box.length){
31761                 return;
31762             }
31763             
31764             if(box.length == 1){
31765                 queue.push(box);
31766                 return;
31767             }
31768             
31769             filterPattern(box, 4);
31770             
31771         }, this);
31772         
31773         
31774         var prune = [];
31775         
31776         var pos = this.el.getBox(true);
31777         
31778         var minX = pos.x;
31779         
31780         var maxX = pos.right - this.unitWidth * 3 - this.gutter * 2 - this.padWidth;
31781         
31782         var hit_end = false;
31783         
31784         Roo.each(queue, function(box){
31785             
31786             if(hit_end){
31787                 
31788                 Roo.each(box, function(b){
31789                 
31790                     b.el.setVisibilityMode(Roo.Element.DISPLAY);
31791                     b.el.hide();
31792
31793                 }, this);
31794
31795                 return;
31796             }
31797             
31798             var mx = 0;
31799             
31800             Roo.each(box, function(b){
31801                 
31802                 b.el.setVisibilityMode(Roo.Element.DISPLAY);
31803                 b.el.show();
31804
31805                 mx = Math.max(mx, b.x);
31806                 
31807             }, this);
31808             
31809             maxX = maxX - this.unitWidth * mx - this.gutter * (mx - 1) - this.padWidth;
31810             
31811             if(maxX < minX){
31812                 
31813                 Roo.each(box, function(b){
31814                 
31815                     b.el.setVisibilityMode(Roo.Element.DISPLAY);
31816                     b.el.hide();
31817                     
31818                 }, this);
31819                 
31820                 hit_end = true;
31821                 
31822                 return;
31823             }
31824             
31825             prune.push(box);
31826             
31827         }, this);
31828         
31829         this._processHorizontalLayoutQueue( prune, eItems, isInstant );
31830     },
31831     
31832     /** Sets position of item in DOM
31833     * @param {Element} item
31834     * @param {Number} x - horizontal position
31835     * @param {Number} y - vertical position
31836     * @param {Boolean} isInstant - disables transitions
31837     */
31838     _processVerticalLayoutQueue : function( queue, isInstant )
31839     {
31840         var pos = this.el.getBox(true);
31841         var x = pos.x;
31842         var y = pos.y;
31843         var maxY = [];
31844         
31845         for (var i = 0; i < this.cols; i++){
31846             maxY[i] = pos.y;
31847         }
31848         
31849         Roo.each(queue, function(box, k){
31850             
31851             var col = k % this.cols;
31852             
31853             Roo.each(box, function(b,kk){
31854                 
31855                 b.el.position('absolute');
31856                 
31857                 var width = Math.floor(this.unitWidth * b.x + (this.gutter * (b.x - 1)) + b.el.getPadding('lr'));
31858                 var height = Math.floor(this.unitHeight * b.y + (this.gutter * (b.y - 1)) + b.el.getPadding('tb'));
31859                 
31860                 if(b.size == 'md-left' || b.size == 'md-right'){
31861                     width = Math.floor(this.unitWidth * (b.x - 1) + (this.gutter * (b.x - 2)) + b.el.getPadding('lr'));
31862                     height = Math.floor(this.unitHeight * (b.y - 1) + (this.gutter * (b.y - 2)) + b.el.getPadding('tb'));
31863                 }
31864                 
31865                 b.el.setWidth(width);
31866                 b.el.setHeight(height);
31867                 // iframe?
31868                 b.el.select('iframe',true).setSize(width,height);
31869                 
31870             }, this);
31871             
31872             for (var i = 0; i < this.cols; i++){
31873                 
31874                 if(maxY[i] < maxY[col]){
31875                     col = i;
31876                     continue;
31877                 }
31878                 
31879                 col = Math.min(col, i);
31880                 
31881             }
31882             
31883             x = pos.x + col * (this.colWidth + this.padWidth);
31884             
31885             y = maxY[col];
31886             
31887             var positions = [];
31888             
31889             switch (box.length){
31890                 case 1 :
31891                     positions = this.getVerticalOneBoxColPositions(x, y, box);
31892                     break;
31893                 case 2 :
31894                     positions = this.getVerticalTwoBoxColPositions(x, y, box);
31895                     break;
31896                 case 3 :
31897                     positions = this.getVerticalThreeBoxColPositions(x, y, box);
31898                     break;
31899                 case 4 :
31900                     positions = this.getVerticalFourBoxColPositions(x, y, box);
31901                     break;
31902                 default :
31903                     break;
31904             }
31905             
31906             Roo.each(box, function(b,kk){
31907                 
31908                 b.el.setXY([positions[kk].x, positions[kk].y], isInstant ? false : true);
31909                 
31910                 var sz = b.el.getSize();
31911                 
31912                 maxY[col] = Math.max(maxY[col], positions[kk].y + sz.height + this.padWidth);
31913                 
31914             }, this);
31915             
31916         }, this);
31917         
31918         var mY = 0;
31919         
31920         for (var i = 0; i < this.cols; i++){
31921             mY = Math.max(mY, maxY[i]);
31922         }
31923         
31924         this.el.setHeight(mY - pos.y);
31925         
31926     },
31927     
31928 //    _processVerticalAlternativeLayoutQueue : function( items, isInstant )
31929 //    {
31930 //        var pos = this.el.getBox(true);
31931 //        var x = pos.x;
31932 //        var y = pos.y;
31933 //        var maxX = pos.right;
31934 //        
31935 //        var maxHeight = 0;
31936 //        
31937 //        Roo.each(items, function(item, k){
31938 //            
31939 //            var c = k % 2;
31940 //            
31941 //            item.el.position('absolute');
31942 //                
31943 //            var width = Math.floor(this.colWidth + item.el.getPadding('lr'));
31944 //
31945 //            item.el.setWidth(width);
31946 //
31947 //            var height = Math.floor(this.colWidth * item.y / item.x + item.el.getPadding('tb'));
31948 //
31949 //            item.el.setHeight(height);
31950 //            
31951 //            if(c == 0){
31952 //                item.el.setXY([x, y], isInstant ? false : true);
31953 //            } else {
31954 //                item.el.setXY([maxX - width, y], isInstant ? false : true);
31955 //            }
31956 //            
31957 //            y = y + height + this.alternativePadWidth;
31958 //            
31959 //            maxHeight = maxHeight + height + this.alternativePadWidth;
31960 //            
31961 //        }, this);
31962 //        
31963 //        this.el.setHeight(maxHeight);
31964 //        
31965 //    },
31966     
31967     _processHorizontalLayoutQueue : function( queue, eItems, isInstant )
31968     {
31969         var pos = this.el.getBox(true);
31970         
31971         var minX = pos.x;
31972         var minY = pos.y;
31973         
31974         var maxX = pos.right;
31975         
31976         this._processHorizontalEndItem(eItems, maxX, minX, minY, isInstant);
31977         
31978         var maxX = maxX - this.unitWidth * 3 - this.gutter * 2 - this.padWidth;
31979         
31980         Roo.each(queue, function(box, k){
31981             
31982             Roo.each(box, function(b, kk){
31983                 
31984                 b.el.position('absolute');
31985                 
31986                 var width = Math.floor(this.unitWidth * b.x + (this.gutter * (b.x - 1)) + b.el.getPadding('lr'));
31987                 var height = Math.floor(this.unitWidth * b.y + (this.gutter * (b.y - 1)) + b.el.getPadding('tb'));
31988                 
31989                 if(b.size == 'md-left' || b.size == 'md-right'){
31990                     width = Math.floor(this.unitWidth * (b.x - 1) + (this.gutter * (b.x - 2)) + b.el.getPadding('lr'));
31991                     height = Math.floor(this.unitWidth * (b.y - 1) + (this.gutter * (b.y - 2)) + b.el.getPadding('tb'));
31992                 }
31993                 
31994                 b.el.setWidth(width);
31995                 b.el.setHeight(height);
31996                 
31997             }, this);
31998             
31999             if(!box.length){
32000                 return;
32001             }
32002             
32003             var positions = [];
32004             
32005             switch (box.length){
32006                 case 1 :
32007                     positions = this.getHorizontalOneBoxColPositions(maxX, minY, box);
32008                     break;
32009                 case 2 :
32010                     positions = this.getHorizontalTwoBoxColPositions(maxX, minY, box);
32011                     break;
32012                 case 3 :
32013                     positions = this.getHorizontalThreeBoxColPositions(maxX, minY, box);
32014                     break;
32015                 case 4 :
32016                     positions = this.getHorizontalFourBoxColPositions(maxX, minY, box);
32017                     break;
32018                 default :
32019                     break;
32020             }
32021             
32022             Roo.each(box, function(b,kk){
32023                 
32024                 b.el.setXY([positions[kk].x, positions[kk].y], isInstant ? false : true);
32025                 
32026                 maxX = Math.min(maxX, positions[kk].x - this.padWidth);
32027                 
32028             }, this);
32029             
32030         }, this);
32031         
32032     },
32033     
32034     _processHorizontalEndItem : function(eItems, maxX, minX, minY, isInstant)
32035     {
32036         Roo.each(eItems, function(b,k){
32037             
32038             b.size = (k == 0) ? 'sm' : 'xs';
32039             b.x = (k == 0) ? 2 : 1;
32040             b.y = (k == 0) ? 2 : 1;
32041             
32042             b.el.position('absolute');
32043             
32044             var width = Math.floor(this.unitWidth * b.x + (this.gutter * (b.x - 1)) + b.el.getPadding('lr'));
32045                 
32046             b.el.setWidth(width);
32047             
32048             var height = Math.floor(this.unitWidth * b.y + (this.gutter * (b.y - 1)) + b.el.getPadding('tb'));
32049             
32050             b.el.setHeight(height);
32051             
32052         }, this);
32053
32054         var positions = [];
32055         
32056         positions.push({
32057             x : maxX - this.unitWidth * 2 - this.gutter,
32058             y : minY
32059         });
32060         
32061         positions.push({
32062             x : maxX - this.unitWidth,
32063             y : minY + (this.unitWidth + this.gutter) * 2
32064         });
32065         
32066         positions.push({
32067             x : maxX - this.unitWidth * 3 - this.gutter * 2,
32068             y : minY
32069         });
32070         
32071         Roo.each(eItems, function(b,k){
32072             
32073             b.el.setXY([positions[k].x, positions[k].y], isInstant ? false : true);
32074
32075         }, this);
32076         
32077     },
32078     
32079     getVerticalOneBoxColPositions : function(x, y, box)
32080     {
32081         var pos = [];
32082         
32083         var rand = Math.floor(Math.random() * ((4 - box[0].x)));
32084         
32085         if(box[0].size == 'md-left'){
32086             rand = 0;
32087         }
32088         
32089         if(box[0].size == 'md-right'){
32090             rand = 1;
32091         }
32092         
32093         pos.push({
32094             x : x + (this.unitWidth + this.gutter) * rand,
32095             y : y
32096         });
32097         
32098         return pos;
32099     },
32100     
32101     getVerticalTwoBoxColPositions : function(x, y, box)
32102     {
32103         var pos = [];
32104         
32105         if(box[0].size == 'xs'){
32106             
32107             pos.push({
32108                 x : x,
32109                 y : y + ((this.unitHeight + this.gutter) * Math.floor(Math.random() * box[1].y))
32110             });
32111
32112             pos.push({
32113                 x : x + (this.unitWidth + this.gutter) * (3 - box[1].x),
32114                 y : y
32115             });
32116             
32117             return pos;
32118             
32119         }
32120         
32121         pos.push({
32122             x : x,
32123             y : y
32124         });
32125
32126         pos.push({
32127             x : x + (this.unitWidth + this.gutter) * 2,
32128             y : y + ((this.unitHeight + this.gutter) * Math.floor(Math.random() * box[0].y))
32129         });
32130         
32131         return pos;
32132         
32133     },
32134     
32135     getVerticalThreeBoxColPositions : function(x, y, box)
32136     {
32137         var pos = [];
32138         
32139         if(box[0].size == 'xs' && box[1].size == 'xs' && box[2].size == 'xs'){
32140             
32141             pos.push({
32142                 x : x,
32143                 y : y
32144             });
32145
32146             pos.push({
32147                 x : x + (this.unitWidth + this.gutter) * 1,
32148                 y : y
32149             });
32150             
32151             pos.push({
32152                 x : x + (this.unitWidth + this.gutter) * 2,
32153                 y : y
32154             });
32155             
32156             return pos;
32157             
32158         }
32159         
32160         if(box[0].size == 'xs' && box[1].size == 'xs'){
32161             
32162             pos.push({
32163                 x : x,
32164                 y : y
32165             });
32166
32167             pos.push({
32168                 x : x,
32169                 y : y + ((this.unitHeight + this.gutter) * (box[2].y - 1))
32170             });
32171             
32172             pos.push({
32173                 x : x + (this.unitWidth + this.gutter) * 1,
32174                 y : y
32175             });
32176             
32177             return pos;
32178             
32179         }
32180         
32181         pos.push({
32182             x : x,
32183             y : y
32184         });
32185
32186         pos.push({
32187             x : x + (this.unitWidth + this.gutter) * 2,
32188             y : y
32189         });
32190
32191         pos.push({
32192             x : x + (this.unitWidth + this.gutter) * 2,
32193             y : y + (this.unitHeight + this.gutter) * (box[0].y - 1)
32194         });
32195             
32196         return pos;
32197         
32198     },
32199     
32200     getVerticalFourBoxColPositions : function(x, y, box)
32201     {
32202         var pos = [];
32203         
32204         if(box[0].size == 'xs'){
32205             
32206             pos.push({
32207                 x : x,
32208                 y : y
32209             });
32210
32211             pos.push({
32212                 x : x,
32213                 y : y + (this.unitHeight + this.gutter) * 1
32214             });
32215             
32216             pos.push({
32217                 x : x,
32218                 y : y + (this.unitHeight + this.gutter) * 2
32219             });
32220             
32221             pos.push({
32222                 x : x + (this.unitWidth + this.gutter) * 1,
32223                 y : y
32224             });
32225             
32226             return pos;
32227             
32228         }
32229         
32230         pos.push({
32231             x : x,
32232             y : y
32233         });
32234
32235         pos.push({
32236             x : x + (this.unitWidth + this.gutter) * 2,
32237             y : y
32238         });
32239
32240         pos.push({
32241             x : x + (this.unitHeightunitWidth + this.gutter) * 2,
32242             y : y + (this.unitHeight + this.gutter) * 1
32243         });
32244
32245         pos.push({
32246             x : x + (this.unitWidth + this.gutter) * 2,
32247             y : y + (this.unitWidth + this.gutter) * 2
32248         });
32249
32250         return pos;
32251         
32252     },
32253     
32254     getHorizontalOneBoxColPositions : function(maxX, minY, box)
32255     {
32256         var pos = [];
32257         
32258         if(box[0].size == 'md-left'){
32259             pos.push({
32260                 x : maxX - this.unitWidth * (box[0].x - 1) - this.gutter * (box[0].x - 2),
32261                 y : minY
32262             });
32263             
32264             return pos;
32265         }
32266         
32267         if(box[0].size == 'md-right'){
32268             pos.push({
32269                 x : maxX - this.unitWidth * (box[0].x - 1) - this.gutter * (box[0].x - 2),
32270                 y : minY + (this.unitWidth + this.gutter) * 1
32271             });
32272             
32273             return pos;
32274         }
32275         
32276         var rand = Math.floor(Math.random() * (4 - box[0].y));
32277         
32278         pos.push({
32279             x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
32280             y : minY + (this.unitWidth + this.gutter) * rand
32281         });
32282         
32283         return pos;
32284         
32285     },
32286     
32287     getHorizontalTwoBoxColPositions : function(maxX, minY, box)
32288     {
32289         var pos = [];
32290         
32291         if(box[0].size == 'xs'){
32292             
32293             pos.push({
32294                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
32295                 y : minY
32296             });
32297
32298             pos.push({
32299                 x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
32300                 y : minY + (this.unitWidth + this.gutter) * (3 - box[1].y)
32301             });
32302             
32303             return pos;
32304             
32305         }
32306         
32307         pos.push({
32308             x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
32309             y : minY
32310         });
32311
32312         pos.push({
32313             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
32314             y : minY + (this.unitWidth + this.gutter) * 2
32315         });
32316         
32317         return pos;
32318         
32319     },
32320     
32321     getHorizontalThreeBoxColPositions : function(maxX, minY, box)
32322     {
32323         var pos = [];
32324         
32325         if(box[0].size == 'xs' && box[1].size == 'xs' && box[2].size == 'xs'){
32326             
32327             pos.push({
32328                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
32329                 y : minY
32330             });
32331
32332             pos.push({
32333                 x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
32334                 y : minY + (this.unitWidth + this.gutter) * 1
32335             });
32336             
32337             pos.push({
32338                 x : maxX - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
32339                 y : minY + (this.unitWidth + this.gutter) * 2
32340             });
32341             
32342             return pos;
32343             
32344         }
32345         
32346         if(box[0].size == 'xs' && box[1].size == 'xs'){
32347             
32348             pos.push({
32349                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
32350                 y : minY
32351             });
32352
32353             pos.push({
32354                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1) - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
32355                 y : minY
32356             });
32357             
32358             pos.push({
32359                 x : maxX - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
32360                 y : minY + (this.unitWidth + this.gutter) * 1
32361             });
32362             
32363             return pos;
32364             
32365         }
32366         
32367         pos.push({
32368             x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
32369             y : minY
32370         });
32371
32372         pos.push({
32373             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
32374             y : minY + (this.unitWidth + this.gutter) * 2
32375         });
32376
32377         pos.push({
32378             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1) - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
32379             y : minY + (this.unitWidth + this.gutter) * 2
32380         });
32381             
32382         return pos;
32383         
32384     },
32385     
32386     getHorizontalFourBoxColPositions : function(maxX, minY, box)
32387     {
32388         var pos = [];
32389         
32390         if(box[0].size == 'xs'){
32391             
32392             pos.push({
32393                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
32394                 y : minY
32395             });
32396
32397             pos.push({
32398                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1) - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
32399                 y : minY
32400             });
32401             
32402             pos.push({
32403                 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),
32404                 y : minY
32405             });
32406             
32407             pos.push({
32408                 x : maxX - this.unitWidth * box[3].x - this.gutter * (box[3].x - 1),
32409                 y : minY + (this.unitWidth + this.gutter) * 1
32410             });
32411             
32412             return pos;
32413             
32414         }
32415         
32416         pos.push({
32417             x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
32418             y : minY
32419         });
32420         
32421         pos.push({
32422             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
32423             y : minY + (this.unitWidth + this.gutter) * 2
32424         });
32425         
32426         pos.push({
32427             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1) - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
32428             y : minY + (this.unitWidth + this.gutter) * 2
32429         });
32430         
32431         pos.push({
32432             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),
32433             y : minY + (this.unitWidth + this.gutter) * 2
32434         });
32435
32436         return pos;
32437         
32438     },
32439     
32440     /**
32441     * remove a Masonry Brick
32442     * @param {Roo.bootstrap.MasonryBrick} the masonry brick to remove
32443     */
32444     removeBrick : function(brick_id)
32445     {
32446         if (!brick_id) {
32447             return;
32448         }
32449         
32450         for (var i = 0; i<this.bricks.length; i++) {
32451             if (this.bricks[i].id == brick_id) {
32452                 this.bricks.splice(i,1);
32453                 this.el.dom.removeChild(Roo.get(brick_id).dom);
32454                 this.initial();
32455             }
32456         }
32457     },
32458     
32459     /**
32460     * adds a Masonry Brick
32461     * @param {Roo.bootstrap.MasonryBrick} the masonry brick to add
32462     */
32463     addBrick : function(cfg)
32464     {
32465         var cn = new Roo.bootstrap.MasonryBrick(cfg);
32466         //this.register(cn);
32467         cn.parentId = this.id;
32468         cn.render(this.el);
32469         return cn;
32470     },
32471     
32472     /**
32473     * register a Masonry Brick
32474     * @param {Roo.bootstrap.MasonryBrick} the masonry brick to add
32475     */
32476     
32477     register : function(brick)
32478     {
32479         this.bricks.push(brick);
32480         brick.masonryId = this.id;
32481     },
32482     
32483     /**
32484     * clear all the Masonry Brick
32485     */
32486     clearAll : function()
32487     {
32488         this.bricks = [];
32489         //this.getChildContainer().dom.innerHTML = "";
32490         this.el.dom.innerHTML = '';
32491     },
32492     
32493     getSelected : function()
32494     {
32495         if (!this.selectedBrick) {
32496             return false;
32497         }
32498         
32499         return this.selectedBrick;
32500     }
32501 });
32502
32503 Roo.apply(Roo.bootstrap.LayoutMasonry, {
32504     
32505     groups: {},
32506      /**
32507     * register a Masonry Layout
32508     * @param {Roo.bootstrap.LayoutMasonry} the masonry layout to add
32509     */
32510     
32511     register : function(layout)
32512     {
32513         this.groups[layout.id] = layout;
32514     },
32515     /**
32516     * fetch a  Masonry Layout based on the masonry layout ID
32517     * @param {string} the masonry layout to add
32518     * @returns {Roo.bootstrap.LayoutMasonry} the masonry layout
32519     */
32520     
32521     get: function(layout_id) {
32522         if (typeof(this.groups[layout_id]) == 'undefined') {
32523             return false;
32524         }
32525         return this.groups[layout_id] ;
32526     }
32527     
32528     
32529     
32530 });
32531
32532  
32533
32534  /**
32535  *
32536  * This is based on 
32537  * http://masonry.desandro.com
32538  *
32539  * The idea is to render all the bricks based on vertical width...
32540  *
32541  * The original code extends 'outlayer' - we might need to use that....
32542  * 
32543  */
32544
32545
32546 /**
32547  * @class Roo.bootstrap.LayoutMasonryAuto
32548  * @extends Roo.bootstrap.Component
32549  * Bootstrap Layout Masonry class
32550  * 
32551  * @constructor
32552  * Create a new Element
32553  * @param {Object} config The config object
32554  */
32555
32556 Roo.bootstrap.LayoutMasonryAuto = function(config){
32557     Roo.bootstrap.LayoutMasonryAuto.superclass.constructor.call(this, config);
32558 };
32559
32560 Roo.extend(Roo.bootstrap.LayoutMasonryAuto, Roo.bootstrap.Component,  {
32561     
32562       /**
32563      * @cfg {Boolean} isFitWidth  - resize the width..
32564      */   
32565     isFitWidth : false,  // options..
32566     /**
32567      * @cfg {Boolean} isOriginLeft = left align?
32568      */   
32569     isOriginLeft : true,
32570     /**
32571      * @cfg {Boolean} isOriginTop = top align?
32572      */   
32573     isOriginTop : false,
32574     /**
32575      * @cfg {Boolean} isLayoutInstant = no animation?
32576      */   
32577     isLayoutInstant : false, // needed?
32578     /**
32579      * @cfg {Boolean} isResizingContainer = not sure if this is used..
32580      */   
32581     isResizingContainer : true,
32582     /**
32583      * @cfg {Number} columnWidth  width of the columns 
32584      */   
32585     
32586     columnWidth : 0,
32587     
32588     /**
32589      * @cfg {Number} maxCols maximum number of columns
32590      */   
32591     
32592     maxCols: 0,
32593     /**
32594      * @cfg {Number} padHeight padding below box..
32595      */   
32596     
32597     padHeight : 10, 
32598     
32599     /**
32600      * @cfg {Boolean} isAutoInitial defalut true
32601      */   
32602     
32603     isAutoInitial : true, 
32604     
32605     // private?
32606     gutter : 0,
32607     
32608     containerWidth: 0,
32609     initialColumnWidth : 0,
32610     currentSize : null,
32611     
32612     colYs : null, // array.
32613     maxY : 0,
32614     padWidth: 10,
32615     
32616     
32617     tag: 'div',
32618     cls: '',
32619     bricks: null, //CompositeElement
32620     cols : 0, // array?
32621     // element : null, // wrapped now this.el
32622     _isLayoutInited : null, 
32623     
32624     
32625     getAutoCreate : function(){
32626         
32627         var cfg = {
32628             tag: this.tag,
32629             cls: 'blog-masonary-wrapper ' + this.cls,
32630             cn : {
32631                 cls : 'mas-boxes masonary'
32632             }
32633         };
32634         
32635         return cfg;
32636     },
32637     
32638     getChildContainer: function( )
32639     {
32640         if (this.boxesEl) {
32641             return this.boxesEl;
32642         }
32643         
32644         this.boxesEl = this.el.select('.mas-boxes').first();
32645         
32646         return this.boxesEl;
32647     },
32648     
32649     
32650     initEvents : function()
32651     {
32652         var _this = this;
32653         
32654         if(this.isAutoInitial){
32655             Roo.log('hook children rendered');
32656             this.on('childrenrendered', function() {
32657                 Roo.log('children rendered');
32658                 _this.initial();
32659             } ,this);
32660         }
32661         
32662     },
32663     
32664     initial : function()
32665     {
32666         this.reloadItems();
32667
32668         this.currentSize = this.el.getBox(true);
32669
32670         /// was window resize... - let's see if this works..
32671         Roo.EventManager.onWindowResize(this.resize, this); 
32672
32673         if(!this.isAutoInitial){
32674             this.layout();
32675             return;
32676         }
32677         
32678         this.layout.defer(500,this);
32679     },
32680     
32681     reloadItems: function()
32682     {
32683         this.bricks = this.el.select('.masonry-brick', true);
32684         
32685         this.bricks.each(function(b) {
32686             //Roo.log(b.getSize());
32687             if (!b.attr('originalwidth')) {
32688                 b.attr('originalwidth',  b.getSize().width);
32689             }
32690             
32691         });
32692         
32693         Roo.log(this.bricks.elements.length);
32694     },
32695     
32696     resize : function()
32697     {
32698         Roo.log('resize');
32699         var cs = this.el.getBox(true);
32700         
32701         if (this.currentSize.width == cs.width && this.currentSize.x == cs.x ) {
32702             Roo.log("no change in with or X");
32703             return;
32704         }
32705         this.currentSize = cs;
32706         this.layout();
32707     },
32708     
32709     layout : function()
32710     {
32711          Roo.log('layout');
32712         this._resetLayout();
32713         //this._manageStamps();
32714       
32715         // don't animate first layout
32716         var isInstant = this.isLayoutInstant !== undefined ? this.isLayoutInstant : !this._isLayoutInited;
32717         this.layoutItems( isInstant );
32718       
32719         // flag for initalized
32720         this._isLayoutInited = true;
32721     },
32722     
32723     layoutItems : function( isInstant )
32724     {
32725         //var items = this._getItemsForLayout( this.items );
32726         // original code supports filtering layout items.. we just ignore it..
32727         
32728         this._layoutItems( this.bricks , isInstant );
32729       
32730         this._postLayout();
32731     },
32732     _layoutItems : function ( items , isInstant)
32733     {
32734        //this.fireEvent( 'layout', this, items );
32735     
32736
32737         if ( !items || !items.elements.length ) {
32738           // no items, emit event with empty array
32739             return;
32740         }
32741
32742         var queue = [];
32743         items.each(function(item) {
32744             Roo.log("layout item");
32745             Roo.log(item);
32746             // get x/y object from method
32747             var position = this._getItemLayoutPosition( item );
32748             // enqueue
32749             position.item = item;
32750             position.isInstant = isInstant; // || item.isLayoutInstant; << not set yet...
32751             queue.push( position );
32752         }, this);
32753       
32754         this._processLayoutQueue( queue );
32755     },
32756     /** Sets position of item in DOM
32757     * @param {Element} item
32758     * @param {Number} x - horizontal position
32759     * @param {Number} y - vertical position
32760     * @param {Boolean} isInstant - disables transitions
32761     */
32762     _processLayoutQueue : function( queue )
32763     {
32764         for ( var i=0, len = queue.length; i < len; i++ ) {
32765             var obj = queue[i];
32766             obj.item.position('absolute');
32767             obj.item.setXY([obj.x,obj.y], obj.isInstant ? false : true);
32768         }
32769     },
32770       
32771     
32772     /**
32773     * Any logic you want to do after each layout,
32774     * i.e. size the container
32775     */
32776     _postLayout : function()
32777     {
32778         this.resizeContainer();
32779     },
32780     
32781     resizeContainer : function()
32782     {
32783         if ( !this.isResizingContainer ) {
32784             return;
32785         }
32786         var size = this._getContainerSize();
32787         if ( size ) {
32788             this.el.setSize(size.width,size.height);
32789             this.boxesEl.setSize(size.width,size.height);
32790         }
32791     },
32792     
32793     
32794     
32795     _resetLayout : function()
32796     {
32797         //this.getSize();  // -- does not really do anything.. it probably applies left/right etc. to obuject but not used
32798         this.colWidth = this.el.getWidth();
32799         //this.gutter = this.el.getWidth(); 
32800         
32801         this.measureColumns();
32802
32803         // reset column Y
32804         var i = this.cols;
32805         this.colYs = [];
32806         while (i--) {
32807             this.colYs.push( 0 );
32808         }
32809     
32810         this.maxY = 0;
32811     },
32812
32813     measureColumns : function()
32814     {
32815         this.getContainerWidth();
32816       // if columnWidth is 0, default to outerWidth of first item
32817         if ( !this.columnWidth ) {
32818             var firstItem = this.bricks.first();
32819             Roo.log(firstItem);
32820             this.columnWidth  = this.containerWidth;
32821             if (firstItem && firstItem.attr('originalwidth') ) {
32822                 this.columnWidth = 1* (firstItem.attr('originalwidth') || firstItem.getWidth());
32823             }
32824             // columnWidth fall back to item of first element
32825             Roo.log("set column width?");
32826                         this.initialColumnWidth = this.columnWidth  ;
32827
32828             // if first elem has no width, default to size of container
32829             
32830         }
32831         
32832         
32833         if (this.initialColumnWidth) {
32834             this.columnWidth = this.initialColumnWidth;
32835         }
32836         
32837         
32838             
32839         // column width is fixed at the top - however if container width get's smaller we should
32840         // reduce it...
32841         
32842         // this bit calcs how man columns..
32843             
32844         var columnWidth = this.columnWidth += this.gutter;
32845       
32846         // calculate columns
32847         var containerWidth = this.containerWidth + this.gutter;
32848         
32849         var cols = (containerWidth - this.padWidth) / (columnWidth - this.padWidth);
32850         // fix rounding errors, typically with gutters
32851         var excess = columnWidth - containerWidth % columnWidth;
32852         
32853         
32854         // if overshoot is less than a pixel, round up, otherwise floor it
32855         var mathMethod = excess && excess < 1 ? 'round' : 'floor';
32856         cols = Math[ mathMethod ]( cols );
32857         this.cols = Math.max( cols, 1 );
32858         this.cols = this.maxCols > 0 ? Math.min( this.cols, this.maxCols ) : this.cols;
32859         
32860          // padding positioning..
32861         var totalColWidth = this.cols * this.columnWidth;
32862         var padavail = this.containerWidth - totalColWidth;
32863         // so for 2 columns - we need 3 'pads'
32864         
32865         var padNeeded = (1+this.cols) * this.padWidth;
32866         
32867         var padExtra = Math.floor((padavail - padNeeded) / this.cols);
32868         
32869         this.columnWidth += padExtra
32870         //this.padWidth = Math.floor(padavail /  ( this.cols));
32871         
32872         // adjust colum width so that padding is fixed??
32873         
32874         // we have 3 columns ... total = width * 3
32875         // we have X left over... that should be used by 
32876         
32877         //if (this.expandC) {
32878             
32879         //}
32880         
32881         
32882         
32883     },
32884     
32885     getContainerWidth : function()
32886     {
32887        /* // container is parent if fit width
32888         var container = this.isFitWidth ? this.element.parentNode : this.element;
32889         // check that this.size and size are there
32890         // IE8 triggers resize on body size change, so they might not be
32891         
32892         var size = getSize( container );  //FIXME
32893         this.containerWidth = size && size.innerWidth; //FIXME
32894         */
32895          
32896         this.containerWidth = this.el.getBox(true).width;  //maybe use getComputedWidth
32897         
32898     },
32899     
32900     _getItemLayoutPosition : function( item )  // what is item?
32901     {
32902         // we resize the item to our columnWidth..
32903       
32904         item.setWidth(this.columnWidth);
32905         item.autoBoxAdjust  = false;
32906         
32907         var sz = item.getSize();
32908  
32909         // how many columns does this brick span
32910         var remainder = this.containerWidth % this.columnWidth;
32911         
32912         var mathMethod = remainder && remainder < 1 ? 'round' : 'ceil';
32913         // round if off by 1 pixel, otherwise use ceil
32914         var colSpan = Math[ mathMethod ]( sz.width  / this.columnWidth );
32915         colSpan = Math.min( colSpan, this.cols );
32916         
32917         // normally this should be '1' as we dont' currently allow multi width columns..
32918         
32919         var colGroup = this._getColGroup( colSpan );
32920         // get the minimum Y value from the columns
32921         var minimumY = Math.min.apply( Math, colGroup );
32922         Roo.log([ 'setHeight',  minimumY, sz.height, setHeight ]);
32923         
32924         var shortColIndex = colGroup.indexOf(  minimumY ); // broken on ie8..?? probably...
32925          
32926         // position the brick
32927         var position = {
32928             x: this.currentSize.x + (this.padWidth /2) + ((this.columnWidth + this.padWidth )* shortColIndex),
32929             y: this.currentSize.y + minimumY + this.padHeight
32930         };
32931         
32932         Roo.log(position);
32933         // apply setHeight to necessary columns
32934         var setHeight = minimumY + sz.height + this.padHeight;
32935         //Roo.log([ 'setHeight',  minimumY, sz.height, setHeight ]);
32936         
32937         var setSpan = this.cols + 1 - colGroup.length;
32938         for ( var i = 0; i < setSpan; i++ ) {
32939           this.colYs[ shortColIndex + i ] = setHeight ;
32940         }
32941       
32942         return position;
32943     },
32944     
32945     /**
32946      * @param {Number} colSpan - number of columns the element spans
32947      * @returns {Array} colGroup
32948      */
32949     _getColGroup : function( colSpan )
32950     {
32951         if ( colSpan < 2 ) {
32952           // if brick spans only one column, use all the column Ys
32953           return this.colYs;
32954         }
32955       
32956         var colGroup = [];
32957         // how many different places could this brick fit horizontally
32958         var groupCount = this.cols + 1 - colSpan;
32959         // for each group potential horizontal position
32960         for ( var i = 0; i < groupCount; i++ ) {
32961           // make an array of colY values for that one group
32962           var groupColYs = this.colYs.slice( i, i + colSpan );
32963           // and get the max value of the array
32964           colGroup[i] = Math.max.apply( Math, groupColYs );
32965         }
32966         return colGroup;
32967     },
32968     /*
32969     _manageStamp : function( stamp )
32970     {
32971         var stampSize =  stamp.getSize();
32972         var offset = stamp.getBox();
32973         // get the columns that this stamp affects
32974         var firstX = this.isOriginLeft ? offset.x : offset.right;
32975         var lastX = firstX + stampSize.width;
32976         var firstCol = Math.floor( firstX / this.columnWidth );
32977         firstCol = Math.max( 0, firstCol );
32978         
32979         var lastCol = Math.floor( lastX / this.columnWidth );
32980         // lastCol should not go over if multiple of columnWidth #425
32981         lastCol -= lastX % this.columnWidth ? 0 : 1;
32982         lastCol = Math.min( this.cols - 1, lastCol );
32983         
32984         // set colYs to bottom of the stamp
32985         var stampMaxY = ( this.isOriginTop ? offset.y : offset.bottom ) +
32986             stampSize.height;
32987             
32988         for ( var i = firstCol; i <= lastCol; i++ ) {
32989           this.colYs[i] = Math.max( stampMaxY, this.colYs[i] );
32990         }
32991     },
32992     */
32993     
32994     _getContainerSize : function()
32995     {
32996         this.maxY = Math.max.apply( Math, this.colYs );
32997         var size = {
32998             height: this.maxY
32999         };
33000       
33001         if ( this.isFitWidth ) {
33002             size.width = this._getContainerFitWidth();
33003         }
33004       
33005         return size;
33006     },
33007     
33008     _getContainerFitWidth : function()
33009     {
33010         var unusedCols = 0;
33011         // count unused columns
33012         var i = this.cols;
33013         while ( --i ) {
33014           if ( this.colYs[i] !== 0 ) {
33015             break;
33016           }
33017           unusedCols++;
33018         }
33019         // fit container to columns that have been used
33020         return ( this.cols - unusedCols ) * this.columnWidth - this.gutter;
33021     },
33022     
33023     needsResizeLayout : function()
33024     {
33025         var previousWidth = this.containerWidth;
33026         this.getContainerWidth();
33027         return previousWidth !== this.containerWidth;
33028     }
33029  
33030 });
33031
33032  
33033
33034  /*
33035  * - LGPL
33036  *
33037  * element
33038  * 
33039  */
33040
33041 /**
33042  * @class Roo.bootstrap.MasonryBrick
33043  * @extends Roo.bootstrap.Component
33044  * Bootstrap MasonryBrick class
33045  * 
33046  * @constructor
33047  * Create a new MasonryBrick
33048  * @param {Object} config The config object
33049  */
33050
33051 Roo.bootstrap.MasonryBrick = function(config){
33052     
33053     Roo.bootstrap.MasonryBrick.superclass.constructor.call(this, config);
33054     
33055     Roo.bootstrap.MasonryBrick.register(this);
33056     
33057     this.addEvents({
33058         // raw events
33059         /**
33060          * @event click
33061          * When a MasonryBrick is clcik
33062          * @param {Roo.bootstrap.MasonryBrick} this
33063          * @param {Roo.EventObject} e
33064          */
33065         "click" : true
33066     });
33067 };
33068
33069 Roo.extend(Roo.bootstrap.MasonryBrick, Roo.bootstrap.Component,  {
33070     
33071     /**
33072      * @cfg {String} title
33073      */   
33074     title : '',
33075     /**
33076      * @cfg {String} html
33077      */   
33078     html : '',
33079     /**
33080      * @cfg {String} bgimage
33081      */   
33082     bgimage : '',
33083     /**
33084      * @cfg {String} videourl
33085      */   
33086     videourl : '',
33087     /**
33088      * @cfg {String} cls
33089      */   
33090     cls : '',
33091     /**
33092      * @cfg {String} href
33093      */   
33094     href : '',
33095     /**
33096      * @cfg {String} size (xs|sm|md|md-left|md-right|tall|wide)
33097      */   
33098     size : 'xs',
33099     
33100     /**
33101      * @cfg {String} placetitle (center|bottom)
33102      */   
33103     placetitle : '',
33104     
33105     /**
33106      * @cfg {Boolean} isFitContainer defalut true
33107      */   
33108     isFitContainer : true, 
33109     
33110     /**
33111      * @cfg {Boolean} preventDefault defalut false
33112      */   
33113     preventDefault : false, 
33114     
33115     /**
33116      * @cfg {Boolean} inverse defalut false
33117      */   
33118     maskInverse : false, 
33119     
33120     getAutoCreate : function()
33121     {
33122         if(!this.isFitContainer){
33123             return this.getSplitAutoCreate();
33124         }
33125         
33126         var cls = 'masonry-brick masonry-brick-full';
33127         
33128         if(this.href.length){
33129             cls += ' masonry-brick-link';
33130         }
33131         
33132         if(this.bgimage.length){
33133             cls += ' masonry-brick-image';
33134         }
33135         
33136         if(this.maskInverse){
33137             cls += ' mask-inverse';
33138         }
33139         
33140         if(!this.html.length && !this.maskInverse && !this.videourl.length){
33141             cls += ' enable-mask';
33142         }
33143         
33144         if(this.size){
33145             cls += ' masonry-' + this.size + '-brick';
33146         }
33147         
33148         if(this.placetitle.length){
33149             
33150             switch (this.placetitle) {
33151                 case 'center' :
33152                     cls += ' masonry-center-title';
33153                     break;
33154                 case 'bottom' :
33155                     cls += ' masonry-bottom-title';
33156                     break;
33157                 default:
33158                     break;
33159             }
33160             
33161         } else {
33162             if(!this.html.length && !this.bgimage.length){
33163                 cls += ' masonry-center-title';
33164             }
33165
33166             if(!this.html.length && this.bgimage.length){
33167                 cls += ' masonry-bottom-title';
33168             }
33169         }
33170         
33171         if(this.cls){
33172             cls += ' ' + this.cls;
33173         }
33174         
33175         var cfg = {
33176             tag: (this.href.length) ? 'a' : 'div',
33177             cls: cls,
33178             cn: [
33179                 {
33180                     tag: 'div',
33181                     cls: 'masonry-brick-mask'
33182                 },
33183                 {
33184                     tag: 'div',
33185                     cls: 'masonry-brick-paragraph',
33186                     cn: []
33187                 }
33188             ]
33189         };
33190         
33191         if(this.href.length){
33192             cfg.href = this.href;
33193         }
33194         
33195         var cn = cfg.cn[1].cn;
33196         
33197         if(this.title.length){
33198             cn.push({
33199                 tag: 'h4',
33200                 cls: 'masonry-brick-title',
33201                 html: this.title
33202             });
33203         }
33204         
33205         if(this.html.length){
33206             cn.push({
33207                 tag: 'p',
33208                 cls: 'masonry-brick-text',
33209                 html: this.html
33210             });
33211         }
33212         
33213         if (!this.title.length && !this.html.length) {
33214             cfg.cn[1].cls += ' hide';
33215         }
33216         
33217         if(this.bgimage.length){
33218             cfg.cn.push({
33219                 tag: 'img',
33220                 cls: 'masonry-brick-image-view',
33221                 src: this.bgimage
33222             });
33223         }
33224         
33225         if(this.videourl.length){
33226             var vurl = this.videourl.replace(/https:\/\/youtu\.be/, 'https://www.youtube.com/embed/');
33227             // youtube support only?
33228             cfg.cn.push({
33229                 tag: 'iframe',
33230                 cls: 'masonry-brick-image-view',
33231                 src: vurl,
33232                 frameborder : 0,
33233                 allowfullscreen : true
33234             });
33235         }
33236         
33237         return cfg;
33238         
33239     },
33240     
33241     getSplitAutoCreate : function()
33242     {
33243         var cls = 'masonry-brick masonry-brick-split';
33244         
33245         if(this.href.length){
33246             cls += ' masonry-brick-link';
33247         }
33248         
33249         if(this.bgimage.length){
33250             cls += ' masonry-brick-image';
33251         }
33252         
33253         if(this.size){
33254             cls += ' masonry-' + this.size + '-brick';
33255         }
33256         
33257         switch (this.placetitle) {
33258             case 'center' :
33259                 cls += ' masonry-center-title';
33260                 break;
33261             case 'bottom' :
33262                 cls += ' masonry-bottom-title';
33263                 break;
33264             default:
33265                 if(!this.bgimage.length){
33266                     cls += ' masonry-center-title';
33267                 }
33268
33269                 if(this.bgimage.length){
33270                     cls += ' masonry-bottom-title';
33271                 }
33272                 break;
33273         }
33274         
33275         if(this.cls){
33276             cls += ' ' + this.cls;
33277         }
33278         
33279         var cfg = {
33280             tag: (this.href.length) ? 'a' : 'div',
33281             cls: cls,
33282             cn: [
33283                 {
33284                     tag: 'div',
33285                     cls: 'masonry-brick-split-head',
33286                     cn: [
33287                         {
33288                             tag: 'div',
33289                             cls: 'masonry-brick-paragraph',
33290                             cn: []
33291                         }
33292                     ]
33293                 },
33294                 {
33295                     tag: 'div',
33296                     cls: 'masonry-brick-split-body',
33297                     cn: []
33298                 }
33299             ]
33300         };
33301         
33302         if(this.href.length){
33303             cfg.href = this.href;
33304         }
33305         
33306         if(this.title.length){
33307             cfg.cn[0].cn[0].cn.push({
33308                 tag: 'h4',
33309                 cls: 'masonry-brick-title',
33310                 html: this.title
33311             });
33312         }
33313         
33314         if(this.html.length){
33315             cfg.cn[1].cn.push({
33316                 tag: 'p',
33317                 cls: 'masonry-brick-text',
33318                 html: this.html
33319             });
33320         }
33321
33322         if(this.bgimage.length){
33323             cfg.cn[0].cn.push({
33324                 tag: 'img',
33325                 cls: 'masonry-brick-image-view',
33326                 src: this.bgimage
33327             });
33328         }
33329         
33330         if(this.videourl.length){
33331             var vurl = this.videourl.replace(/https:\/\/youtu\.be/, 'https://www.youtube.com/embed/');
33332             // youtube support only?
33333             cfg.cn[0].cn.cn.push({
33334                 tag: 'iframe',
33335                 cls: 'masonry-brick-image-view',
33336                 src: vurl,
33337                 frameborder : 0,
33338                 allowfullscreen : true
33339             });
33340         }
33341         
33342         return cfg;
33343     },
33344     
33345     initEvents: function() 
33346     {
33347         switch (this.size) {
33348             case 'xs' :
33349                 this.x = 1;
33350                 this.y = 1;
33351                 break;
33352             case 'sm' :
33353                 this.x = 2;
33354                 this.y = 2;
33355                 break;
33356             case 'md' :
33357             case 'md-left' :
33358             case 'md-right' :
33359                 this.x = 3;
33360                 this.y = 3;
33361                 break;
33362             case 'tall' :
33363                 this.x = 2;
33364                 this.y = 3;
33365                 break;
33366             case 'wide' :
33367                 this.x = 3;
33368                 this.y = 2;
33369                 break;
33370             case 'wide-thin' :
33371                 this.x = 3;
33372                 this.y = 1;
33373                 break;
33374                         
33375             default :
33376                 break;
33377         }
33378         
33379         if(Roo.isTouch){
33380             this.el.on('touchstart', this.onTouchStart, this);
33381             this.el.on('touchmove', this.onTouchMove, this);
33382             this.el.on('touchend', this.onTouchEnd, this);
33383             this.el.on('contextmenu', this.onContextMenu, this);
33384         } else {
33385             this.el.on('mouseenter'  ,this.enter, this);
33386             this.el.on('mouseleave', this.leave, this);
33387             this.el.on('click', this.onClick, this);
33388         }
33389         
33390         if (typeof(this.parent().bricks) == 'object' && this.parent().bricks != null) {
33391             this.parent().bricks.push(this);   
33392         }
33393         
33394     },
33395     
33396     onClick: function(e, el)
33397     {
33398         var time = this.endTimer - this.startTimer;
33399         // Roo.log(e.preventDefault());
33400         if(Roo.isTouch){
33401             if(time > 1000){
33402                 e.preventDefault();
33403                 return;
33404             }
33405         }
33406         
33407         if(!this.preventDefault){
33408             return;
33409         }
33410         
33411         e.preventDefault();
33412         
33413         if (this.activeClass != '') {
33414             this.selectBrick();
33415         }
33416         
33417         this.fireEvent('click', this, e);
33418     },
33419     
33420     enter: function(e, el)
33421     {
33422         e.preventDefault();
33423         
33424         if(!this.isFitContainer || this.maskInverse || this.videourl.length){
33425             return;
33426         }
33427         
33428         if(this.bgimage.length && this.html.length){
33429             this.el.select('.masonry-brick-paragraph', true).first().setOpacity(0.9, true);
33430         }
33431     },
33432     
33433     leave: function(e, el)
33434     {
33435         e.preventDefault();
33436         
33437         if(!this.isFitContainer || this.maskInverse  || this.videourl.length){
33438             return;
33439         }
33440         
33441         if(this.bgimage.length && this.html.length){
33442             this.el.select('.masonry-brick-paragraph', true).first().setOpacity(0, true);
33443         }
33444     },
33445     
33446     onTouchStart: function(e, el)
33447     {
33448 //        e.preventDefault();
33449         
33450         this.touchmoved = false;
33451         
33452         if(!this.isFitContainer){
33453             return;
33454         }
33455         
33456         if(!this.bgimage.length || !this.html.length){
33457             return;
33458         }
33459         
33460         this.el.select('.masonry-brick-paragraph', true).first().setOpacity(0.9, true);
33461         
33462         this.timer = new Date().getTime();
33463         
33464     },
33465     
33466     onTouchMove: function(e, el)
33467     {
33468         this.touchmoved = true;
33469     },
33470     
33471     onContextMenu : function(e,el)
33472     {
33473         e.preventDefault();
33474         e.stopPropagation();
33475         return false;
33476     },
33477     
33478     onTouchEnd: function(e, el)
33479     {
33480 //        e.preventDefault();
33481         
33482         if((new Date().getTime() - this.timer > 1000) || !this.href.length || this.touchmoved){
33483         
33484             this.leave(e,el);
33485             
33486             return;
33487         }
33488         
33489         if(!this.bgimage.length || !this.html.length){
33490             
33491             if(this.href.length){
33492                 window.location.href = this.href;
33493             }
33494             
33495             return;
33496         }
33497         
33498         if(!this.isFitContainer){
33499             return;
33500         }
33501         
33502         this.el.select('.masonry-brick-paragraph', true).first().setOpacity(0, true);
33503         
33504         window.location.href = this.href;
33505     },
33506     
33507     //selection on single brick only
33508     selectBrick : function() {
33509         
33510         if (!this.parentId) {
33511             return;
33512         }
33513         
33514         var m = Roo.bootstrap.LayoutMasonry.get(this.parentId);
33515         var index = m.selectedBrick.indexOf(this.id);
33516         
33517         if ( index > -1) {
33518             m.selectedBrick.splice(index,1);
33519             this.el.removeClass(this.activeClass);
33520             return;
33521         }
33522         
33523         for(var i = 0; i < m.selectedBrick.length; i++) {
33524             var b = Roo.bootstrap.MasonryBrick.get(m.selectedBrick[i]);
33525             b.el.removeClass(b.activeClass);
33526         }
33527         
33528         m.selectedBrick = [];
33529         
33530         m.selectedBrick.push(this.id);
33531         this.el.addClass(this.activeClass);
33532         return;
33533     },
33534     
33535     isSelected : function(){
33536         return this.el.hasClass(this.activeClass);
33537         
33538     }
33539 });
33540
33541 Roo.apply(Roo.bootstrap.MasonryBrick, {
33542     
33543     //groups: {},
33544     groups : new Roo.util.MixedCollection(false, function(o) { return o.el.id; }),
33545      /**
33546     * register a Masonry Brick
33547     * @param {Roo.bootstrap.MasonryBrick} the masonry brick to add
33548     */
33549     
33550     register : function(brick)
33551     {
33552         //this.groups[brick.id] = brick;
33553         this.groups.add(brick.id, brick);
33554     },
33555     /**
33556     * fetch a  masonry brick based on the masonry brick ID
33557     * @param {string} the masonry brick to add
33558     * @returns {Roo.bootstrap.MasonryBrick} the masonry brick
33559     */
33560     
33561     get: function(brick_id) 
33562     {
33563         // if (typeof(this.groups[brick_id]) == 'undefined') {
33564         //     return false;
33565         // }
33566         // return this.groups[brick_id] ;
33567         
33568         if(this.groups.key(brick_id)) {
33569             return this.groups.key(brick_id);
33570         }
33571         
33572         return false;
33573     }
33574     
33575     
33576     
33577 });
33578
33579  /*
33580  * - LGPL
33581  *
33582  * element
33583  * 
33584  */
33585
33586 /**
33587  * @class Roo.bootstrap.Brick
33588  * @extends Roo.bootstrap.Component
33589  * Bootstrap Brick class
33590  * 
33591  * @constructor
33592  * Create a new Brick
33593  * @param {Object} config The config object
33594  */
33595
33596 Roo.bootstrap.Brick = function(config){
33597     Roo.bootstrap.Brick.superclass.constructor.call(this, config);
33598     
33599     this.addEvents({
33600         // raw events
33601         /**
33602          * @event click
33603          * When a Brick is click
33604          * @param {Roo.bootstrap.Brick} this
33605          * @param {Roo.EventObject} e
33606          */
33607         "click" : true
33608     });
33609 };
33610
33611 Roo.extend(Roo.bootstrap.Brick, Roo.bootstrap.Component,  {
33612     
33613     /**
33614      * @cfg {String} title
33615      */   
33616     title : '',
33617     /**
33618      * @cfg {String} html
33619      */   
33620     html : '',
33621     /**
33622      * @cfg {String} bgimage
33623      */   
33624     bgimage : '',
33625     /**
33626      * @cfg {String} cls
33627      */   
33628     cls : '',
33629     /**
33630      * @cfg {String} href
33631      */   
33632     href : '',
33633     /**
33634      * @cfg {String} video
33635      */   
33636     video : '',
33637     /**
33638      * @cfg {Boolean} square
33639      */   
33640     square : true,
33641     
33642     getAutoCreate : function()
33643     {
33644         var cls = 'roo-brick';
33645         
33646         if(this.href.length){
33647             cls += ' roo-brick-link';
33648         }
33649         
33650         if(this.bgimage.length){
33651             cls += ' roo-brick-image';
33652         }
33653         
33654         if(!this.html.length && !this.bgimage.length){
33655             cls += ' roo-brick-center-title';
33656         }
33657         
33658         if(!this.html.length && this.bgimage.length){
33659             cls += ' roo-brick-bottom-title';
33660         }
33661         
33662         if(this.cls){
33663             cls += ' ' + this.cls;
33664         }
33665         
33666         var cfg = {
33667             tag: (this.href.length) ? 'a' : 'div',
33668             cls: cls,
33669             cn: [
33670                 {
33671                     tag: 'div',
33672                     cls: 'roo-brick-paragraph',
33673                     cn: []
33674                 }
33675             ]
33676         };
33677         
33678         if(this.href.length){
33679             cfg.href = this.href;
33680         }
33681         
33682         var cn = cfg.cn[0].cn;
33683         
33684         if(this.title.length){
33685             cn.push({
33686                 tag: 'h4',
33687                 cls: 'roo-brick-title',
33688                 html: this.title
33689             });
33690         }
33691         
33692         if(this.html.length){
33693             cn.push({
33694                 tag: 'p',
33695                 cls: 'roo-brick-text',
33696                 html: this.html
33697             });
33698         } else {
33699             cn.cls += ' hide';
33700         }
33701         
33702         if(this.bgimage.length){
33703             cfg.cn.push({
33704                 tag: 'img',
33705                 cls: 'roo-brick-image-view',
33706                 src: this.bgimage
33707             });
33708         }
33709         
33710         return cfg;
33711     },
33712     
33713     initEvents: function() 
33714     {
33715         if(this.title.length || this.html.length){
33716             this.el.on('mouseenter'  ,this.enter, this);
33717             this.el.on('mouseleave', this.leave, this);
33718         }
33719         
33720         Roo.EventManager.onWindowResize(this.resize, this); 
33721         
33722         if(this.bgimage.length){
33723             this.imageEl = this.el.select('.roo-brick-image-view', true).first();
33724             this.imageEl.on('load', this.onImageLoad, this);
33725             return;
33726         }
33727         
33728         this.resize();
33729     },
33730     
33731     onImageLoad : function()
33732     {
33733         this.resize();
33734     },
33735     
33736     resize : function()
33737     {
33738         var paragraph = this.el.select('.roo-brick-paragraph', true).first();
33739         
33740         paragraph.setHeight(paragraph.getWidth() + paragraph.getPadding('tb'));
33741         
33742         if(this.bgimage.length){
33743             var image = this.el.select('.roo-brick-image-view', true).first();
33744             
33745             image.setWidth(paragraph.getWidth());
33746             
33747             if(this.square){
33748                 image.setHeight(paragraph.getWidth());
33749             }
33750             
33751             this.el.setHeight(image.getHeight());
33752             paragraph.setHeight(image.getHeight());
33753             
33754         }
33755         
33756     },
33757     
33758     enter: function(e, el)
33759     {
33760         e.preventDefault();
33761         
33762         if(this.bgimage.length){
33763             this.el.select('.roo-brick-paragraph', true).first().setOpacity(0.9, true);
33764             this.el.select('.roo-brick-image-view', true).first().setOpacity(0.1, true);
33765         }
33766     },
33767     
33768     leave: function(e, el)
33769     {
33770         e.preventDefault();
33771         
33772         if(this.bgimage.length){
33773             this.el.select('.roo-brick-paragraph', true).first().setOpacity(0, true);
33774             this.el.select('.roo-brick-image-view', true).first().setOpacity(1, true);
33775         }
33776     }
33777     
33778 });
33779
33780  
33781
33782  /*
33783  * - LGPL
33784  *
33785  * Number field 
33786  */
33787
33788 /**
33789  * @class Roo.bootstrap.NumberField
33790  * @extends Roo.bootstrap.Input
33791  * Bootstrap NumberField class
33792  * 
33793  * 
33794  * 
33795  * 
33796  * @constructor
33797  * Create a new NumberField
33798  * @param {Object} config The config object
33799  */
33800
33801 Roo.bootstrap.NumberField = function(config){
33802     Roo.bootstrap.NumberField.superclass.constructor.call(this, config);
33803 };
33804
33805 Roo.extend(Roo.bootstrap.NumberField, Roo.bootstrap.Input, {
33806     
33807     /**
33808      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
33809      */
33810     allowDecimals : true,
33811     /**
33812      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
33813      */
33814     decimalSeparator : ".",
33815     /**
33816      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
33817      */
33818     decimalPrecision : 2,
33819     /**
33820      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
33821      */
33822     allowNegative : true,
33823     
33824     /**
33825      * @cfg {Boolean} allowZero False to blank out if the user enters '0' (defaults to true)
33826      */
33827     allowZero: true,
33828     /**
33829      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
33830      */
33831     minValue : Number.NEGATIVE_INFINITY,
33832     /**
33833      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
33834      */
33835     maxValue : Number.MAX_VALUE,
33836     /**
33837      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
33838      */
33839     minText : "The minimum value for this field is {0}",
33840     /**
33841      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
33842      */
33843     maxText : "The maximum value for this field is {0}",
33844     /**
33845      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
33846      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
33847      */
33848     nanText : "{0} is not a valid number",
33849     /**
33850      * @cfg {String} thousandsDelimiter Symbol of thousandsDelimiter
33851      */
33852     thousandsDelimiter : false,
33853     /**
33854      * @cfg {String} valueAlign alignment of value
33855      */
33856     valueAlign : "left",
33857
33858     getAutoCreate : function()
33859     {
33860         var hiddenInput = {
33861             tag: 'input',
33862             type: 'hidden',
33863             id: Roo.id(),
33864             cls: 'hidden-number-input'
33865         };
33866         
33867         if (this.name) {
33868             hiddenInput.name = this.name;
33869         }
33870         
33871         this.name = '';
33872         
33873         var cfg = Roo.bootstrap.NumberField.superclass.getAutoCreate.call(this);
33874         
33875         this.name = hiddenInput.name;
33876         
33877         if(cfg.cn.length > 0) {
33878             cfg.cn.push(hiddenInput);
33879         }
33880         
33881         return cfg;
33882     },
33883
33884     // private
33885     initEvents : function()
33886     {   
33887         Roo.bootstrap.NumberField.superclass.initEvents.call(this);
33888         
33889         var allowed = "0123456789";
33890         
33891         if(this.allowDecimals){
33892             allowed += this.decimalSeparator;
33893         }
33894         
33895         if(this.allowNegative){
33896             allowed += "-";
33897         }
33898         
33899         if(this.thousandsDelimiter) {
33900             allowed += ",";
33901         }
33902         
33903         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
33904         
33905         var keyPress = function(e){
33906             
33907             var k = e.getKey();
33908             
33909             var c = e.getCharCode();
33910             
33911             if(
33912                     (String.fromCharCode(c) == '.' || String.fromCharCode(c) == '-') &&
33913                     allowed.indexOf(String.fromCharCode(c)) === -1
33914             ){
33915                 e.stopEvent();
33916                 return;
33917             }
33918             
33919             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
33920                 return;
33921             }
33922             
33923             if(allowed.indexOf(String.fromCharCode(c)) === -1){
33924                 e.stopEvent();
33925             }
33926         };
33927         
33928         this.el.on("keypress", keyPress, this);
33929     },
33930     
33931     validateValue : function(value)
33932     {
33933         
33934         if(!Roo.bootstrap.NumberField.superclass.validateValue.call(this, value)){
33935             return false;
33936         }
33937         
33938         var num = this.parseValue(value);
33939         
33940         if(isNaN(num)){
33941             this.markInvalid(String.format(this.nanText, value));
33942             return false;
33943         }
33944         
33945         if(num < this.minValue){
33946             this.markInvalid(String.format(this.minText, this.minValue));
33947             return false;
33948         }
33949         
33950         if(num > this.maxValue){
33951             this.markInvalid(String.format(this.maxText, this.maxValue));
33952             return false;
33953         }
33954         
33955         return true;
33956     },
33957
33958     getValue : function()
33959     {
33960         var v = this.hiddenEl().getValue();
33961         
33962         return this.fixPrecision(this.parseValue(v));
33963     },
33964
33965     parseValue : function(value)
33966     {
33967         if(this.thousandsDelimiter) {
33968             value += "";
33969             r = new RegExp(",", "g");
33970             value = value.replace(r, "");
33971         }
33972         
33973         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
33974         return isNaN(value) ? '' : value;
33975     },
33976
33977     fixPrecision : function(value)
33978     {
33979         if(this.thousandsDelimiter) {
33980             value += "";
33981             r = new RegExp(",", "g");
33982             value = value.replace(r, "");
33983         }
33984         
33985         var nan = isNaN(value);
33986         
33987         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
33988             return nan ? '' : value;
33989         }
33990         return parseFloat(value).toFixed(this.decimalPrecision);
33991     },
33992
33993     setValue : function(v)
33994     {
33995         v = String(this.fixPrecision(v)).replace(".", this.decimalSeparator);
33996         
33997         this.value = v;
33998         
33999         if(this.rendered){
34000             
34001             this.hiddenEl().dom.value = (v === null || v === undefined ? '' : v);
34002             
34003             this.inputEl().dom.value = (v == '') ? '' :
34004                 Roo.util.Format.number(v, this.decimalPrecision, this.thousandsDelimiter || '');
34005             
34006             if(!this.allowZero && v === '0') {
34007                 this.hiddenEl().dom.value = '';
34008                 this.inputEl().dom.value = '';
34009             }
34010             
34011             this.validate();
34012         }
34013     },
34014
34015     decimalPrecisionFcn : function(v)
34016     {
34017         return Math.floor(v);
34018     },
34019
34020     beforeBlur : function()
34021     {
34022         var v = this.parseValue(this.getRawValue());
34023         
34024         if(v || v === 0 || v === ''){
34025             this.setValue(v);
34026         }
34027     },
34028     
34029     hiddenEl : function()
34030     {
34031         return this.el.select('input.hidden-number-input',true).first();
34032     }
34033     
34034 });
34035
34036  
34037
34038 /*
34039 * Licence: LGPL
34040 */
34041
34042 /**
34043  * @class Roo.bootstrap.DocumentSlider
34044  * @extends Roo.bootstrap.Component
34045  * Bootstrap DocumentSlider class
34046  * 
34047  * @constructor
34048  * Create a new DocumentViewer
34049  * @param {Object} config The config object
34050  */
34051
34052 Roo.bootstrap.DocumentSlider = function(config){
34053     Roo.bootstrap.DocumentSlider.superclass.constructor.call(this, config);
34054     
34055     this.files = [];
34056     
34057     this.addEvents({
34058         /**
34059          * @event initial
34060          * Fire after initEvent
34061          * @param {Roo.bootstrap.DocumentSlider} this
34062          */
34063         "initial" : true,
34064         /**
34065          * @event update
34066          * Fire after update
34067          * @param {Roo.bootstrap.DocumentSlider} this
34068          */
34069         "update" : true,
34070         /**
34071          * @event click
34072          * Fire after click
34073          * @param {Roo.bootstrap.DocumentSlider} this
34074          */
34075         "click" : true
34076     });
34077 };
34078
34079 Roo.extend(Roo.bootstrap.DocumentSlider, Roo.bootstrap.Component,  {
34080     
34081     files : false,
34082     
34083     indicator : 0,
34084     
34085     getAutoCreate : function()
34086     {
34087         var cfg = {
34088             tag : 'div',
34089             cls : 'roo-document-slider',
34090             cn : [
34091                 {
34092                     tag : 'div',
34093                     cls : 'roo-document-slider-header',
34094                     cn : [
34095                         {
34096                             tag : 'div',
34097                             cls : 'roo-document-slider-header-title'
34098                         }
34099                     ]
34100                 },
34101                 {
34102                     tag : 'div',
34103                     cls : 'roo-document-slider-body',
34104                     cn : [
34105                         {
34106                             tag : 'div',
34107                             cls : 'roo-document-slider-prev',
34108                             cn : [
34109                                 {
34110                                     tag : 'i',
34111                                     cls : 'fa fa-chevron-left'
34112                                 }
34113                             ]
34114                         },
34115                         {
34116                             tag : 'div',
34117                             cls : 'roo-document-slider-thumb',
34118                             cn : [
34119                                 {
34120                                     tag : 'img',
34121                                     cls : 'roo-document-slider-image'
34122                                 }
34123                             ]
34124                         },
34125                         {
34126                             tag : 'div',
34127                             cls : 'roo-document-slider-next',
34128                             cn : [
34129                                 {
34130                                     tag : 'i',
34131                                     cls : 'fa fa-chevron-right'
34132                                 }
34133                             ]
34134                         }
34135                     ]
34136                 }
34137             ]
34138         };
34139         
34140         return cfg;
34141     },
34142     
34143     initEvents : function()
34144     {
34145         this.headerEl = this.el.select('.roo-document-slider-header', true).first();
34146         this.headerEl.setVisibilityMode(Roo.Element.DISPLAY);
34147         
34148         this.titleEl = this.el.select('.roo-document-slider-header .roo-document-slider-header-title', true).first();
34149         this.titleEl.setVisibilityMode(Roo.Element.DISPLAY);
34150         
34151         this.bodyEl = this.el.select('.roo-document-slider-body', true).first();
34152         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY);
34153         
34154         this.thumbEl = this.el.select('.roo-document-slider-thumb', true).first();
34155         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY);
34156         
34157         this.imageEl = this.el.select('.roo-document-slider-image', true).first();
34158         this.imageEl.setVisibilityMode(Roo.Element.DISPLAY);
34159         
34160         this.prevIndicator = this.el.select('.roo-document-slider-prev i', true).first();
34161         this.prevIndicator.setVisibilityMode(Roo.Element.DISPLAY);
34162         
34163         this.nextIndicator = this.el.select('.roo-document-slider-next i', true).first();
34164         this.nextIndicator.setVisibilityMode(Roo.Element.DISPLAY);
34165         
34166         this.thumbEl.on('click', this.onClick, this);
34167         
34168         this.prevIndicator.on('click', this.prev, this);
34169         
34170         this.nextIndicator.on('click', this.next, this);
34171         
34172     },
34173     
34174     initial : function()
34175     {
34176         if(this.files.length){
34177             this.indicator = 1;
34178             this.update()
34179         }
34180         
34181         this.fireEvent('initial', this);
34182     },
34183     
34184     update : function()
34185     {
34186         this.imageEl.attr('src', this.files[this.indicator - 1]);
34187         
34188         this.titleEl.dom.innerHTML = String.format('{0} / {1}', this.indicator, this.files.length);
34189         
34190         this.prevIndicator.show();
34191         
34192         if(this.indicator == 1){
34193             this.prevIndicator.hide();
34194         }
34195         
34196         this.nextIndicator.show();
34197         
34198         if(this.indicator == this.files.length){
34199             this.nextIndicator.hide();
34200         }
34201         
34202         this.thumbEl.scrollTo('top');
34203         
34204         this.fireEvent('update', this);
34205     },
34206     
34207     onClick : function(e)
34208     {
34209         e.preventDefault();
34210         
34211         this.fireEvent('click', this);
34212     },
34213     
34214     prev : function(e)
34215     {
34216         e.preventDefault();
34217         
34218         this.indicator = Math.max(1, this.indicator - 1);
34219         
34220         this.update();
34221     },
34222     
34223     next : function(e)
34224     {
34225         e.preventDefault();
34226         
34227         this.indicator = Math.min(this.files.length, this.indicator + 1);
34228         
34229         this.update();
34230     }
34231 });
34232 /*
34233  * - LGPL
34234  *
34235  * RadioSet
34236  *
34237  *
34238  */
34239
34240 /**
34241  * @class Roo.bootstrap.RadioSet
34242  * @extends Roo.bootstrap.Input
34243  * Bootstrap RadioSet class
34244  * @cfg {String} indicatorpos (left|right) default left
34245  * @cfg {Boolean} inline (true|false) inline the element (default true)
34246  * @cfg {String} weight (primary|warning|info|danger|success) The text that appears beside the radio
34247  * @constructor
34248  * Create a new RadioSet
34249  * @param {Object} config The config object
34250  */
34251
34252 Roo.bootstrap.RadioSet = function(config){
34253     
34254     Roo.bootstrap.RadioSet.superclass.constructor.call(this, config);
34255     
34256     this.radioes = [];
34257     
34258     Roo.bootstrap.RadioSet.register(this);
34259     
34260     this.addEvents({
34261         /**
34262         * @event check
34263         * Fires when the element is checked or unchecked.
34264         * @param {Roo.bootstrap.RadioSet} this This radio
34265         * @param {Roo.bootstrap.Radio} item The checked item
34266         */
34267        check : true,
34268        /**
34269         * @event click
34270         * Fires when the element is click.
34271         * @param {Roo.bootstrap.RadioSet} this This radio set
34272         * @param {Roo.bootstrap.Radio} item The checked item
34273         * @param {Roo.EventObject} e The event object
34274         */
34275        click : true
34276     });
34277     
34278 };
34279
34280 Roo.extend(Roo.bootstrap.RadioSet, Roo.bootstrap.Input,  {
34281
34282     radioes : false,
34283     
34284     inline : true,
34285     
34286     weight : '',
34287     
34288     indicatorpos : 'left',
34289     
34290     getAutoCreate : function()
34291     {
34292         var label = {
34293             tag : 'label',
34294             cls : 'roo-radio-set-label',
34295             cn : [
34296                 {
34297                     tag : 'span',
34298                     html : this.fieldLabel
34299                 }
34300             ]
34301         };
34302         if (Roo.bootstrap.version == 3) {
34303             
34304             
34305             if(this.indicatorpos == 'left'){
34306                 label.cn.unshift({
34307                     tag : 'i',
34308                     cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
34309                     tooltip : 'This field is required'
34310                 });
34311             } else {
34312                 label.cn.push({
34313                     tag : 'i',
34314                     cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
34315                     tooltip : 'This field is required'
34316                 });
34317             }
34318         }
34319         var items = {
34320             tag : 'div',
34321             cls : 'roo-radio-set-items'
34322         };
34323         
34324         var align = (!this.labelAlign) ? this.parentLabelAlign() : this.labelAlign;
34325         
34326         if (align === 'left' && this.fieldLabel.length) {
34327             
34328             items = {
34329                 cls : "roo-radio-set-right", 
34330                 cn: [
34331                     items
34332                 ]
34333             };
34334             
34335             if(this.labelWidth > 12){
34336                 label.style = "width: " + this.labelWidth + 'px';
34337             }
34338             
34339             if(this.labelWidth < 13 && this.labelmd == 0){
34340                 this.labelmd = this.labelWidth;
34341             }
34342             
34343             if(this.labellg > 0){
34344                 label.cls += ' col-lg-' + this.labellg;
34345                 items.cls += ' col-lg-' + (12 - this.labellg);
34346             }
34347             
34348             if(this.labelmd > 0){
34349                 label.cls += ' col-md-' + this.labelmd;
34350                 items.cls += ' col-md-' + (12 - this.labelmd);
34351             }
34352             
34353             if(this.labelsm > 0){
34354                 label.cls += ' col-sm-' + this.labelsm;
34355                 items.cls += ' col-sm-' + (12 - this.labelsm);
34356             }
34357             
34358             if(this.labelxs > 0){
34359                 label.cls += ' col-xs-' + this.labelxs;
34360                 items.cls += ' col-xs-' + (12 - this.labelxs);
34361             }
34362         }
34363         
34364         var cfg = {
34365             tag : 'div',
34366             cls : 'roo-radio-set',
34367             cn : [
34368                 {
34369                     tag : 'input',
34370                     cls : 'roo-radio-set-input',
34371                     type : 'hidden',
34372                     name : this.name,
34373                     value : this.value ? this.value :  ''
34374                 },
34375                 label,
34376                 items
34377             ]
34378         };
34379         
34380         if(this.weight.length){
34381             cfg.cls += ' roo-radio-' + this.weight;
34382         }
34383         
34384         if(this.inline) {
34385             cfg.cls += ' roo-radio-set-inline';
34386         }
34387         
34388         var settings=this;
34389         ['xs','sm','md','lg'].map(function(size){
34390             if (settings[size]) {
34391                 cfg.cls += ' col-' + size + '-' + settings[size];
34392             }
34393         });
34394         
34395         return cfg;
34396         
34397     },
34398
34399     initEvents : function()
34400     {
34401         this.labelEl = this.el.select('.roo-radio-set-label', true).first();
34402         this.labelEl.setVisibilityMode(Roo.Element.DISPLAY);
34403         
34404         if(!this.fieldLabel.length){
34405             this.labelEl.hide();
34406         }
34407         
34408         this.itemsEl = this.el.select('.roo-radio-set-items', true).first();
34409         this.itemsEl.setVisibilityMode(Roo.Element.DISPLAY);
34410         
34411         this.indicator = this.indicatorEl();
34412         
34413         if(this.indicator){
34414             this.indicator.addClass('invisible');
34415         }
34416         
34417         this.originalValue = this.getValue();
34418         
34419     },
34420     
34421     inputEl: function ()
34422     {
34423         return this.el.select('.roo-radio-set-input', true).first();
34424     },
34425     
34426     getChildContainer : function()
34427     {
34428         return this.itemsEl;
34429     },
34430     
34431     register : function(item)
34432     {
34433         this.radioes.push(item);
34434         
34435     },
34436     
34437     validate : function()
34438     {   
34439         if(this.getVisibilityEl().hasClass('hidden')){
34440             return true;
34441         }
34442         
34443         var valid = false;
34444         
34445         Roo.each(this.radioes, function(i){
34446             if(!i.checked){
34447                 return;
34448             }
34449             
34450             valid = true;
34451             return false;
34452         });
34453         
34454         if(this.allowBlank) {
34455             return true;
34456         }
34457         
34458         if(this.disabled || valid){
34459             this.markValid();
34460             return true;
34461         }
34462         
34463         this.markInvalid();
34464         return false;
34465         
34466     },
34467     
34468     markValid : function()
34469     {
34470         if(this.labelEl.isVisible(true) && this.indicatorEl()){
34471             this.indicatorEl().removeClass('visible');
34472             this.indicatorEl().addClass('invisible');
34473         }
34474         
34475         
34476         if (Roo.bootstrap.version == 3) {
34477             this.el.removeClass([this.invalidClass, this.validClass]);
34478             this.el.addClass(this.validClass);
34479         } else {
34480             this.el.removeClass(['is-invalid','is-valid']);
34481             this.el.addClass(['is-valid']);
34482         }
34483         this.fireEvent('valid', this);
34484     },
34485     
34486     markInvalid : function(msg)
34487     {
34488         if(this.allowBlank || this.disabled){
34489             return;
34490         }
34491         
34492         if(this.labelEl.isVisible(true) && this.indicatorEl()){
34493             this.indicatorEl().removeClass('invisible');
34494             this.indicatorEl().addClass('visible');
34495         }
34496         if (Roo.bootstrap.version == 3) {
34497             this.el.removeClass([this.invalidClass, this.validClass]);
34498             this.el.addClass(this.invalidClass);
34499         } else {
34500             this.el.removeClass(['is-invalid','is-valid']);
34501             this.el.addClass(['is-invalid']);
34502         }
34503         
34504         this.fireEvent('invalid', this, msg);
34505         
34506     },
34507     
34508     setValue : function(v, suppressEvent)
34509     {   
34510         if(this.value === v){
34511             return;
34512         }
34513         
34514         this.value = v;
34515         
34516         if(this.rendered){
34517             this.inputEl().dom.value = (v === null || v === undefined ? '' : v);
34518         }
34519         
34520         Roo.each(this.radioes, function(i){
34521             i.checked = false;
34522             i.el.removeClass('checked');
34523         });
34524         
34525         Roo.each(this.radioes, function(i){
34526             
34527             if(i.value === v || i.value.toString() === v.toString()){
34528                 i.checked = true;
34529                 i.el.addClass('checked');
34530                 
34531                 if(suppressEvent !== true){
34532                     this.fireEvent('check', this, i);
34533                 }
34534                 
34535                 return false;
34536             }
34537             
34538         }, this);
34539         
34540         this.validate();
34541     },
34542     
34543     clearInvalid : function(){
34544         
34545         if(!this.el || this.preventMark){
34546             return;
34547         }
34548         
34549         this.el.removeClass([this.invalidClass]);
34550         
34551         this.fireEvent('valid', this);
34552     }
34553     
34554 });
34555
34556 Roo.apply(Roo.bootstrap.RadioSet, {
34557     
34558     groups: {},
34559     
34560     register : function(set)
34561     {
34562         this.groups[set.name] = set;
34563     },
34564     
34565     get: function(name) 
34566     {
34567         if (typeof(this.groups[name]) == 'undefined') {
34568             return false;
34569         }
34570         
34571         return this.groups[name] ;
34572     }
34573     
34574 });
34575 /*
34576  * Based on:
34577  * Ext JS Library 1.1.1
34578  * Copyright(c) 2006-2007, Ext JS, LLC.
34579  *
34580  * Originally Released Under LGPL - original licence link has changed is not relivant.
34581  *
34582  * Fork - LGPL
34583  * <script type="text/javascript">
34584  */
34585
34586
34587 /**
34588  * @class Roo.bootstrap.SplitBar
34589  * @extends Roo.util.Observable
34590  * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
34591  * <br><br>
34592  * Usage:
34593  * <pre><code>
34594 var split = new Roo.bootstrap.SplitBar("elementToDrag", "elementToSize",
34595                    Roo.bootstrap.SplitBar.HORIZONTAL, Roo.bootstrap.SplitBar.LEFT);
34596 split.setAdapter(new Roo.bootstrap.SplitBar.AbsoluteLayoutAdapter("container"));
34597 split.minSize = 100;
34598 split.maxSize = 600;
34599 split.animate = true;
34600 split.on('moved', splitterMoved);
34601 </code></pre>
34602  * @constructor
34603  * Create a new SplitBar
34604  * @config {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar. 
34605  * @config {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged 
34606  * @config {Number} orientation (optional) Either Roo.bootstrap.SplitBar.HORIZONTAL or Roo.bootstrap.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
34607  * @config {Number} placement (optional) Either Roo.bootstrap.SplitBar.LEFT or Roo.bootstrap.SplitBar.RIGHT for horizontal or  
34608                         Roo.bootstrap.SplitBar.TOP or Roo.bootstrap.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
34609                         position of the SplitBar).
34610  */
34611 Roo.bootstrap.SplitBar = function(cfg){
34612     
34613     /** @private */
34614     
34615     //{
34616     //  dragElement : elm
34617     //  resizingElement: el,
34618         // optional..
34619     //    orientation : Either Roo.bootstrap.SplitBar.HORIZONTAL
34620     //    placement : Roo.bootstrap.SplitBar.LEFT  ,
34621         // existingProxy ???
34622     //}
34623     
34624     this.el = Roo.get(cfg.dragElement, true);
34625     this.el.dom.unselectable = "on";
34626     /** @private */
34627     this.resizingEl = Roo.get(cfg.resizingElement, true);
34628
34629     /**
34630      * @private
34631      * The orientation of the split. Either Roo.bootstrap.SplitBar.HORIZONTAL or Roo.bootstrap.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
34632      * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
34633      * @type Number
34634      */
34635     this.orientation = cfg.orientation || Roo.bootstrap.SplitBar.HORIZONTAL;
34636     
34637     /**
34638      * The minimum size of the resizing element. (Defaults to 0)
34639      * @type Number
34640      */
34641     this.minSize = 0;
34642     
34643     /**
34644      * The maximum size of the resizing element. (Defaults to 2000)
34645      * @type Number
34646      */
34647     this.maxSize = 2000;
34648     
34649     /**
34650      * Whether to animate the transition to the new size
34651      * @type Boolean
34652      */
34653     this.animate = false;
34654     
34655     /**
34656      * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
34657      * @type Boolean
34658      */
34659     this.useShim = false;
34660     
34661     /** @private */
34662     this.shim = null;
34663     
34664     if(!cfg.existingProxy){
34665         /** @private */
34666         this.proxy = Roo.bootstrap.SplitBar.createProxy(this.orientation);
34667     }else{
34668         this.proxy = Roo.get(cfg.existingProxy).dom;
34669     }
34670     /** @private */
34671     this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
34672     
34673     /** @private */
34674     this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
34675     
34676     /** @private */
34677     this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
34678     
34679     /** @private */
34680     this.dragSpecs = {};
34681     
34682     /**
34683      * @private The adapter to use to positon and resize elements
34684      */
34685     this.adapter = new Roo.bootstrap.SplitBar.BasicLayoutAdapter();
34686     this.adapter.init(this);
34687     
34688     if(this.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
34689         /** @private */
34690         this.placement = cfg.placement || (this.el.getX() > this.resizingEl.getX() ? Roo.bootstrap.SplitBar.LEFT : Roo.bootstrap.SplitBar.RIGHT);
34691         this.el.addClass("roo-splitbar-h");
34692     }else{
34693         /** @private */
34694         this.placement = cfg.placement || (this.el.getY() > this.resizingEl.getY() ? Roo.bootstrap.SplitBar.TOP : Roo.bootstrap.SplitBar.BOTTOM);
34695         this.el.addClass("roo-splitbar-v");
34696     }
34697     
34698     this.addEvents({
34699         /**
34700          * @event resize
34701          * Fires when the splitter is moved (alias for {@link #event-moved})
34702          * @param {Roo.bootstrap.SplitBar} this
34703          * @param {Number} newSize the new width or height
34704          */
34705         "resize" : true,
34706         /**
34707          * @event moved
34708          * Fires when the splitter is moved
34709          * @param {Roo.bootstrap.SplitBar} this
34710          * @param {Number} newSize the new width or height
34711          */
34712         "moved" : true,
34713         /**
34714          * @event beforeresize
34715          * Fires before the splitter is dragged
34716          * @param {Roo.bootstrap.SplitBar} this
34717          */
34718         "beforeresize" : true,
34719
34720         "beforeapply" : true
34721     });
34722
34723     Roo.util.Observable.call(this);
34724 };
34725
34726 Roo.extend(Roo.bootstrap.SplitBar, Roo.util.Observable, {
34727     onStartProxyDrag : function(x, y){
34728         this.fireEvent("beforeresize", this);
34729         if(!this.overlay){
34730             var o = Roo.DomHelper.insertFirst(document.body,  {cls: "roo-drag-overlay", html: "&#160;"}, true);
34731             o.unselectable();
34732             o.enableDisplayMode("block");
34733             // all splitbars share the same overlay
34734             Roo.bootstrap.SplitBar.prototype.overlay = o;
34735         }
34736         this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
34737         this.overlay.show();
34738         Roo.get(this.proxy).setDisplayed("block");
34739         var size = this.adapter.getElementSize(this);
34740         this.activeMinSize = this.getMinimumSize();;
34741         this.activeMaxSize = this.getMaximumSize();;
34742         var c1 = size - this.activeMinSize;
34743         var c2 = Math.max(this.activeMaxSize - size, 0);
34744         if(this.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
34745             this.dd.resetConstraints();
34746             this.dd.setXConstraint(
34747                 this.placement == Roo.bootstrap.SplitBar.LEFT ? c1 : c2, 
34748                 this.placement == Roo.bootstrap.SplitBar.LEFT ? c2 : c1
34749             );
34750             this.dd.setYConstraint(0, 0);
34751         }else{
34752             this.dd.resetConstraints();
34753             this.dd.setXConstraint(0, 0);
34754             this.dd.setYConstraint(
34755                 this.placement == Roo.bootstrap.SplitBar.TOP ? c1 : c2, 
34756                 this.placement == Roo.bootstrap.SplitBar.TOP ? c2 : c1
34757             );
34758          }
34759         this.dragSpecs.startSize = size;
34760         this.dragSpecs.startPoint = [x, y];
34761         Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
34762     },
34763     
34764     /** 
34765      * @private Called after the drag operation by the DDProxy
34766      */
34767     onEndProxyDrag : function(e){
34768         Roo.get(this.proxy).setDisplayed(false);
34769         var endPoint = Roo.lib.Event.getXY(e);
34770         if(this.overlay){
34771             this.overlay.hide();
34772         }
34773         var newSize;
34774         if(this.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
34775             newSize = this.dragSpecs.startSize + 
34776                 (this.placement == Roo.bootstrap.SplitBar.LEFT ?
34777                     endPoint[0] - this.dragSpecs.startPoint[0] :
34778                     this.dragSpecs.startPoint[0] - endPoint[0]
34779                 );
34780         }else{
34781             newSize = this.dragSpecs.startSize + 
34782                 (this.placement == Roo.bootstrap.SplitBar.TOP ?
34783                     endPoint[1] - this.dragSpecs.startPoint[1] :
34784                     this.dragSpecs.startPoint[1] - endPoint[1]
34785                 );
34786         }
34787         newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
34788         if(newSize != this.dragSpecs.startSize){
34789             if(this.fireEvent('beforeapply', this, newSize) !== false){
34790                 this.adapter.setElementSize(this, newSize);
34791                 this.fireEvent("moved", this, newSize);
34792                 this.fireEvent("resize", this, newSize);
34793             }
34794         }
34795     },
34796     
34797     /**
34798      * Get the adapter this SplitBar uses
34799      * @return The adapter object
34800      */
34801     getAdapter : function(){
34802         return this.adapter;
34803     },
34804     
34805     /**
34806      * Set the adapter this SplitBar uses
34807      * @param {Object} adapter A SplitBar adapter object
34808      */
34809     setAdapter : function(adapter){
34810         this.adapter = adapter;
34811         this.adapter.init(this);
34812     },
34813     
34814     /**
34815      * Gets the minimum size for the resizing element
34816      * @return {Number} The minimum size
34817      */
34818     getMinimumSize : function(){
34819         return this.minSize;
34820     },
34821     
34822     /**
34823      * Sets the minimum size for the resizing element
34824      * @param {Number} minSize The minimum size
34825      */
34826     setMinimumSize : function(minSize){
34827         this.minSize = minSize;
34828     },
34829     
34830     /**
34831      * Gets the maximum size for the resizing element
34832      * @return {Number} The maximum size
34833      */
34834     getMaximumSize : function(){
34835         return this.maxSize;
34836     },
34837     
34838     /**
34839      * Sets the maximum size for the resizing element
34840      * @param {Number} maxSize The maximum size
34841      */
34842     setMaximumSize : function(maxSize){
34843         this.maxSize = maxSize;
34844     },
34845     
34846     /**
34847      * Sets the initialize size for the resizing element
34848      * @param {Number} size The initial size
34849      */
34850     setCurrentSize : function(size){
34851         var oldAnimate = this.animate;
34852         this.animate = false;
34853         this.adapter.setElementSize(this, size);
34854         this.animate = oldAnimate;
34855     },
34856     
34857     /**
34858      * Destroy this splitbar. 
34859      * @param {Boolean} removeEl True to remove the element
34860      */
34861     destroy : function(removeEl){
34862         if(this.shim){
34863             this.shim.remove();
34864         }
34865         this.dd.unreg();
34866         this.proxy.parentNode.removeChild(this.proxy);
34867         if(removeEl){
34868             this.el.remove();
34869         }
34870     }
34871 });
34872
34873 /**
34874  * @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.
34875  */
34876 Roo.bootstrap.SplitBar.createProxy = function(dir){
34877     var proxy = new Roo.Element(document.createElement("div"));
34878     proxy.unselectable();
34879     var cls = 'roo-splitbar-proxy';
34880     proxy.addClass(cls + ' ' + (dir == Roo.bootstrap.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
34881     document.body.appendChild(proxy.dom);
34882     return proxy.dom;
34883 };
34884
34885 /** 
34886  * @class Roo.bootstrap.SplitBar.BasicLayoutAdapter
34887  * Default Adapter. It assumes the splitter and resizing element are not positioned
34888  * elements and only gets/sets the width of the element. Generally used for table based layouts.
34889  */
34890 Roo.bootstrap.SplitBar.BasicLayoutAdapter = function(){
34891 };
34892
34893 Roo.bootstrap.SplitBar.BasicLayoutAdapter.prototype = {
34894     // do nothing for now
34895     init : function(s){
34896     
34897     },
34898     /**
34899      * Called before drag operations to get the current size of the resizing element. 
34900      * @param {Roo.bootstrap.SplitBar} s The SplitBar using this adapter
34901      */
34902      getElementSize : function(s){
34903         if(s.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
34904             return s.resizingEl.getWidth();
34905         }else{
34906             return s.resizingEl.getHeight();
34907         }
34908     },
34909     
34910     /**
34911      * Called after drag operations to set the size of the resizing element.
34912      * @param {Roo.bootstrap.SplitBar} s The SplitBar using this adapter
34913      * @param {Number} newSize The new size to set
34914      * @param {Function} onComplete A function to be invoked when resizing is complete
34915      */
34916     setElementSize : function(s, newSize, onComplete){
34917         if(s.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
34918             if(!s.animate){
34919                 s.resizingEl.setWidth(newSize);
34920                 if(onComplete){
34921                     onComplete(s, newSize);
34922                 }
34923             }else{
34924                 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
34925             }
34926         }else{
34927             
34928             if(!s.animate){
34929                 s.resizingEl.setHeight(newSize);
34930                 if(onComplete){
34931                     onComplete(s, newSize);
34932                 }
34933             }else{
34934                 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
34935             }
34936         }
34937     }
34938 };
34939
34940 /** 
34941  *@class Roo.bootstrap.SplitBar.AbsoluteLayoutAdapter
34942  * @extends Roo.bootstrap.SplitBar.BasicLayoutAdapter
34943  * Adapter that  moves the splitter element to align with the resized sizing element. 
34944  * Used with an absolute positioned SplitBar.
34945  * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
34946  * document.body, make sure you assign an id to the body element.
34947  */
34948 Roo.bootstrap.SplitBar.AbsoluteLayoutAdapter = function(container){
34949     this.basic = new Roo.bootstrap.SplitBar.BasicLayoutAdapter();
34950     this.container = Roo.get(container);
34951 };
34952
34953 Roo.bootstrap.SplitBar.AbsoluteLayoutAdapter.prototype = {
34954     init : function(s){
34955         this.basic.init(s);
34956     },
34957     
34958     getElementSize : function(s){
34959         return this.basic.getElementSize(s);
34960     },
34961     
34962     setElementSize : function(s, newSize, onComplete){
34963         this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
34964     },
34965     
34966     moveSplitter : function(s){
34967         var yes = Roo.bootstrap.SplitBar;
34968         switch(s.placement){
34969             case yes.LEFT:
34970                 s.el.setX(s.resizingEl.getRight());
34971                 break;
34972             case yes.RIGHT:
34973                 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
34974                 break;
34975             case yes.TOP:
34976                 s.el.setY(s.resizingEl.getBottom());
34977                 break;
34978             case yes.BOTTOM:
34979                 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
34980                 break;
34981         }
34982     }
34983 };
34984
34985 /**
34986  * Orientation constant - Create a vertical SplitBar
34987  * @static
34988  * @type Number
34989  */
34990 Roo.bootstrap.SplitBar.VERTICAL = 1;
34991
34992 /**
34993  * Orientation constant - Create a horizontal SplitBar
34994  * @static
34995  * @type Number
34996  */
34997 Roo.bootstrap.SplitBar.HORIZONTAL = 2;
34998
34999 /**
35000  * Placement constant - The resizing element is to the left of the splitter element
35001  * @static
35002  * @type Number
35003  */
35004 Roo.bootstrap.SplitBar.LEFT = 1;
35005
35006 /**
35007  * Placement constant - The resizing element is to the right of the splitter element
35008  * @static
35009  * @type Number
35010  */
35011 Roo.bootstrap.SplitBar.RIGHT = 2;
35012
35013 /**
35014  * Placement constant - The resizing element is positioned above the splitter element
35015  * @static
35016  * @type Number
35017  */
35018 Roo.bootstrap.SplitBar.TOP = 3;
35019
35020 /**
35021  * Placement constant - The resizing element is positioned under splitter element
35022  * @static
35023  * @type Number
35024  */
35025 Roo.bootstrap.SplitBar.BOTTOM = 4;
35026 Roo.namespace("Roo.bootstrap.layout");/*
35027  * Based on:
35028  * Ext JS Library 1.1.1
35029  * Copyright(c) 2006-2007, Ext JS, LLC.
35030  *
35031  * Originally Released Under LGPL - original licence link has changed is not relivant.
35032  *
35033  * Fork - LGPL
35034  * <script type="text/javascript">
35035  */
35036
35037 /**
35038  * @class Roo.bootstrap.layout.Manager
35039  * @extends Roo.bootstrap.Component
35040  * Base class for layout managers.
35041  */
35042 Roo.bootstrap.layout.Manager = function(config)
35043 {
35044     Roo.bootstrap.layout.Manager.superclass.constructor.call(this,config);
35045
35046
35047
35048
35049
35050     /** false to disable window resize monitoring @type Boolean */
35051     this.monitorWindowResize = true;
35052     this.regions = {};
35053     this.addEvents({
35054         /**
35055          * @event layout
35056          * Fires when a layout is performed.
35057          * @param {Roo.LayoutManager} this
35058          */
35059         "layout" : true,
35060         /**
35061          * @event regionresized
35062          * Fires when the user resizes a region.
35063          * @param {Roo.LayoutRegion} region The resized region
35064          * @param {Number} newSize The new size (width for east/west, height for north/south)
35065          */
35066         "regionresized" : true,
35067         /**
35068          * @event regioncollapsed
35069          * Fires when a region is collapsed.
35070          * @param {Roo.LayoutRegion} region The collapsed region
35071          */
35072         "regioncollapsed" : true,
35073         /**
35074          * @event regionexpanded
35075          * Fires when a region is expanded.
35076          * @param {Roo.LayoutRegion} region The expanded region
35077          */
35078         "regionexpanded" : true
35079     });
35080     this.updating = false;
35081
35082     if (config.el) {
35083         this.el = Roo.get(config.el);
35084         this.initEvents();
35085     }
35086
35087 };
35088
35089 Roo.extend(Roo.bootstrap.layout.Manager, Roo.bootstrap.Component, {
35090
35091
35092     regions : null,
35093
35094     monitorWindowResize : true,
35095
35096
35097     updating : false,
35098
35099
35100     onRender : function(ct, position)
35101     {
35102         if(!this.el){
35103             this.el = Roo.get(ct);
35104             this.initEvents();
35105         }
35106         //this.fireEvent('render',this);
35107     },
35108
35109
35110     initEvents: function()
35111     {
35112
35113
35114         // ie scrollbar fix
35115         if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
35116             document.body.scroll = "no";
35117         }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
35118             this.el.position('relative');
35119         }
35120         this.id = this.el.id;
35121         this.el.addClass("roo-layout-container");
35122         Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
35123         if(this.el.dom != document.body ) {
35124             this.el.on('resize', this.layout,this);
35125             this.el.on('show', this.layout,this);
35126         }
35127
35128     },
35129
35130     /**
35131      * Returns true if this layout is currently being updated
35132      * @return {Boolean}
35133      */
35134     isUpdating : function(){
35135         return this.updating;
35136     },
35137
35138     /**
35139      * Suspend the LayoutManager from doing auto-layouts while
35140      * making multiple add or remove calls
35141      */
35142     beginUpdate : function(){
35143         this.updating = true;
35144     },
35145
35146     /**
35147      * Restore auto-layouts and optionally disable the manager from performing a layout
35148      * @param {Boolean} noLayout true to disable a layout update
35149      */
35150     endUpdate : function(noLayout){
35151         this.updating = false;
35152         if(!noLayout){
35153             this.layout();
35154         }
35155     },
35156
35157     layout: function(){
35158         // abstract...
35159     },
35160
35161     onRegionResized : function(region, newSize){
35162         this.fireEvent("regionresized", region, newSize);
35163         this.layout();
35164     },
35165
35166     onRegionCollapsed : function(region){
35167         this.fireEvent("regioncollapsed", region);
35168     },
35169
35170     onRegionExpanded : function(region){
35171         this.fireEvent("regionexpanded", region);
35172     },
35173
35174     /**
35175      * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
35176      * performs box-model adjustments.
35177      * @return {Object} The size as an object {width: (the width), height: (the height)}
35178      */
35179     getViewSize : function()
35180     {
35181         var size;
35182         if(this.el.dom != document.body){
35183             size = this.el.getSize();
35184         }else{
35185             size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
35186         }
35187         size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
35188         size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
35189         return size;
35190     },
35191
35192     /**
35193      * Returns the Element this layout is bound to.
35194      * @return {Roo.Element}
35195      */
35196     getEl : function(){
35197         return this.el;
35198     },
35199
35200     /**
35201      * Returns the specified region.
35202      * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
35203      * @return {Roo.LayoutRegion}
35204      */
35205     getRegion : function(target){
35206         return this.regions[target.toLowerCase()];
35207     },
35208
35209     onWindowResize : function(){
35210         if(this.monitorWindowResize){
35211             this.layout();
35212         }
35213     }
35214 });
35215 /*
35216  * Based on:
35217  * Ext JS Library 1.1.1
35218  * Copyright(c) 2006-2007, Ext JS, LLC.
35219  *
35220  * Originally Released Under LGPL - original licence link has changed is not relivant.
35221  *
35222  * Fork - LGPL
35223  * <script type="text/javascript">
35224  */
35225 /**
35226  * @class Roo.bootstrap.layout.Border
35227  * @extends Roo.bootstrap.layout.Manager
35228  * This class represents a common layout manager used in desktop applications. For screenshots and more details,
35229  * please see: examples/bootstrap/nested.html<br><br>
35230  
35231 <b>The container the layout is rendered into can be either the body element or any other element.
35232 If it is not the body element, the container needs to either be an absolute positioned element,
35233 or you will need to add "position:relative" to the css of the container.  You will also need to specify
35234 the container size if it is not the body element.</b>
35235
35236 * @constructor
35237 * Create a new Border
35238 * @param {Object} config Configuration options
35239  */
35240 Roo.bootstrap.layout.Border = function(config){
35241     config = config || {};
35242     Roo.bootstrap.layout.Border.superclass.constructor.call(this, config);
35243     
35244     
35245     
35246     Roo.each(Roo.bootstrap.layout.Border.regions, function(region) {
35247         if(config[region]){
35248             config[region].region = region;
35249             this.addRegion(config[region]);
35250         }
35251     },this);
35252     
35253 };
35254
35255 Roo.bootstrap.layout.Border.regions =  ["north","south","east","west","center"];
35256
35257 Roo.extend(Roo.bootstrap.layout.Border, Roo.bootstrap.layout.Manager, {
35258     
35259     parent : false, // this might point to a 'nest' or a ???
35260     
35261     /**
35262      * Creates and adds a new region if it doesn't already exist.
35263      * @param {String} target The target region key (north, south, east, west or center).
35264      * @param {Object} config The regions config object
35265      * @return {BorderLayoutRegion} The new region
35266      */
35267     addRegion : function(config)
35268     {
35269         if(!this.regions[config.region]){
35270             var r = this.factory(config);
35271             this.bindRegion(r);
35272         }
35273         return this.regions[config.region];
35274     },
35275
35276     // private (kinda)
35277     bindRegion : function(r){
35278         this.regions[r.config.region] = r;
35279         
35280         r.on("visibilitychange",    this.layout, this);
35281         r.on("paneladded",          this.layout, this);
35282         r.on("panelremoved",        this.layout, this);
35283         r.on("invalidated",         this.layout, this);
35284         r.on("resized",             this.onRegionResized, this);
35285         r.on("collapsed",           this.onRegionCollapsed, this);
35286         r.on("expanded",            this.onRegionExpanded, this);
35287     },
35288
35289     /**
35290      * Performs a layout update.
35291      */
35292     layout : function()
35293     {
35294         if(this.updating) {
35295             return;
35296         }
35297         
35298         // render all the rebions if they have not been done alreayd?
35299         Roo.each(Roo.bootstrap.layout.Border.regions, function(region) {
35300             if(this.regions[region] && !this.regions[region].bodyEl){
35301                 this.regions[region].onRender(this.el)
35302             }
35303         },this);
35304         
35305         var size = this.getViewSize();
35306         var w = size.width;
35307         var h = size.height;
35308         var centerW = w;
35309         var centerH = h;
35310         var centerY = 0;
35311         var centerX = 0;
35312         //var x = 0, y = 0;
35313
35314         var rs = this.regions;
35315         var north = rs["north"];
35316         var south = rs["south"]; 
35317         var west = rs["west"];
35318         var east = rs["east"];
35319         var center = rs["center"];
35320         //if(this.hideOnLayout){ // not supported anymore
35321             //c.el.setStyle("display", "none");
35322         //}
35323         if(north && north.isVisible()){
35324             var b = north.getBox();
35325             var m = north.getMargins();
35326             b.width = w - (m.left+m.right);
35327             b.x = m.left;
35328             b.y = m.top;
35329             centerY = b.height + b.y + m.bottom;
35330             centerH -= centerY;
35331             north.updateBox(this.safeBox(b));
35332         }
35333         if(south && south.isVisible()){
35334             var b = south.getBox();
35335             var m = south.getMargins();
35336             b.width = w - (m.left+m.right);
35337             b.x = m.left;
35338             var totalHeight = (b.height + m.top + m.bottom);
35339             b.y = h - totalHeight + m.top;
35340             centerH -= totalHeight;
35341             south.updateBox(this.safeBox(b));
35342         }
35343         if(west && west.isVisible()){
35344             var b = west.getBox();
35345             var m = west.getMargins();
35346             b.height = centerH - (m.top+m.bottom);
35347             b.x = m.left;
35348             b.y = centerY + m.top;
35349             var totalWidth = (b.width + m.left + m.right);
35350             centerX += totalWidth;
35351             centerW -= totalWidth;
35352             west.updateBox(this.safeBox(b));
35353         }
35354         if(east && east.isVisible()){
35355             var b = east.getBox();
35356             var m = east.getMargins();
35357             b.height = centerH - (m.top+m.bottom);
35358             var totalWidth = (b.width + m.left + m.right);
35359             b.x = w - totalWidth + m.left;
35360             b.y = centerY + m.top;
35361             centerW -= totalWidth;
35362             east.updateBox(this.safeBox(b));
35363         }
35364         if(center){
35365             var m = center.getMargins();
35366             var centerBox = {
35367                 x: centerX + m.left,
35368                 y: centerY + m.top,
35369                 width: centerW - (m.left+m.right),
35370                 height: centerH - (m.top+m.bottom)
35371             };
35372             //if(this.hideOnLayout){
35373                 //center.el.setStyle("display", "block");
35374             //}
35375             center.updateBox(this.safeBox(centerBox));
35376         }
35377         this.el.repaint();
35378         this.fireEvent("layout", this);
35379     },
35380
35381     // private
35382     safeBox : function(box){
35383         box.width = Math.max(0, box.width);
35384         box.height = Math.max(0, box.height);
35385         return box;
35386     },
35387
35388     /**
35389      * Adds a ContentPanel (or subclass) to this layout.
35390      * @param {String} target The target region key (north, south, east, west or center).
35391      * @param {Roo.ContentPanel} panel The panel to add
35392      * @return {Roo.ContentPanel} The added panel
35393      */
35394     add : function(target, panel){
35395          
35396         target = target.toLowerCase();
35397         return this.regions[target].add(panel);
35398     },
35399
35400     /**
35401      * Remove a ContentPanel (or subclass) to this layout.
35402      * @param {String} target The target region key (north, south, east, west or center).
35403      * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
35404      * @return {Roo.ContentPanel} The removed panel
35405      */
35406     remove : function(target, panel){
35407         target = target.toLowerCase();
35408         return this.regions[target].remove(panel);
35409     },
35410
35411     /**
35412      * Searches all regions for a panel with the specified id
35413      * @param {String} panelId
35414      * @return {Roo.ContentPanel} The panel or null if it wasn't found
35415      */
35416     findPanel : function(panelId){
35417         var rs = this.regions;
35418         for(var target in rs){
35419             if(typeof rs[target] != "function"){
35420                 var p = rs[target].getPanel(panelId);
35421                 if(p){
35422                     return p;
35423                 }
35424             }
35425         }
35426         return null;
35427     },
35428
35429     /**
35430      * Searches all regions for a panel with the specified id and activates (shows) it.
35431      * @param {String/ContentPanel} panelId The panels id or the panel itself
35432      * @return {Roo.ContentPanel} The shown panel or null
35433      */
35434     showPanel : function(panelId) {
35435       var rs = this.regions;
35436       for(var target in rs){
35437          var r = rs[target];
35438          if(typeof r != "function"){
35439             if(r.hasPanel(panelId)){
35440                return r.showPanel(panelId);
35441             }
35442          }
35443       }
35444       return null;
35445    },
35446
35447    /**
35448      * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
35449      * @param {Roo.state.Provider} provider (optional) An alternate state provider
35450      */
35451    /*
35452     restoreState : function(provider){
35453         if(!provider){
35454             provider = Roo.state.Manager;
35455         }
35456         var sm = new Roo.LayoutStateManager();
35457         sm.init(this, provider);
35458     },
35459 */
35460  
35461  
35462     /**
35463      * Adds a xtype elements to the layout.
35464      * <pre><code>
35465
35466 layout.addxtype({
35467        xtype : 'ContentPanel',
35468        region: 'west',
35469        items: [ .... ]
35470    }
35471 );
35472
35473 layout.addxtype({
35474         xtype : 'NestedLayoutPanel',
35475         region: 'west',
35476         layout: {
35477            center: { },
35478            west: { }   
35479         },
35480         items : [ ... list of content panels or nested layout panels.. ]
35481    }
35482 );
35483 </code></pre>
35484      * @param {Object} cfg Xtype definition of item to add.
35485      */
35486     addxtype : function(cfg)
35487     {
35488         // basically accepts a pannel...
35489         // can accept a layout region..!?!?
35490         //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
35491         
35492         
35493         // theory?  children can only be panels??
35494         
35495         //if (!cfg.xtype.match(/Panel$/)) {
35496         //    return false;
35497         //}
35498         var ret = false;
35499         
35500         if (typeof(cfg.region) == 'undefined') {
35501             Roo.log("Failed to add Panel, region was not set");
35502             Roo.log(cfg);
35503             return false;
35504         }
35505         var region = cfg.region;
35506         delete cfg.region;
35507         
35508           
35509         var xitems = [];
35510         if (cfg.items) {
35511             xitems = cfg.items;
35512             delete cfg.items;
35513         }
35514         var nb = false;
35515         
35516         if ( region == 'center') {
35517             Roo.log("Center: " + cfg.title);
35518         }
35519         
35520         
35521         switch(cfg.xtype) 
35522         {
35523             case 'Content':  // ContentPanel (el, cfg)
35524             case 'Scroll':  // ContentPanel (el, cfg)
35525             case 'View': 
35526                 cfg.autoCreate = cfg.autoCreate || true;
35527                 ret = new cfg.xns[cfg.xtype](cfg); // new panel!!!!!
35528                 //} else {
35529                 //    var el = this.el.createChild();
35530                 //    ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
35531                 //}
35532                 
35533                 this.add(region, ret);
35534                 break;
35535             
35536             /*
35537             case 'TreePanel': // our new panel!
35538                 cfg.el = this.el.createChild();
35539                 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
35540                 this.add(region, ret);
35541                 break;
35542             */
35543             
35544             case 'Nest': 
35545                 // create a new Layout (which is  a Border Layout...
35546                 
35547                 var clayout = cfg.layout;
35548                 clayout.el  = this.el.createChild();
35549                 clayout.items   = clayout.items  || [];
35550                 
35551                 delete cfg.layout;
35552                 
35553                 // replace this exitems with the clayout ones..
35554                 xitems = clayout.items;
35555                  
35556                 // force background off if it's in center...
35557                 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
35558                     cfg.background = false;
35559                 }
35560                 cfg.layout  = new Roo.bootstrap.layout.Border(clayout);
35561                 
35562                 
35563                 ret = new cfg.xns[cfg.xtype](cfg); // new panel!!!!!
35564                 //console.log('adding nested layout panel '  + cfg.toSource());
35565                 this.add(region, ret);
35566                 nb = {}; /// find first...
35567                 break;
35568             
35569             case 'Grid':
35570                 
35571                 // needs grid and region
35572                 
35573                 //var el = this.getRegion(region).el.createChild();
35574                 /*
35575                  *var el = this.el.createChild();
35576                 // create the grid first...
35577                 cfg.grid.container = el;
35578                 cfg.grid = new cfg.grid.xns[cfg.grid.xtype](cfg.grid);
35579                 */
35580                 
35581                 if (region == 'center' && this.active ) {
35582                     cfg.background = false;
35583                 }
35584                 
35585                 ret = new cfg.xns[cfg.xtype](cfg); // new panel!!!!!
35586                 
35587                 this.add(region, ret);
35588                 /*
35589                 if (cfg.background) {
35590                     // render grid on panel activation (if panel background)
35591                     ret.on('activate', function(gp) {
35592                         if (!gp.grid.rendered) {
35593                     //        gp.grid.render(el);
35594                         }
35595                     });
35596                 } else {
35597                   //  cfg.grid.render(el);
35598                 }
35599                 */
35600                 break;
35601            
35602            
35603             case 'Border': // it can get called on it'self... - might need to check if this is fixed?
35604                 // it was the old xcomponent building that caused this before.
35605                 // espeically if border is the top element in the tree.
35606                 ret = this;
35607                 break; 
35608                 
35609                     
35610                 
35611                 
35612                 
35613             default:
35614                 /*
35615                 if (typeof(Roo[cfg.xtype]) != 'undefined') {
35616                     
35617                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
35618                     this.add(region, ret);
35619                 } else {
35620                 */
35621                     Roo.log(cfg);
35622                     throw "Can not add '" + cfg.xtype + "' to Border";
35623                     return null;
35624              
35625                                 
35626              
35627         }
35628         this.beginUpdate();
35629         // add children..
35630         var region = '';
35631         var abn = {};
35632         Roo.each(xitems, function(i)  {
35633             region = nb && i.region ? i.region : false;
35634             
35635             var add = ret.addxtype(i);
35636            
35637             if (region) {
35638                 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
35639                 if (!i.background) {
35640                     abn[region] = nb[region] ;
35641                 }
35642             }
35643             
35644         });
35645         this.endUpdate();
35646
35647         // make the last non-background panel active..
35648         //if (nb) { Roo.log(abn); }
35649         if (nb) {
35650             
35651             for(var r in abn) {
35652                 region = this.getRegion(r);
35653                 if (region) {
35654                     // tried using nb[r], but it does not work..
35655                      
35656                     region.showPanel(abn[r]);
35657                    
35658                 }
35659             }
35660         }
35661         return ret;
35662         
35663     },
35664     
35665     
35666 // private
35667     factory : function(cfg)
35668     {
35669         
35670         var validRegions = Roo.bootstrap.layout.Border.regions;
35671
35672         var target = cfg.region;
35673         cfg.mgr = this;
35674         
35675         var r = Roo.bootstrap.layout;
35676         Roo.log(target);
35677         switch(target){
35678             case "north":
35679                 return new r.North(cfg);
35680             case "south":
35681                 return new r.South(cfg);
35682             case "east":
35683                 return new r.East(cfg);
35684             case "west":
35685                 return new r.West(cfg);
35686             case "center":
35687                 return new r.Center(cfg);
35688         }
35689         throw 'Layout region "'+target+'" not supported.';
35690     }
35691     
35692     
35693 });
35694  /*
35695  * Based on:
35696  * Ext JS Library 1.1.1
35697  * Copyright(c) 2006-2007, Ext JS, LLC.
35698  *
35699  * Originally Released Under LGPL - original licence link has changed is not relivant.
35700  *
35701  * Fork - LGPL
35702  * <script type="text/javascript">
35703  */
35704  
35705 /**
35706  * @class Roo.bootstrap.layout.Basic
35707  * @extends Roo.util.Observable
35708  * This class represents a lightweight region in a layout manager. This region does not move dom nodes
35709  * and does not have a titlebar, tabs or any other features. All it does is size and position 
35710  * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
35711  * @cfg {Roo.bootstrap.layout.Manager}   mgr The manager
35712  * @cfg {string}   region  the region that it inhabits..
35713  * @cfg {bool}   skipConfig skip config?
35714  * 
35715
35716  */
35717 Roo.bootstrap.layout.Basic = function(config){
35718     
35719     this.mgr = config.mgr;
35720     
35721     this.position = config.region;
35722     
35723     var skipConfig = config.skipConfig;
35724     
35725     this.events = {
35726         /**
35727          * @scope Roo.BasicLayoutRegion
35728          */
35729         
35730         /**
35731          * @event beforeremove
35732          * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
35733          * @param {Roo.LayoutRegion} this
35734          * @param {Roo.ContentPanel} panel The panel
35735          * @param {Object} e The cancel event object
35736          */
35737         "beforeremove" : true,
35738         /**
35739          * @event invalidated
35740          * Fires when the layout for this region is changed.
35741          * @param {Roo.LayoutRegion} this
35742          */
35743         "invalidated" : true,
35744         /**
35745          * @event visibilitychange
35746          * Fires when this region is shown or hidden 
35747          * @param {Roo.LayoutRegion} this
35748          * @param {Boolean} visibility true or false
35749          */
35750         "visibilitychange" : true,
35751         /**
35752          * @event paneladded
35753          * Fires when a panel is added. 
35754          * @param {Roo.LayoutRegion} this
35755          * @param {Roo.ContentPanel} panel The panel
35756          */
35757         "paneladded" : true,
35758         /**
35759          * @event panelremoved
35760          * Fires when a panel is removed. 
35761          * @param {Roo.LayoutRegion} this
35762          * @param {Roo.ContentPanel} panel The panel
35763          */
35764         "panelremoved" : true,
35765         /**
35766          * @event beforecollapse
35767          * Fires when this region before collapse.
35768          * @param {Roo.LayoutRegion} this
35769          */
35770         "beforecollapse" : true,
35771         /**
35772          * @event collapsed
35773          * Fires when this region is collapsed.
35774          * @param {Roo.LayoutRegion} this
35775          */
35776         "collapsed" : true,
35777         /**
35778          * @event expanded
35779          * Fires when this region is expanded.
35780          * @param {Roo.LayoutRegion} this
35781          */
35782         "expanded" : true,
35783         /**
35784          * @event slideshow
35785          * Fires when this region is slid into view.
35786          * @param {Roo.LayoutRegion} this
35787          */
35788         "slideshow" : true,
35789         /**
35790          * @event slidehide
35791          * Fires when this region slides out of view. 
35792          * @param {Roo.LayoutRegion} this
35793          */
35794         "slidehide" : true,
35795         /**
35796          * @event panelactivated
35797          * Fires when a panel is activated. 
35798          * @param {Roo.LayoutRegion} this
35799          * @param {Roo.ContentPanel} panel The activated panel
35800          */
35801         "panelactivated" : true,
35802         /**
35803          * @event resized
35804          * Fires when the user resizes this region. 
35805          * @param {Roo.LayoutRegion} this
35806          * @param {Number} newSize The new size (width for east/west, height for north/south)
35807          */
35808         "resized" : true
35809     };
35810     /** A collection of panels in this region. @type Roo.util.MixedCollection */
35811     this.panels = new Roo.util.MixedCollection();
35812     this.panels.getKey = this.getPanelId.createDelegate(this);
35813     this.box = null;
35814     this.activePanel = null;
35815     // ensure listeners are added...
35816     
35817     if (config.listeners || config.events) {
35818         Roo.bootstrap.layout.Basic.superclass.constructor.call(this, {
35819             listeners : config.listeners || {},
35820             events : config.events || {}
35821         });
35822     }
35823     
35824     if(skipConfig !== true){
35825         this.applyConfig(config);
35826     }
35827 };
35828
35829 Roo.extend(Roo.bootstrap.layout.Basic, Roo.util.Observable,
35830 {
35831     getPanelId : function(p){
35832         return p.getId();
35833     },
35834     
35835     applyConfig : function(config){
35836         this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
35837         this.config = config;
35838         
35839     },
35840     
35841     /**
35842      * Resizes the region to the specified size. For vertical regions (west, east) this adjusts 
35843      * the width, for horizontal (north, south) the height.
35844      * @param {Number} newSize The new width or height
35845      */
35846     resizeTo : function(newSize){
35847         var el = this.el ? this.el :
35848                  (this.activePanel ? this.activePanel.getEl() : null);
35849         if(el){
35850             switch(this.position){
35851                 case "east":
35852                 case "west":
35853                     el.setWidth(newSize);
35854                     this.fireEvent("resized", this, newSize);
35855                 break;
35856                 case "north":
35857                 case "south":
35858                     el.setHeight(newSize);
35859                     this.fireEvent("resized", this, newSize);
35860                 break;                
35861             }
35862         }
35863     },
35864     
35865     getBox : function(){
35866         return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
35867     },
35868     
35869     getMargins : function(){
35870         return this.margins;
35871     },
35872     
35873     updateBox : function(box){
35874         this.box = box;
35875         var el = this.activePanel.getEl();
35876         el.dom.style.left = box.x + "px";
35877         el.dom.style.top = box.y + "px";
35878         this.activePanel.setSize(box.width, box.height);
35879     },
35880     
35881     /**
35882      * Returns the container element for this region.
35883      * @return {Roo.Element}
35884      */
35885     getEl : function(){
35886         return this.activePanel;
35887     },
35888     
35889     /**
35890      * Returns true if this region is currently visible.
35891      * @return {Boolean}
35892      */
35893     isVisible : function(){
35894         return this.activePanel ? true : false;
35895     },
35896     
35897     setActivePanel : function(panel){
35898         panel = this.getPanel(panel);
35899         if(this.activePanel && this.activePanel != panel){
35900             this.activePanel.setActiveState(false);
35901             this.activePanel.getEl().setLeftTop(-10000,-10000);
35902         }
35903         this.activePanel = panel;
35904         panel.setActiveState(true);
35905         if(this.box){
35906             panel.setSize(this.box.width, this.box.height);
35907         }
35908         this.fireEvent("panelactivated", this, panel);
35909         this.fireEvent("invalidated");
35910     },
35911     
35912     /**
35913      * Show the specified panel.
35914      * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
35915      * @return {Roo.ContentPanel} The shown panel or null
35916      */
35917     showPanel : function(panel){
35918         panel = this.getPanel(panel);
35919         if(panel){
35920             this.setActivePanel(panel);
35921         }
35922         return panel;
35923     },
35924     
35925     /**
35926      * Get the active panel for this region.
35927      * @return {Roo.ContentPanel} The active panel or null
35928      */
35929     getActivePanel : function(){
35930         return this.activePanel;
35931     },
35932     
35933     /**
35934      * Add the passed ContentPanel(s)
35935      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
35936      * @return {Roo.ContentPanel} The panel added (if only one was added)
35937      */
35938     add : function(panel){
35939         if(arguments.length > 1){
35940             for(var i = 0, len = arguments.length; i < len; i++) {
35941                 this.add(arguments[i]);
35942             }
35943             return null;
35944         }
35945         if(this.hasPanel(panel)){
35946             this.showPanel(panel);
35947             return panel;
35948         }
35949         var el = panel.getEl();
35950         if(el.dom.parentNode != this.mgr.el.dom){
35951             this.mgr.el.dom.appendChild(el.dom);
35952         }
35953         if(panel.setRegion){
35954             panel.setRegion(this);
35955         }
35956         this.panels.add(panel);
35957         el.setStyle("position", "absolute");
35958         if(!panel.background){
35959             this.setActivePanel(panel);
35960             if(this.config.initialSize && this.panels.getCount()==1){
35961                 this.resizeTo(this.config.initialSize);
35962             }
35963         }
35964         this.fireEvent("paneladded", this, panel);
35965         return panel;
35966     },
35967     
35968     /**
35969      * Returns true if the panel is in this region.
35970      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
35971      * @return {Boolean}
35972      */
35973     hasPanel : function(panel){
35974         if(typeof panel == "object"){ // must be panel obj
35975             panel = panel.getId();
35976         }
35977         return this.getPanel(panel) ? true : false;
35978     },
35979     
35980     /**
35981      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
35982      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
35983      * @param {Boolean} preservePanel Overrides the config preservePanel option
35984      * @return {Roo.ContentPanel} The panel that was removed
35985      */
35986     remove : function(panel, preservePanel){
35987         panel = this.getPanel(panel);
35988         if(!panel){
35989             return null;
35990         }
35991         var e = {};
35992         this.fireEvent("beforeremove", this, panel, e);
35993         if(e.cancel === true){
35994             return null;
35995         }
35996         var panelId = panel.getId();
35997         this.panels.removeKey(panelId);
35998         return panel;
35999     },
36000     
36001     /**
36002      * Returns the panel specified or null if it's not in this region.
36003      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
36004      * @return {Roo.ContentPanel}
36005      */
36006     getPanel : function(id){
36007         if(typeof id == "object"){ // must be panel obj
36008             return id;
36009         }
36010         return this.panels.get(id);
36011     },
36012     
36013     /**
36014      * Returns this regions position (north/south/east/west/center).
36015      * @return {String} 
36016      */
36017     getPosition: function(){
36018         return this.position;    
36019     }
36020 });/*
36021  * Based on:
36022  * Ext JS Library 1.1.1
36023  * Copyright(c) 2006-2007, Ext JS, LLC.
36024  *
36025  * Originally Released Under LGPL - original licence link has changed is not relivant.
36026  *
36027  * Fork - LGPL
36028  * <script type="text/javascript">
36029  */
36030  
36031 /**
36032  * @class Roo.bootstrap.layout.Region
36033  * @extends Roo.bootstrap.layout.Basic
36034  * This class represents a region in a layout manager.
36035  
36036  * @cfg {Object}    margins         Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
36037  * @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})
36038  * @cfg {String}    tabPosition     (top|bottom) "top" or "bottom" (defaults to "bottom")
36039  * @cfg {Boolean}   alwaysShowTabs  True to always display tabs even when there is only 1 panel (defaults to false)
36040  * @cfg {Boolean}   autoScroll      True to enable overflow scrolling (defaults to false)
36041  * @cfg {Boolean}   titlebar        True to display a title bar (defaults to true)
36042  * @cfg {String}    title           The title for the region (overrides panel titles)
36043  * @cfg {Boolean}   animate         True to animate expand/collapse (defaults to false)
36044  * @cfg {Boolean}   autoHide        False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
36045  * @cfg {Boolean}   preservePanels  True to preserve removed panels so they can be readded later (defaults to false)
36046  * @cfg {Boolean}   closeOnTab      True to place the close icon on the tabs instead of the region titlebar (defaults to false)
36047  * @cfg {Boolean}   hideTabs        True to hide the tab strip (defaults to false)
36048  * @cfg {Boolean}   resizeTabs      True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
36049  *                      the space available, similar to FireFox 1.5 tabs (defaults to false)
36050  * @cfg {Number}    minTabWidth     The minimum tab width (defaults to 40)
36051  * @cfg {Number}    preferredTabWidth The preferred tab width (defaults to 150)
36052  * @cfg {String}    overflow       (hidden|visible) if you have menus in the region, then you need to set this to visible.
36053
36054  * @cfg {Boolean}   hidden          True to start the region hidden (defaults to false)
36055  * @cfg {Boolean}   hideWhenEmpty   True to hide the region when it has no panels
36056  * @cfg {Boolean}   disableTabTips  True to disable tab tooltips
36057  * @cfg {Number}    width           For East/West panels
36058  * @cfg {Number}    height          For North/South panels
36059  * @cfg {Boolean}   split           To show the splitter
36060  * @cfg {Boolean}   toolbar         xtype configuration for a toolbar - shows on right of tabbar
36061  * 
36062  * @cfg {string}   cls             Extra CSS classes to add to region
36063  * 
36064  * @cfg {Roo.bootstrap.layout.Manager}   mgr The manager
36065  * @cfg {string}   region  the region that it inhabits..
36066  *
36067
36068  * @xxxcfg {Boolean}   collapsible     DISABLED False to disable collapsing (defaults to true)
36069  * @xxxcfg {Boolean}   collapsed       DISABLED True to set the initial display to collapsed (defaults to false)
36070
36071  * @xxxcfg {String}    collapsedTitle  DISABLED Optional string message to display in the collapsed block of a north or south region
36072  * @xxxxcfg {Boolean}   floatable       DISABLED False to disable floating (defaults to true)
36073  * @xxxxcfg {Boolean}   showPin         True to show a pin button NOT SUPPORTED YET
36074  */
36075 Roo.bootstrap.layout.Region = function(config)
36076 {
36077     this.applyConfig(config);
36078
36079     var mgr = config.mgr;
36080     var pos = config.region;
36081     config.skipConfig = true;
36082     Roo.bootstrap.layout.Region.superclass.constructor.call(this, config);
36083     
36084     if (mgr.el) {
36085         this.onRender(mgr.el);   
36086     }
36087      
36088     this.visible = true;
36089     this.collapsed = false;
36090     this.unrendered_panels = [];
36091 };
36092
36093 Roo.extend(Roo.bootstrap.layout.Region, Roo.bootstrap.layout.Basic, {
36094
36095     position: '', // set by wrapper (eg. north/south etc..)
36096     unrendered_panels : null,  // unrendered panels.
36097     
36098     tabPosition : false,
36099     
36100     mgr: false, // points to 'Border'
36101     
36102     
36103     createBody : function(){
36104         /** This region's body element 
36105         * @type Roo.Element */
36106         this.bodyEl = this.el.createChild({
36107                 tag: "div",
36108                 cls: "roo-layout-panel-body tab-content" // bootstrap added...
36109         });
36110     },
36111
36112     onRender: function(ctr, pos)
36113     {
36114         var dh = Roo.DomHelper;
36115         /** This region's container element 
36116         * @type Roo.Element */
36117         this.el = dh.append(ctr.dom, {
36118                 tag: "div",
36119                 cls: (this.config.cls || '') + " roo-layout-region roo-layout-panel roo-layout-panel-" + this.position
36120             }, true);
36121         /** This region's title element 
36122         * @type Roo.Element */
36123     
36124         this.titleEl = dh.append(this.el.dom,  {
36125                 tag: "div",
36126                 unselectable: "on",
36127                 cls: "roo-unselectable roo-layout-panel-hd breadcrumb roo-layout-title-" + this.position,
36128                 children:[
36129                     {tag: "span", cls: "roo-unselectable roo-layout-panel-hd-text", unselectable: "on", html: "&#160;"},
36130                     {tag: "div", cls: "roo-unselectable roo-layout-panel-hd-tools", unselectable: "on"}
36131                 ]
36132             }, true);
36133         
36134         this.titleEl.enableDisplayMode();
36135         /** This region's title text element 
36136         * @type HTMLElement */
36137         this.titleTextEl = this.titleEl.dom.firstChild;
36138         this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
36139         /*
36140         this.closeBtn = this.createTool(this.tools.dom, "roo-layout-close");
36141         this.closeBtn.enableDisplayMode();
36142         this.closeBtn.on("click", this.closeClicked, this);
36143         this.closeBtn.hide();
36144     */
36145         this.createBody(this.config);
36146         if(this.config.hideWhenEmpty){
36147             this.hide();
36148             this.on("paneladded", this.validateVisibility, this);
36149             this.on("panelremoved", this.validateVisibility, this);
36150         }
36151         if(this.autoScroll){
36152             this.bodyEl.setStyle("overflow", "auto");
36153         }else{
36154             this.bodyEl.setStyle("overflow", this.config.overflow || 'hidden');
36155         }
36156         //if(c.titlebar !== false){
36157             if((!this.config.titlebar && !this.config.title) || this.config.titlebar === false){
36158                 this.titleEl.hide();
36159             }else{
36160                 this.titleEl.show();
36161                 if(this.config.title){
36162                     this.titleTextEl.innerHTML = this.config.title;
36163                 }
36164             }
36165         //}
36166         if(this.config.collapsed){
36167             this.collapse(true);
36168         }
36169         if(this.config.hidden){
36170             this.hide();
36171         }
36172         
36173         if (this.unrendered_panels && this.unrendered_panels.length) {
36174             for (var i =0;i< this.unrendered_panels.length; i++) {
36175                 this.add(this.unrendered_panels[i]);
36176             }
36177             this.unrendered_panels = null;
36178             
36179         }
36180         
36181     },
36182     
36183     applyConfig : function(c)
36184     {
36185         /*
36186          *if(c.collapsible && this.position != "center" && !this.collapsedEl){
36187             var dh = Roo.DomHelper;
36188             if(c.titlebar !== false){
36189                 this.collapseBtn = this.createTool(this.tools.dom, "roo-layout-collapse-"+this.position);
36190                 this.collapseBtn.on("click", this.collapse, this);
36191                 this.collapseBtn.enableDisplayMode();
36192                 /*
36193                 if(c.showPin === true || this.showPin){
36194                     this.stickBtn = this.createTool(this.tools.dom, "roo-layout-stick");
36195                     this.stickBtn.enableDisplayMode();
36196                     this.stickBtn.on("click", this.expand, this);
36197                     this.stickBtn.hide();
36198                 }
36199                 
36200             }
36201             */
36202             /** This region's collapsed element
36203             * @type Roo.Element */
36204             /*
36205              *
36206             this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
36207                 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
36208             ]}, true);
36209             
36210             if(c.floatable !== false){
36211                this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
36212                this.collapsedEl.on("click", this.collapseClick, this);
36213             }
36214
36215             if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
36216                 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
36217                    id: "message", unselectable: "on", style:{"float":"left"}});
36218                this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
36219              }
36220             this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
36221             this.expandBtn.on("click", this.expand, this);
36222             
36223         }
36224         
36225         if(this.collapseBtn){
36226             this.collapseBtn.setVisible(c.collapsible == true);
36227         }
36228         
36229         this.cmargins = c.cmargins || this.cmargins ||
36230                          (this.position == "west" || this.position == "east" ?
36231                              {top: 0, left: 2, right:2, bottom: 0} :
36232                              {top: 2, left: 0, right:0, bottom: 2});
36233         */
36234         this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
36235         
36236         
36237         this.tabPosition = [ 'top','bottom', 'west'].indexOf(c.tabPosition) > -1 ? c.tabPosition : "top";
36238         
36239         this.autoScroll = c.autoScroll || false;
36240         
36241         
36242        
36243         
36244         this.duration = c.duration || .30;
36245         this.slideDuration = c.slideDuration || .45;
36246         this.config = c;
36247        
36248     },
36249     /**
36250      * Returns true if this region is currently visible.
36251      * @return {Boolean}
36252      */
36253     isVisible : function(){
36254         return this.visible;
36255     },
36256
36257     /**
36258      * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
36259      * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&amp;#160;")
36260      */
36261     //setCollapsedTitle : function(title){
36262     //    title = title || "&#160;";
36263      //   if(this.collapsedTitleTextEl){
36264       //      this.collapsedTitleTextEl.innerHTML = title;
36265        // }
36266     //},
36267
36268     getBox : function(){
36269         var b;
36270       //  if(!this.collapsed){
36271             b = this.el.getBox(false, true);
36272        // }else{
36273           //  b = this.collapsedEl.getBox(false, true);
36274         //}
36275         return b;
36276     },
36277
36278     getMargins : function(){
36279         return this.margins;
36280         //return this.collapsed ? this.cmargins : this.margins;
36281     },
36282 /*
36283     highlight : function(){
36284         this.el.addClass("x-layout-panel-dragover");
36285     },
36286
36287     unhighlight : function(){
36288         this.el.removeClass("x-layout-panel-dragover");
36289     },
36290 */
36291     updateBox : function(box)
36292     {
36293         if (!this.bodyEl) {
36294             return; // not rendered yet..
36295         }
36296         
36297         this.box = box;
36298         if(!this.collapsed){
36299             this.el.dom.style.left = box.x + "px";
36300             this.el.dom.style.top = box.y + "px";
36301             this.updateBody(box.width, box.height);
36302         }else{
36303             this.collapsedEl.dom.style.left = box.x + "px";
36304             this.collapsedEl.dom.style.top = box.y + "px";
36305             this.collapsedEl.setSize(box.width, box.height);
36306         }
36307         if(this.tabs){
36308             this.tabs.autoSizeTabs();
36309         }
36310     },
36311
36312     updateBody : function(w, h)
36313     {
36314         if(w !== null){
36315             this.el.setWidth(w);
36316             w -= this.el.getBorderWidth("rl");
36317             if(this.config.adjustments){
36318                 w += this.config.adjustments[0];
36319             }
36320         }
36321         if(h !== null && h > 0){
36322             this.el.setHeight(h);
36323             h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
36324             h -= this.el.getBorderWidth("tb");
36325             if(this.config.adjustments){
36326                 h += this.config.adjustments[1];
36327             }
36328             this.bodyEl.setHeight(h);
36329             if(this.tabs){
36330                 h = this.tabs.syncHeight(h);
36331             }
36332         }
36333         if(this.panelSize){
36334             w = w !== null ? w : this.panelSize.width;
36335             h = h !== null ? h : this.panelSize.height;
36336         }
36337         if(this.activePanel){
36338             var el = this.activePanel.getEl();
36339             w = w !== null ? w : el.getWidth();
36340             h = h !== null ? h : el.getHeight();
36341             this.panelSize = {width: w, height: h};
36342             this.activePanel.setSize(w, h);
36343         }
36344         if(Roo.isIE && this.tabs){
36345             this.tabs.el.repaint();
36346         }
36347     },
36348
36349     /**
36350      * Returns the container element for this region.
36351      * @return {Roo.Element}
36352      */
36353     getEl : function(){
36354         return this.el;
36355     },
36356
36357     /**
36358      * Hides this region.
36359      */
36360     hide : function(){
36361         //if(!this.collapsed){
36362             this.el.dom.style.left = "-2000px";
36363             this.el.hide();
36364         //}else{
36365          //   this.collapsedEl.dom.style.left = "-2000px";
36366          //   this.collapsedEl.hide();
36367        // }
36368         this.visible = false;
36369         this.fireEvent("visibilitychange", this, false);
36370     },
36371
36372     /**
36373      * Shows this region if it was previously hidden.
36374      */
36375     show : function(){
36376         //if(!this.collapsed){
36377             this.el.show();
36378         //}else{
36379         //    this.collapsedEl.show();
36380        // }
36381         this.visible = true;
36382         this.fireEvent("visibilitychange", this, true);
36383     },
36384 /*
36385     closeClicked : function(){
36386         if(this.activePanel){
36387             this.remove(this.activePanel);
36388         }
36389     },
36390
36391     collapseClick : function(e){
36392         if(this.isSlid){
36393            e.stopPropagation();
36394            this.slideIn();
36395         }else{
36396            e.stopPropagation();
36397            this.slideOut();
36398         }
36399     },
36400 */
36401     /**
36402      * Collapses this region.
36403      * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
36404      */
36405     /*
36406     collapse : function(skipAnim, skipCheck = false){
36407         if(this.collapsed) {
36408             return;
36409         }
36410         
36411         if(skipCheck || this.fireEvent("beforecollapse", this) != false){
36412             
36413             this.collapsed = true;
36414             if(this.split){
36415                 this.split.el.hide();
36416             }
36417             if(this.config.animate && skipAnim !== true){
36418                 this.fireEvent("invalidated", this);
36419                 this.animateCollapse();
36420             }else{
36421                 this.el.setLocation(-20000,-20000);
36422                 this.el.hide();
36423                 this.collapsedEl.show();
36424                 this.fireEvent("collapsed", this);
36425                 this.fireEvent("invalidated", this);
36426             }
36427         }
36428         
36429     },
36430 */
36431     animateCollapse : function(){
36432         // overridden
36433     },
36434
36435     /**
36436      * Expands this region if it was previously collapsed.
36437      * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
36438      * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
36439      */
36440     /*
36441     expand : function(e, skipAnim){
36442         if(e) {
36443             e.stopPropagation();
36444         }
36445         if(!this.collapsed || this.el.hasActiveFx()) {
36446             return;
36447         }
36448         if(this.isSlid){
36449             this.afterSlideIn();
36450             skipAnim = true;
36451         }
36452         this.collapsed = false;
36453         if(this.config.animate && skipAnim !== true){
36454             this.animateExpand();
36455         }else{
36456             this.el.show();
36457             if(this.split){
36458                 this.split.el.show();
36459             }
36460             this.collapsedEl.setLocation(-2000,-2000);
36461             this.collapsedEl.hide();
36462             this.fireEvent("invalidated", this);
36463             this.fireEvent("expanded", this);
36464         }
36465     },
36466 */
36467     animateExpand : function(){
36468         // overridden
36469     },
36470
36471     initTabs : function()
36472     {
36473         //this.bodyEl.setStyle("overflow", "hidden"); -- this is set in render?
36474         
36475         var ts = new Roo.bootstrap.panel.Tabs({
36476             el: this.bodyEl.dom,
36477             region : this,
36478             tabPosition: this.tabPosition ? this.tabPosition  : 'top',
36479             disableTooltips: this.config.disableTabTips,
36480             toolbar : this.config.toolbar
36481         });
36482         
36483         if(this.config.hideTabs){
36484             ts.stripWrap.setDisplayed(false);
36485         }
36486         this.tabs = ts;
36487         ts.resizeTabs = this.config.resizeTabs === true;
36488         ts.minTabWidth = this.config.minTabWidth || 40;
36489         ts.maxTabWidth = this.config.maxTabWidth || 250;
36490         ts.preferredTabWidth = this.config.preferredTabWidth || 150;
36491         ts.monitorResize = false;
36492         //ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden"); // this is set in render?
36493         ts.bodyEl.addClass('roo-layout-tabs-body');
36494         this.panels.each(this.initPanelAsTab, this);
36495     },
36496
36497     initPanelAsTab : function(panel){
36498         var ti = this.tabs.addTab(
36499             panel.getEl().id,
36500             panel.getTitle(),
36501             null,
36502             this.config.closeOnTab && panel.isClosable(),
36503             panel.tpl
36504         );
36505         if(panel.tabTip !== undefined){
36506             ti.setTooltip(panel.tabTip);
36507         }
36508         ti.on("activate", function(){
36509               this.setActivePanel(panel);
36510         }, this);
36511         
36512         if(this.config.closeOnTab){
36513             ti.on("beforeclose", function(t, e){
36514                 e.cancel = true;
36515                 this.remove(panel);
36516             }, this);
36517         }
36518         
36519         panel.tabItem = ti;
36520         
36521         return ti;
36522     },
36523
36524     updatePanelTitle : function(panel, title)
36525     {
36526         if(this.activePanel == panel){
36527             this.updateTitle(title);
36528         }
36529         if(this.tabs){
36530             var ti = this.tabs.getTab(panel.getEl().id);
36531             ti.setText(title);
36532             if(panel.tabTip !== undefined){
36533                 ti.setTooltip(panel.tabTip);
36534             }
36535         }
36536     },
36537
36538     updateTitle : function(title){
36539         if(this.titleTextEl && !this.config.title){
36540             this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : "&#160;");
36541         }
36542     },
36543
36544     setActivePanel : function(panel)
36545     {
36546         panel = this.getPanel(panel);
36547         if(this.activePanel && this.activePanel != panel){
36548             if(this.activePanel.setActiveState(false) === false){
36549                 return;
36550             }
36551         }
36552         this.activePanel = panel;
36553         panel.setActiveState(true);
36554         if(this.panelSize){
36555             panel.setSize(this.panelSize.width, this.panelSize.height);
36556         }
36557         if(this.closeBtn){
36558             this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
36559         }
36560         this.updateTitle(panel.getTitle());
36561         if(this.tabs){
36562             this.fireEvent("invalidated", this);
36563         }
36564         this.fireEvent("panelactivated", this, panel);
36565     },
36566
36567     /**
36568      * Shows the specified panel.
36569      * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
36570      * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
36571      */
36572     showPanel : function(panel)
36573     {
36574         panel = this.getPanel(panel);
36575         if(panel){
36576             if(this.tabs){
36577                 var tab = this.tabs.getTab(panel.getEl().id);
36578                 if(tab.isHidden()){
36579                     this.tabs.unhideTab(tab.id);
36580                 }
36581                 tab.activate();
36582             }else{
36583                 this.setActivePanel(panel);
36584             }
36585         }
36586         return panel;
36587     },
36588
36589     /**
36590      * Get the active panel for this region.
36591      * @return {Roo.ContentPanel} The active panel or null
36592      */
36593     getActivePanel : function(){
36594         return this.activePanel;
36595     },
36596
36597     validateVisibility : function(){
36598         if(this.panels.getCount() < 1){
36599             this.updateTitle("&#160;");
36600             this.closeBtn.hide();
36601             this.hide();
36602         }else{
36603             if(!this.isVisible()){
36604                 this.show();
36605             }
36606         }
36607     },
36608
36609     /**
36610      * Adds the passed ContentPanel(s) to this region.
36611      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
36612      * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
36613      */
36614     add : function(panel)
36615     {
36616         if(arguments.length > 1){
36617             for(var i = 0, len = arguments.length; i < len; i++) {
36618                 this.add(arguments[i]);
36619             }
36620             return null;
36621         }
36622         
36623         // if we have not been rendered yet, then we can not really do much of this..
36624         if (!this.bodyEl) {
36625             this.unrendered_panels.push(panel);
36626             return panel;
36627         }
36628         
36629         
36630         
36631         
36632         if(this.hasPanel(panel)){
36633             this.showPanel(panel);
36634             return panel;
36635         }
36636         panel.setRegion(this);
36637         this.panels.add(panel);
36638        /* if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
36639             // sinle panel - no tab...?? would it not be better to render it with the tabs,
36640             // and hide them... ???
36641             this.bodyEl.dom.appendChild(panel.getEl().dom);
36642             if(panel.background !== true){
36643                 this.setActivePanel(panel);
36644             }
36645             this.fireEvent("paneladded", this, panel);
36646             return panel;
36647         }
36648         */
36649         if(!this.tabs){
36650             this.initTabs();
36651         }else{
36652             this.initPanelAsTab(panel);
36653         }
36654         
36655         
36656         if(panel.background !== true){
36657             this.tabs.activate(panel.getEl().id);
36658         }
36659         this.fireEvent("paneladded", this, panel);
36660         return panel;
36661     },
36662
36663     /**
36664      * Hides the tab for the specified panel.
36665      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
36666      */
36667     hidePanel : function(panel){
36668         if(this.tabs && (panel = this.getPanel(panel))){
36669             this.tabs.hideTab(panel.getEl().id);
36670         }
36671     },
36672
36673     /**
36674      * Unhides the tab for a previously hidden panel.
36675      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
36676      */
36677     unhidePanel : function(panel){
36678         if(this.tabs && (panel = this.getPanel(panel))){
36679             this.tabs.unhideTab(panel.getEl().id);
36680         }
36681     },
36682
36683     clearPanels : function(){
36684         while(this.panels.getCount() > 0){
36685              this.remove(this.panels.first());
36686         }
36687     },
36688
36689     /**
36690      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
36691      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
36692      * @param {Boolean} preservePanel Overrides the config preservePanel option
36693      * @return {Roo.ContentPanel} The panel that was removed
36694      */
36695     remove : function(panel, preservePanel)
36696     {
36697         panel = this.getPanel(panel);
36698         if(!panel){
36699             return null;
36700         }
36701         var e = {};
36702         this.fireEvent("beforeremove", this, panel, e);
36703         if(e.cancel === true){
36704             return null;
36705         }
36706         preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
36707         var panelId = panel.getId();
36708         this.panels.removeKey(panelId);
36709         if(preservePanel){
36710             document.body.appendChild(panel.getEl().dom);
36711         }
36712         if(this.tabs){
36713             this.tabs.removeTab(panel.getEl().id);
36714         }else if (!preservePanel){
36715             this.bodyEl.dom.removeChild(panel.getEl().dom);
36716         }
36717         if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
36718             var p = this.panels.first();
36719             var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
36720             tempEl.appendChild(p.getEl().dom);
36721             this.bodyEl.update("");
36722             this.bodyEl.dom.appendChild(p.getEl().dom);
36723             tempEl = null;
36724             this.updateTitle(p.getTitle());
36725             this.tabs = null;
36726             this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
36727             this.setActivePanel(p);
36728         }
36729         panel.setRegion(null);
36730         if(this.activePanel == panel){
36731             this.activePanel = null;
36732         }
36733         if(this.config.autoDestroy !== false && preservePanel !== true){
36734             try{panel.destroy();}catch(e){}
36735         }
36736         this.fireEvent("panelremoved", this, panel);
36737         return panel;
36738     },
36739
36740     /**
36741      * Returns the TabPanel component used by this region
36742      * @return {Roo.TabPanel}
36743      */
36744     getTabs : function(){
36745         return this.tabs;
36746     },
36747
36748     createTool : function(parentEl, className){
36749         var btn = Roo.DomHelper.append(parentEl, {
36750             tag: "div",
36751             cls: "x-layout-tools-button",
36752             children: [ {
36753                 tag: "div",
36754                 cls: "roo-layout-tools-button-inner " + className,
36755                 html: "&#160;"
36756             }]
36757         }, true);
36758         btn.addClassOnOver("roo-layout-tools-button-over");
36759         return btn;
36760     }
36761 });/*
36762  * Based on:
36763  * Ext JS Library 1.1.1
36764  * Copyright(c) 2006-2007, Ext JS, LLC.
36765  *
36766  * Originally Released Under LGPL - original licence link has changed is not relivant.
36767  *
36768  * Fork - LGPL
36769  * <script type="text/javascript">
36770  */
36771  
36772
36773
36774 /**
36775  * @class Roo.SplitLayoutRegion
36776  * @extends Roo.LayoutRegion
36777  * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
36778  */
36779 Roo.bootstrap.layout.Split = function(config){
36780     this.cursor = config.cursor;
36781     Roo.bootstrap.layout.Split.superclass.constructor.call(this, config);
36782 };
36783
36784 Roo.extend(Roo.bootstrap.layout.Split, Roo.bootstrap.layout.Region,
36785 {
36786     splitTip : "Drag to resize.",
36787     collapsibleSplitTip : "Drag to resize. Double click to hide.",
36788     useSplitTips : false,
36789
36790     applyConfig : function(config){
36791         Roo.bootstrap.layout.Split.superclass.applyConfig.call(this, config);
36792     },
36793     
36794     onRender : function(ctr,pos) {
36795         
36796         Roo.bootstrap.layout.Split.superclass.onRender.call(this, ctr,pos);
36797         if(!this.config.split){
36798             return;
36799         }
36800         if(!this.split){
36801             
36802             var splitEl = Roo.DomHelper.append(ctr.dom,  {
36803                             tag: "div",
36804                             id: this.el.id + "-split",
36805                             cls: "roo-layout-split roo-layout-split-"+this.position,
36806                             html: "&#160;"
36807             });
36808             /** The SplitBar for this region 
36809             * @type Roo.SplitBar */
36810             // does not exist yet...
36811             Roo.log([this.position, this.orientation]);
36812             
36813             this.split = new Roo.bootstrap.SplitBar({
36814                 dragElement : splitEl,
36815                 resizingElement: this.el,
36816                 orientation : this.orientation
36817             });
36818             
36819             this.split.on("moved", this.onSplitMove, this);
36820             this.split.useShim = this.config.useShim === true;
36821             this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
36822             if(this.useSplitTips){
36823                 this.split.el.dom.title = this.config.collapsible ? this.collapsibleSplitTip : this.splitTip;
36824             }
36825             //if(config.collapsible){
36826             //    this.split.el.on("dblclick", this.collapse,  this);
36827             //}
36828         }
36829         if(typeof this.config.minSize != "undefined"){
36830             this.split.minSize = this.config.minSize;
36831         }
36832         if(typeof this.config.maxSize != "undefined"){
36833             this.split.maxSize = this.config.maxSize;
36834         }
36835         if(this.config.hideWhenEmpty || this.config.hidden || this.config.collapsed){
36836             this.hideSplitter();
36837         }
36838         
36839     },
36840
36841     getHMaxSize : function(){
36842          var cmax = this.config.maxSize || 10000;
36843          var center = this.mgr.getRegion("center");
36844          return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
36845     },
36846
36847     getVMaxSize : function(){
36848          var cmax = this.config.maxSize || 10000;
36849          var center = this.mgr.getRegion("center");
36850          return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
36851     },
36852
36853     onSplitMove : function(split, newSize){
36854         this.fireEvent("resized", this, newSize);
36855     },
36856     
36857     /** 
36858      * Returns the {@link Roo.SplitBar} for this region.
36859      * @return {Roo.SplitBar}
36860      */
36861     getSplitBar : function(){
36862         return this.split;
36863     },
36864     
36865     hide : function(){
36866         this.hideSplitter();
36867         Roo.bootstrap.layout.Split.superclass.hide.call(this);
36868     },
36869
36870     hideSplitter : function(){
36871         if(this.split){
36872             this.split.el.setLocation(-2000,-2000);
36873             this.split.el.hide();
36874         }
36875     },
36876
36877     show : function(){
36878         if(this.split){
36879             this.split.el.show();
36880         }
36881         Roo.bootstrap.layout.Split.superclass.show.call(this);
36882     },
36883     
36884     beforeSlide: function(){
36885         if(Roo.isGecko){// firefox overflow auto bug workaround
36886             this.bodyEl.clip();
36887             if(this.tabs) {
36888                 this.tabs.bodyEl.clip();
36889             }
36890             if(this.activePanel){
36891                 this.activePanel.getEl().clip();
36892                 
36893                 if(this.activePanel.beforeSlide){
36894                     this.activePanel.beforeSlide();
36895                 }
36896             }
36897         }
36898     },
36899     
36900     afterSlide : function(){
36901         if(Roo.isGecko){// firefox overflow auto bug workaround
36902             this.bodyEl.unclip();
36903             if(this.tabs) {
36904                 this.tabs.bodyEl.unclip();
36905             }
36906             if(this.activePanel){
36907                 this.activePanel.getEl().unclip();
36908                 if(this.activePanel.afterSlide){
36909                     this.activePanel.afterSlide();
36910                 }
36911             }
36912         }
36913     },
36914
36915     initAutoHide : function(){
36916         if(this.autoHide !== false){
36917             if(!this.autoHideHd){
36918                 var st = new Roo.util.DelayedTask(this.slideIn, this);
36919                 this.autoHideHd = {
36920                     "mouseout": function(e){
36921                         if(!e.within(this.el, true)){
36922                             st.delay(500);
36923                         }
36924                     },
36925                     "mouseover" : function(e){
36926                         st.cancel();
36927                     },
36928                     scope : this
36929                 };
36930             }
36931             this.el.on(this.autoHideHd);
36932         }
36933     },
36934
36935     clearAutoHide : function(){
36936         if(this.autoHide !== false){
36937             this.el.un("mouseout", this.autoHideHd.mouseout);
36938             this.el.un("mouseover", this.autoHideHd.mouseover);
36939         }
36940     },
36941
36942     clearMonitor : function(){
36943         Roo.get(document).un("click", this.slideInIf, this);
36944     },
36945
36946     // these names are backwards but not changed for compat
36947     slideOut : function(){
36948         if(this.isSlid || this.el.hasActiveFx()){
36949             return;
36950         }
36951         this.isSlid = true;
36952         if(this.collapseBtn){
36953             this.collapseBtn.hide();
36954         }
36955         this.closeBtnState = this.closeBtn.getStyle('display');
36956         this.closeBtn.hide();
36957         if(this.stickBtn){
36958             this.stickBtn.show();
36959         }
36960         this.el.show();
36961         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
36962         this.beforeSlide();
36963         this.el.setStyle("z-index", 10001);
36964         this.el.slideIn(this.getSlideAnchor(), {
36965             callback: function(){
36966                 this.afterSlide();
36967                 this.initAutoHide();
36968                 Roo.get(document).on("click", this.slideInIf, this);
36969                 this.fireEvent("slideshow", this);
36970             },
36971             scope: this,
36972             block: true
36973         });
36974     },
36975
36976     afterSlideIn : function(){
36977         this.clearAutoHide();
36978         this.isSlid = false;
36979         this.clearMonitor();
36980         this.el.setStyle("z-index", "");
36981         if(this.collapseBtn){
36982             this.collapseBtn.show();
36983         }
36984         this.closeBtn.setStyle('display', this.closeBtnState);
36985         if(this.stickBtn){
36986             this.stickBtn.hide();
36987         }
36988         this.fireEvent("slidehide", this);
36989     },
36990
36991     slideIn : function(cb){
36992         if(!this.isSlid || this.el.hasActiveFx()){
36993             Roo.callback(cb);
36994             return;
36995         }
36996         this.isSlid = false;
36997         this.beforeSlide();
36998         this.el.slideOut(this.getSlideAnchor(), {
36999             callback: function(){
37000                 this.el.setLeftTop(-10000, -10000);
37001                 this.afterSlide();
37002                 this.afterSlideIn();
37003                 Roo.callback(cb);
37004             },
37005             scope: this,
37006             block: true
37007         });
37008     },
37009     
37010     slideInIf : function(e){
37011         if(!e.within(this.el)){
37012             this.slideIn();
37013         }
37014     },
37015
37016     animateCollapse : function(){
37017         this.beforeSlide();
37018         this.el.setStyle("z-index", 20000);
37019         var anchor = this.getSlideAnchor();
37020         this.el.slideOut(anchor, {
37021             callback : function(){
37022                 this.el.setStyle("z-index", "");
37023                 this.collapsedEl.slideIn(anchor, {duration:.3});
37024                 this.afterSlide();
37025                 this.el.setLocation(-10000,-10000);
37026                 this.el.hide();
37027                 this.fireEvent("collapsed", this);
37028             },
37029             scope: this,
37030             block: true
37031         });
37032     },
37033
37034     animateExpand : function(){
37035         this.beforeSlide();
37036         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
37037         this.el.setStyle("z-index", 20000);
37038         this.collapsedEl.hide({
37039             duration:.1
37040         });
37041         this.el.slideIn(this.getSlideAnchor(), {
37042             callback : function(){
37043                 this.el.setStyle("z-index", "");
37044                 this.afterSlide();
37045                 if(this.split){
37046                     this.split.el.show();
37047                 }
37048                 this.fireEvent("invalidated", this);
37049                 this.fireEvent("expanded", this);
37050             },
37051             scope: this,
37052             block: true
37053         });
37054     },
37055
37056     anchors : {
37057         "west" : "left",
37058         "east" : "right",
37059         "north" : "top",
37060         "south" : "bottom"
37061     },
37062
37063     sanchors : {
37064         "west" : "l",
37065         "east" : "r",
37066         "north" : "t",
37067         "south" : "b"
37068     },
37069
37070     canchors : {
37071         "west" : "tl-tr",
37072         "east" : "tr-tl",
37073         "north" : "tl-bl",
37074         "south" : "bl-tl"
37075     },
37076
37077     getAnchor : function(){
37078         return this.anchors[this.position];
37079     },
37080
37081     getCollapseAnchor : function(){
37082         return this.canchors[this.position];
37083     },
37084
37085     getSlideAnchor : function(){
37086         return this.sanchors[this.position];
37087     },
37088
37089     getAlignAdj : function(){
37090         var cm = this.cmargins;
37091         switch(this.position){
37092             case "west":
37093                 return [0, 0];
37094             break;
37095             case "east":
37096                 return [0, 0];
37097             break;
37098             case "north":
37099                 return [0, 0];
37100             break;
37101             case "south":
37102                 return [0, 0];
37103             break;
37104         }
37105     },
37106
37107     getExpandAdj : function(){
37108         var c = this.collapsedEl, cm = this.cmargins;
37109         switch(this.position){
37110             case "west":
37111                 return [-(cm.right+c.getWidth()+cm.left), 0];
37112             break;
37113             case "east":
37114                 return [cm.right+c.getWidth()+cm.left, 0];
37115             break;
37116             case "north":
37117                 return [0, -(cm.top+cm.bottom+c.getHeight())];
37118             break;
37119             case "south":
37120                 return [0, cm.top+cm.bottom+c.getHeight()];
37121             break;
37122         }
37123     }
37124 });/*
37125  * Based on:
37126  * Ext JS Library 1.1.1
37127  * Copyright(c) 2006-2007, Ext JS, LLC.
37128  *
37129  * Originally Released Under LGPL - original licence link has changed is not relivant.
37130  *
37131  * Fork - LGPL
37132  * <script type="text/javascript">
37133  */
37134 /*
37135  * These classes are private internal classes
37136  */
37137 Roo.bootstrap.layout.Center = function(config){
37138     config.region = "center";
37139     Roo.bootstrap.layout.Region.call(this, config);
37140     this.visible = true;
37141     this.minWidth = config.minWidth || 20;
37142     this.minHeight = config.minHeight || 20;
37143 };
37144
37145 Roo.extend(Roo.bootstrap.layout.Center, Roo.bootstrap.layout.Region, {
37146     hide : function(){
37147         // center panel can't be hidden
37148     },
37149     
37150     show : function(){
37151         // center panel can't be hidden
37152     },
37153     
37154     getMinWidth: function(){
37155         return this.minWidth;
37156     },
37157     
37158     getMinHeight: function(){
37159         return this.minHeight;
37160     }
37161 });
37162
37163
37164
37165
37166  
37167
37168
37169
37170
37171
37172
37173 Roo.bootstrap.layout.North = function(config)
37174 {
37175     config.region = 'north';
37176     config.cursor = 'n-resize';
37177     
37178     Roo.bootstrap.layout.Split.call(this, config);
37179     
37180     
37181     if(this.split){
37182         this.split.placement = Roo.bootstrap.SplitBar.TOP;
37183         this.split.orientation = Roo.bootstrap.SplitBar.VERTICAL;
37184         this.split.el.addClass("roo-layout-split-v");
37185     }
37186     var size = config.initialSize || config.height;
37187     if(typeof size != "undefined"){
37188         this.el.setHeight(size);
37189     }
37190 };
37191 Roo.extend(Roo.bootstrap.layout.North, Roo.bootstrap.layout.Split,
37192 {
37193     orientation: Roo.bootstrap.SplitBar.VERTICAL,
37194     
37195     
37196     
37197     getBox : function(){
37198         if(this.collapsed){
37199             return this.collapsedEl.getBox();
37200         }
37201         var box = this.el.getBox();
37202         if(this.split){
37203             box.height += this.split.el.getHeight();
37204         }
37205         return box;
37206     },
37207     
37208     updateBox : function(box){
37209         if(this.split && !this.collapsed){
37210             box.height -= this.split.el.getHeight();
37211             this.split.el.setLeft(box.x);
37212             this.split.el.setTop(box.y+box.height);
37213             this.split.el.setWidth(box.width);
37214         }
37215         if(this.collapsed){
37216             this.updateBody(box.width, null);
37217         }
37218         Roo.bootstrap.layout.Region.prototype.updateBox.call(this, box);
37219     }
37220 });
37221
37222
37223
37224
37225
37226 Roo.bootstrap.layout.South = function(config){
37227     config.region = 'south';
37228     config.cursor = 's-resize';
37229     Roo.bootstrap.layout.Split.call(this, config);
37230     if(this.split){
37231         this.split.placement = Roo.bootstrap.SplitBar.BOTTOM;
37232         this.split.orientation = Roo.bootstrap.SplitBar.VERTICAL;
37233         this.split.el.addClass("roo-layout-split-v");
37234     }
37235     var size = config.initialSize || config.height;
37236     if(typeof size != "undefined"){
37237         this.el.setHeight(size);
37238     }
37239 };
37240
37241 Roo.extend(Roo.bootstrap.layout.South, Roo.bootstrap.layout.Split, {
37242     orientation: Roo.bootstrap.SplitBar.VERTICAL,
37243     getBox : function(){
37244         if(this.collapsed){
37245             return this.collapsedEl.getBox();
37246         }
37247         var box = this.el.getBox();
37248         if(this.split){
37249             var sh = this.split.el.getHeight();
37250             box.height += sh;
37251             box.y -= sh;
37252         }
37253         return box;
37254     },
37255     
37256     updateBox : function(box){
37257         if(this.split && !this.collapsed){
37258             var sh = this.split.el.getHeight();
37259             box.height -= sh;
37260             box.y += sh;
37261             this.split.el.setLeft(box.x);
37262             this.split.el.setTop(box.y-sh);
37263             this.split.el.setWidth(box.width);
37264         }
37265         if(this.collapsed){
37266             this.updateBody(box.width, null);
37267         }
37268         Roo.bootstrap.layout.Region.prototype.updateBox.call(this, box);
37269     }
37270 });
37271
37272 Roo.bootstrap.layout.East = function(config){
37273     config.region = "east";
37274     config.cursor = "e-resize";
37275     Roo.bootstrap.layout.Split.call(this, config);
37276     if(this.split){
37277         this.split.placement = Roo.bootstrap.SplitBar.RIGHT;
37278         this.split.orientation = Roo.bootstrap.SplitBar.HORIZONTAL;
37279         this.split.el.addClass("roo-layout-split-h");
37280     }
37281     var size = config.initialSize || config.width;
37282     if(typeof size != "undefined"){
37283         this.el.setWidth(size);
37284     }
37285 };
37286 Roo.extend(Roo.bootstrap.layout.East, Roo.bootstrap.layout.Split, {
37287     orientation: Roo.bootstrap.SplitBar.HORIZONTAL,
37288     getBox : function(){
37289         if(this.collapsed){
37290             return this.collapsedEl.getBox();
37291         }
37292         var box = this.el.getBox();
37293         if(this.split){
37294             var sw = this.split.el.getWidth();
37295             box.width += sw;
37296             box.x -= sw;
37297         }
37298         return box;
37299     },
37300
37301     updateBox : function(box){
37302         if(this.split && !this.collapsed){
37303             var sw = this.split.el.getWidth();
37304             box.width -= sw;
37305             this.split.el.setLeft(box.x);
37306             this.split.el.setTop(box.y);
37307             this.split.el.setHeight(box.height);
37308             box.x += sw;
37309         }
37310         if(this.collapsed){
37311             this.updateBody(null, box.height);
37312         }
37313         Roo.bootstrap.layout.Region.prototype.updateBox.call(this, box);
37314     }
37315 });
37316
37317 Roo.bootstrap.layout.West = function(config){
37318     config.region = "west";
37319     config.cursor = "w-resize";
37320     
37321     Roo.bootstrap.layout.Split.call(this, config);
37322     if(this.split){
37323         this.split.placement = Roo.bootstrap.SplitBar.LEFT;
37324         this.split.orientation = Roo.bootstrap.SplitBar.HORIZONTAL;
37325         this.split.el.addClass("roo-layout-split-h");
37326     }
37327     
37328 };
37329 Roo.extend(Roo.bootstrap.layout.West, Roo.bootstrap.layout.Split, {
37330     orientation: Roo.bootstrap.SplitBar.HORIZONTAL,
37331     
37332     onRender: function(ctr, pos)
37333     {
37334         Roo.bootstrap.layout.West.superclass.onRender.call(this, ctr,pos);
37335         var size = this.config.initialSize || this.config.width;
37336         if(typeof size != "undefined"){
37337             this.el.setWidth(size);
37338         }
37339     },
37340     
37341     getBox : function(){
37342         if(this.collapsed){
37343             return this.collapsedEl.getBox();
37344         }
37345         var box = this.el.getBox();
37346         if(this.split){
37347             box.width += this.split.el.getWidth();
37348         }
37349         return box;
37350     },
37351     
37352     updateBox : function(box){
37353         if(this.split && !this.collapsed){
37354             var sw = this.split.el.getWidth();
37355             box.width -= sw;
37356             this.split.el.setLeft(box.x+box.width);
37357             this.split.el.setTop(box.y);
37358             this.split.el.setHeight(box.height);
37359         }
37360         if(this.collapsed){
37361             this.updateBody(null, box.height);
37362         }
37363         Roo.bootstrap.layout.Region.prototype.updateBox.call(this, box);
37364     }
37365 });Roo.namespace("Roo.bootstrap.panel");/*
37366  * Based on:
37367  * Ext JS Library 1.1.1
37368  * Copyright(c) 2006-2007, Ext JS, LLC.
37369  *
37370  * Originally Released Under LGPL - original licence link has changed is not relivant.
37371  *
37372  * Fork - LGPL
37373  * <script type="text/javascript">
37374  */
37375 /**
37376  * @class Roo.ContentPanel
37377  * @extends Roo.util.Observable
37378  * A basic ContentPanel element.
37379  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
37380  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
37381  * @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
37382  * @cfg {Boolean}   closable      True if the panel can be closed/removed
37383  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
37384  * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
37385  * @cfg {Toolbar}   toolbar       A toolbar for this panel
37386  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
37387  * @cfg {String} title          The title for this panel
37388  * @cfg {Array} adjustments     Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
37389  * @cfg {String} url            Calls {@link #setUrl} with this value
37390  * @cfg {String} region         (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
37391  * @cfg {String/Object} params  When used with {@link #url}, calls {@link #setUrl} with this value
37392  * @cfg {Boolean} loadOnce      When used with {@link #url}, calls {@link #setUrl} with this value
37393  * @cfg {String}    content        Raw content to fill content panel with (uses setContent on construction.)
37394  * @cfg {Boolean} badges render the badges
37395
37396  * @constructor
37397  * Create a new ContentPanel.
37398  * @param {String/HTMLElement/Roo.Element} el The container element for this panel
37399  * @param {String/Object} config A string to set only the title or a config object
37400  * @param {String} content (optional) Set the HTML content for this panel
37401  * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
37402  */
37403 Roo.bootstrap.panel.Content = function( config){
37404     
37405     this.tpl = config.tpl || false;
37406     
37407     var el = config.el;
37408     var content = config.content;
37409
37410     if(config.autoCreate){ // xtype is available if this is called from factory
37411         el = Roo.id();
37412     }
37413     this.el = Roo.get(el);
37414     if(!this.el && config && config.autoCreate){
37415         if(typeof config.autoCreate == "object"){
37416             if(!config.autoCreate.id){
37417                 config.autoCreate.id = config.id||el;
37418             }
37419             this.el = Roo.DomHelper.append(document.body,
37420                         config.autoCreate, true);
37421         }else{
37422             var elcfg =  {   tag: "div",
37423                             cls: "roo-layout-inactive-content",
37424                             id: config.id||el
37425                             };
37426             if (config.html) {
37427                 elcfg.html = config.html;
37428                 
37429             }
37430                         
37431             this.el = Roo.DomHelper.append(document.body, elcfg , true);
37432         }
37433     } 
37434     this.closable = false;
37435     this.loaded = false;
37436     this.active = false;
37437    
37438       
37439     if (config.toolbar && !config.toolbar.el && config.toolbar.xtype) {
37440         
37441         this.toolbar = new config.toolbar.xns[config.toolbar.xtype](config.toolbar);
37442         
37443         this.wrapEl = this.el; //this.el.wrap();
37444         var ti = [];
37445         if (config.toolbar.items) {
37446             ti = config.toolbar.items ;
37447             delete config.toolbar.items ;
37448         }
37449         
37450         var nitems = [];
37451         this.toolbar.render(this.wrapEl, 'before');
37452         for(var i =0;i < ti.length;i++) {
37453           //  Roo.log(['add child', items[i]]);
37454             nitems.push(this.toolbar.addxtype(Roo.apply({}, ti[i])));
37455         }
37456         this.toolbar.items = nitems;
37457         this.toolbar.el.insertBefore(this.wrapEl.dom.firstChild);
37458         delete config.toolbar;
37459         
37460     }
37461     /*
37462     // xtype created footer. - not sure if will work as we normally have to render first..
37463     if (this.footer && !this.footer.el && this.footer.xtype) {
37464         if (!this.wrapEl) {
37465             this.wrapEl = this.el.wrap();
37466         }
37467     
37468         this.footer.container = this.wrapEl.createChild();
37469          
37470         this.footer = Roo.factory(this.footer, Roo);
37471         
37472     }
37473     */
37474     
37475      if(typeof config == "string"){
37476         this.title = config;
37477     }else{
37478         Roo.apply(this, config);
37479     }
37480     
37481     if(this.resizeEl){
37482         this.resizeEl = Roo.get(this.resizeEl, true);
37483     }else{
37484         this.resizeEl = this.el;
37485     }
37486     // handle view.xtype
37487     
37488  
37489     
37490     
37491     this.addEvents({
37492         /**
37493          * @event activate
37494          * Fires when this panel is activated. 
37495          * @param {Roo.ContentPanel} this
37496          */
37497         "activate" : true,
37498         /**
37499          * @event deactivate
37500          * Fires when this panel is activated. 
37501          * @param {Roo.ContentPanel} this
37502          */
37503         "deactivate" : true,
37504
37505         /**
37506          * @event resize
37507          * Fires when this panel is resized if fitToFrame is true.
37508          * @param {Roo.ContentPanel} this
37509          * @param {Number} width The width after any component adjustments
37510          * @param {Number} height The height after any component adjustments
37511          */
37512         "resize" : true,
37513         
37514          /**
37515          * @event render
37516          * Fires when this tab is created
37517          * @param {Roo.ContentPanel} this
37518          */
37519         "render" : true
37520         
37521         
37522         
37523     });
37524     
37525
37526     
37527     
37528     if(this.autoScroll){
37529         this.resizeEl.setStyle("overflow", "auto");
37530     } else {
37531         // fix randome scrolling
37532         //this.el.on('scroll', function() {
37533         //    Roo.log('fix random scolling');
37534         //    this.scrollTo('top',0); 
37535         //});
37536     }
37537     content = content || this.content;
37538     if(content){
37539         this.setContent(content);
37540     }
37541     if(config && config.url){
37542         this.setUrl(this.url, this.params, this.loadOnce);
37543     }
37544     
37545     
37546     
37547     Roo.bootstrap.panel.Content.superclass.constructor.call(this);
37548     
37549     if (this.view && typeof(this.view.xtype) != 'undefined') {
37550         this.view.el = this.el.appendChild(document.createElement("div"));
37551         this.view = Roo.factory(this.view); 
37552         this.view.render  &&  this.view.render(false, '');  
37553     }
37554     
37555     
37556     this.fireEvent('render', this);
37557 };
37558
37559 Roo.extend(Roo.bootstrap.panel.Content, Roo.bootstrap.Component, {
37560     
37561     tabTip : '',
37562     
37563     setRegion : function(region){
37564         this.region = region;
37565         this.setActiveClass(region && !this.background);
37566     },
37567     
37568     
37569     setActiveClass: function(state)
37570     {
37571         if(state){
37572            this.el.replaceClass("roo-layout-inactive-content", "roo-layout-active-content");
37573            this.el.setStyle('position','relative');
37574         }else{
37575            this.el.replaceClass("roo-layout-active-content", "roo-layout-inactive-content");
37576            this.el.setStyle('position', 'absolute');
37577         } 
37578     },
37579     
37580     /**
37581      * Returns the toolbar for this Panel if one was configured. 
37582      * @return {Roo.Toolbar} 
37583      */
37584     getToolbar : function(){
37585         return this.toolbar;
37586     },
37587     
37588     setActiveState : function(active)
37589     {
37590         this.active = active;
37591         this.setActiveClass(active);
37592         if(!active){
37593             if(this.fireEvent("deactivate", this) === false){
37594                 return false;
37595             }
37596             return true;
37597         }
37598         this.fireEvent("activate", this);
37599         return true;
37600     },
37601     /**
37602      * Updates this panel's element
37603      * @param {String} content The new content
37604      * @param {Boolean} loadScripts (optional) true to look for and process scripts
37605     */
37606     setContent : function(content, loadScripts){
37607         this.el.update(content, loadScripts);
37608     },
37609
37610     ignoreResize : function(w, h){
37611         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
37612             return true;
37613         }else{
37614             this.lastSize = {width: w, height: h};
37615             return false;
37616         }
37617     },
37618     /**
37619      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
37620      * @return {Roo.UpdateManager} The UpdateManager
37621      */
37622     getUpdateManager : function(){
37623         return this.el.getUpdateManager();
37624     },
37625      /**
37626      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
37627      * @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:
37628 <pre><code>
37629 panel.load({
37630     url: "your-url.php",
37631     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
37632     callback: yourFunction,
37633     scope: yourObject, //(optional scope)
37634     discardUrl: false,
37635     nocache: false,
37636     text: "Loading...",
37637     timeout: 30,
37638     scripts: false
37639 });
37640 </code></pre>
37641      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
37642      * 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.
37643      * @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}
37644      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
37645      * @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.
37646      * @return {Roo.ContentPanel} this
37647      */
37648     load : function(){
37649         var um = this.el.getUpdateManager();
37650         um.update.apply(um, arguments);
37651         return this;
37652     },
37653
37654
37655     /**
37656      * 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.
37657      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
37658      * @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)
37659      * @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)
37660      * @return {Roo.UpdateManager} The UpdateManager
37661      */
37662     setUrl : function(url, params, loadOnce){
37663         if(this.refreshDelegate){
37664             this.removeListener("activate", this.refreshDelegate);
37665         }
37666         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
37667         this.on("activate", this.refreshDelegate);
37668         return this.el.getUpdateManager();
37669     },
37670     
37671     _handleRefresh : function(url, params, loadOnce){
37672         if(!loadOnce || !this.loaded){
37673             var updater = this.el.getUpdateManager();
37674             updater.update(url, params, this._setLoaded.createDelegate(this));
37675         }
37676     },
37677     
37678     _setLoaded : function(){
37679         this.loaded = true;
37680     }, 
37681     
37682     /**
37683      * Returns this panel's id
37684      * @return {String} 
37685      */
37686     getId : function(){
37687         return this.el.id;
37688     },
37689     
37690     /** 
37691      * Returns this panel's element - used by regiosn to add.
37692      * @return {Roo.Element} 
37693      */
37694     getEl : function(){
37695         return this.wrapEl || this.el;
37696     },
37697     
37698    
37699     
37700     adjustForComponents : function(width, height)
37701     {
37702         //Roo.log('adjustForComponents ');
37703         if(this.resizeEl != this.el){
37704             width -= this.el.getFrameWidth('lr');
37705             height -= this.el.getFrameWidth('tb');
37706         }
37707         if(this.toolbar){
37708             var te = this.toolbar.getEl();
37709             te.setWidth(width);
37710             height -= te.getHeight();
37711         }
37712         if(this.footer){
37713             var te = this.footer.getEl();
37714             te.setWidth(width);
37715             height -= te.getHeight();
37716         }
37717         
37718         
37719         if(this.adjustments){
37720             width += this.adjustments[0];
37721             height += this.adjustments[1];
37722         }
37723         return {"width": width, "height": height};
37724     },
37725     
37726     setSize : function(width, height){
37727         if(this.fitToFrame && !this.ignoreResize(width, height)){
37728             if(this.fitContainer && this.resizeEl != this.el){
37729                 this.el.setSize(width, height);
37730             }
37731             var size = this.adjustForComponents(width, height);
37732             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
37733             this.fireEvent('resize', this, size.width, size.height);
37734         }
37735     },
37736     
37737     /**
37738      * Returns this panel's title
37739      * @return {String} 
37740      */
37741     getTitle : function(){
37742         
37743         if (typeof(this.title) != 'object') {
37744             return this.title;
37745         }
37746         
37747         var t = '';
37748         for (var k in this.title) {
37749             if (!this.title.hasOwnProperty(k)) {
37750                 continue;
37751             }
37752             
37753             if (k.indexOf('-') >= 0) {
37754                 var s = k.split('-');
37755                 for (var i = 0; i<s.length; i++) {
37756                     t += "<span class='visible-"+s[i]+"'>"+this.title[k]+"</span>";
37757                 }
37758             } else {
37759                 t += "<span class='visible-"+k+"'>"+this.title[k]+"</span>";
37760             }
37761         }
37762         return t;
37763     },
37764     
37765     /**
37766      * Set this panel's title
37767      * @param {String} title
37768      */
37769     setTitle : function(title){
37770         this.title = title;
37771         if(this.region){
37772             this.region.updatePanelTitle(this, title);
37773         }
37774     },
37775     
37776     /**
37777      * Returns true is this panel was configured to be closable
37778      * @return {Boolean} 
37779      */
37780     isClosable : function(){
37781         return this.closable;
37782     },
37783     
37784     beforeSlide : function(){
37785         this.el.clip();
37786         this.resizeEl.clip();
37787     },
37788     
37789     afterSlide : function(){
37790         this.el.unclip();
37791         this.resizeEl.unclip();
37792     },
37793     
37794     /**
37795      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
37796      *   Will fail silently if the {@link #setUrl} method has not been called.
37797      *   This does not activate the panel, just updates its content.
37798      */
37799     refresh : function(){
37800         if(this.refreshDelegate){
37801            this.loaded = false;
37802            this.refreshDelegate();
37803         }
37804     },
37805     
37806     /**
37807      * Destroys this panel
37808      */
37809     destroy : function(){
37810         this.el.removeAllListeners();
37811         var tempEl = document.createElement("span");
37812         tempEl.appendChild(this.el.dom);
37813         tempEl.innerHTML = "";
37814         this.el.remove();
37815         this.el = null;
37816     },
37817     
37818     /**
37819      * form - if the content panel contains a form - this is a reference to it.
37820      * @type {Roo.form.Form}
37821      */
37822     form : false,
37823     /**
37824      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
37825      *    This contains a reference to it.
37826      * @type {Roo.View}
37827      */
37828     view : false,
37829     
37830       /**
37831      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
37832      * <pre><code>
37833
37834 layout.addxtype({
37835        xtype : 'Form',
37836        items: [ .... ]
37837    }
37838 );
37839
37840 </code></pre>
37841      * @param {Object} cfg Xtype definition of item to add.
37842      */
37843     
37844     
37845     getChildContainer: function () {
37846         return this.getEl();
37847     }
37848     
37849     
37850     /*
37851         var  ret = new Roo.factory(cfg);
37852         return ret;
37853         
37854         
37855         // add form..
37856         if (cfg.xtype.match(/^Form$/)) {
37857             
37858             var el;
37859             //if (this.footer) {
37860             //    el = this.footer.container.insertSibling(false, 'before');
37861             //} else {
37862                 el = this.el.createChild();
37863             //}
37864
37865             this.form = new  Roo.form.Form(cfg);
37866             
37867             
37868             if ( this.form.allItems.length) {
37869                 this.form.render(el.dom);
37870             }
37871             return this.form;
37872         }
37873         // should only have one of theses..
37874         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
37875             // views.. should not be just added - used named prop 'view''
37876             
37877             cfg.el = this.el.appendChild(document.createElement("div"));
37878             // factory?
37879             
37880             var ret = new Roo.factory(cfg);
37881              
37882              ret.render && ret.render(false, ''); // render blank..
37883             this.view = ret;
37884             return ret;
37885         }
37886         return false;
37887     }
37888     \*/
37889 });
37890  
37891 /**
37892  * @class Roo.bootstrap.panel.Grid
37893  * @extends Roo.bootstrap.panel.Content
37894  * @constructor
37895  * Create a new GridPanel.
37896  * @cfg {Roo.bootstrap.Table} grid The grid for this panel
37897  * @param {Object} config A the config object
37898   
37899  */
37900
37901
37902
37903 Roo.bootstrap.panel.Grid = function(config)
37904 {
37905     
37906       
37907     this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
37908         {tag: "div", cls: "roo-layout-grid-wrapper roo-layout-inactive-content"}, true);
37909
37910     config.el = this.wrapper;
37911     //this.el = this.wrapper;
37912     
37913       if (config.container) {
37914         // ctor'ed from a Border/panel.grid
37915         
37916         
37917         this.wrapper.setStyle("overflow", "hidden");
37918         this.wrapper.addClass('roo-grid-container');
37919
37920     }
37921     
37922     
37923     if(config.toolbar){
37924         var tool_el = this.wrapper.createChild();    
37925         this.toolbar = Roo.factory(config.toolbar);
37926         var ti = [];
37927         if (config.toolbar.items) {
37928             ti = config.toolbar.items ;
37929             delete config.toolbar.items ;
37930         }
37931         
37932         var nitems = [];
37933         this.toolbar.render(tool_el);
37934         for(var i =0;i < ti.length;i++) {
37935           //  Roo.log(['add child', items[i]]);
37936             nitems.push(this.toolbar.addxtype(Roo.apply({}, ti[i])));
37937         }
37938         this.toolbar.items = nitems;
37939         
37940         delete config.toolbar;
37941     }
37942     
37943     Roo.bootstrap.panel.Grid.superclass.constructor.call(this, config);
37944     config.grid.scrollBody = true;;
37945     config.grid.monitorWindowResize = false; // turn off autosizing
37946     config.grid.autoHeight = false;
37947     config.grid.autoWidth = false;
37948     
37949     this.grid = new config.grid.xns[config.grid.xtype](config.grid);
37950     
37951     if (config.background) {
37952         // render grid on panel activation (if panel background)
37953         this.on('activate', function(gp) {
37954             if (!gp.grid.rendered) {
37955                 gp.grid.render(this.wrapper);
37956                 gp.grid.getGridEl().replaceClass("roo-layout-inactive-content", "roo-layout-component-panel");   
37957             }
37958         });
37959             
37960     } else {
37961         this.grid.render(this.wrapper);
37962         this.grid.getGridEl().replaceClass("roo-layout-inactive-content", "roo-layout-component-panel");               
37963
37964     }
37965     //this.wrapper.dom.appendChild(config.grid.getGridEl().dom);
37966     // ??? needed ??? config.el = this.wrapper;
37967     
37968     
37969     
37970   
37971     // xtype created footer. - not sure if will work as we normally have to render first..
37972     if (this.footer && !this.footer.el && this.footer.xtype) {
37973         
37974         var ctr = this.grid.getView().getFooterPanel(true);
37975         this.footer.dataSource = this.grid.dataSource;
37976         this.footer = Roo.factory(this.footer, Roo);
37977         this.footer.render(ctr);
37978         
37979     }
37980     
37981     
37982     
37983     
37984      
37985 };
37986
37987 Roo.extend(Roo.bootstrap.panel.Grid, Roo.bootstrap.panel.Content, {
37988     getId : function(){
37989         return this.grid.id;
37990     },
37991     
37992     /**
37993      * Returns the grid for this panel
37994      * @return {Roo.bootstrap.Table} 
37995      */
37996     getGrid : function(){
37997         return this.grid;    
37998     },
37999     
38000     setSize : function(width, height){
38001         if(!this.ignoreResize(width, height)){
38002             var grid = this.grid;
38003             var size = this.adjustForComponents(width, height);
38004             var gridel = grid.getGridEl();
38005             gridel.setSize(size.width, size.height);
38006             /*
38007             var thd = grid.getGridEl().select('thead',true).first();
38008             var tbd = grid.getGridEl().select('tbody', true).first();
38009             if (tbd) {
38010                 tbd.setSize(width, height - thd.getHeight());
38011             }
38012             */
38013             grid.autoSize();
38014         }
38015     },
38016      
38017     
38018     
38019     beforeSlide : function(){
38020         this.grid.getView().scroller.clip();
38021     },
38022     
38023     afterSlide : function(){
38024         this.grid.getView().scroller.unclip();
38025     },
38026     
38027     destroy : function(){
38028         this.grid.destroy();
38029         delete this.grid;
38030         Roo.bootstrap.panel.Grid.superclass.destroy.call(this); 
38031     }
38032 });
38033
38034 /**
38035  * @class Roo.bootstrap.panel.Nest
38036  * @extends Roo.bootstrap.panel.Content
38037  * @constructor
38038  * Create a new Panel, that can contain a layout.Border.
38039  * 
38040  * 
38041  * @param {Roo.BorderLayout} layout The layout for this panel
38042  * @param {String/Object} config A string to set only the title or a config object
38043  */
38044 Roo.bootstrap.panel.Nest = function(config)
38045 {
38046     // construct with only one argument..
38047     /* FIXME - implement nicer consturctors
38048     if (layout.layout) {
38049         config = layout;
38050         layout = config.layout;
38051         delete config.layout;
38052     }
38053     if (layout.xtype && !layout.getEl) {
38054         // then layout needs constructing..
38055         layout = Roo.factory(layout, Roo);
38056     }
38057     */
38058     
38059     config.el =  config.layout.getEl();
38060     
38061     Roo.bootstrap.panel.Nest.superclass.constructor.call(this, config);
38062     
38063     config.layout.monitorWindowResize = false; // turn off autosizing
38064     this.layout = config.layout;
38065     this.layout.getEl().addClass("roo-layout-nested-layout");
38066     this.layout.parent = this;
38067     
38068     
38069     
38070     
38071 };
38072
38073 Roo.extend(Roo.bootstrap.panel.Nest, Roo.bootstrap.panel.Content, {
38074
38075     setSize : function(width, height){
38076         if(!this.ignoreResize(width, height)){
38077             var size = this.adjustForComponents(width, height);
38078             var el = this.layout.getEl();
38079             if (size.height < 1) {
38080                 el.setWidth(size.width);   
38081             } else {
38082                 el.setSize(size.width, size.height);
38083             }
38084             var touch = el.dom.offsetWidth;
38085             this.layout.layout();
38086             // ie requires a double layout on the first pass
38087             if(Roo.isIE && !this.initialized){
38088                 this.initialized = true;
38089                 this.layout.layout();
38090             }
38091         }
38092     },
38093     
38094     // activate all subpanels if not currently active..
38095     
38096     setActiveState : function(active){
38097         this.active = active;
38098         this.setActiveClass(active);
38099         
38100         if(!active){
38101             this.fireEvent("deactivate", this);
38102             return;
38103         }
38104         
38105         this.fireEvent("activate", this);
38106         // not sure if this should happen before or after..
38107         if (!this.layout) {
38108             return; // should not happen..
38109         }
38110         var reg = false;
38111         for (var r in this.layout.regions) {
38112             reg = this.layout.getRegion(r);
38113             if (reg.getActivePanel()) {
38114                 //reg.showPanel(reg.getActivePanel()); // force it to activate.. 
38115                 reg.setActivePanel(reg.getActivePanel());
38116                 continue;
38117             }
38118             if (!reg.panels.length) {
38119                 continue;
38120             }
38121             reg.showPanel(reg.getPanel(0));
38122         }
38123         
38124         
38125         
38126         
38127     },
38128     
38129     /**
38130      * Returns the nested BorderLayout for this panel
38131      * @return {Roo.BorderLayout} 
38132      */
38133     getLayout : function(){
38134         return this.layout;
38135     },
38136     
38137      /**
38138      * Adds a xtype elements to the layout of the nested panel
38139      * <pre><code>
38140
38141 panel.addxtype({
38142        xtype : 'ContentPanel',
38143        region: 'west',
38144        items: [ .... ]
38145    }
38146 );
38147
38148 panel.addxtype({
38149         xtype : 'NestedLayoutPanel',
38150         region: 'west',
38151         layout: {
38152            center: { },
38153            west: { }   
38154         },
38155         items : [ ... list of content panels or nested layout panels.. ]
38156    }
38157 );
38158 </code></pre>
38159      * @param {Object} cfg Xtype definition of item to add.
38160      */
38161     addxtype : function(cfg) {
38162         return this.layout.addxtype(cfg);
38163     
38164     }
38165 });/*
38166  * Based on:
38167  * Ext JS Library 1.1.1
38168  * Copyright(c) 2006-2007, Ext JS, LLC.
38169  *
38170  * Originally Released Under LGPL - original licence link has changed is not relivant.
38171  *
38172  * Fork - LGPL
38173  * <script type="text/javascript">
38174  */
38175 /**
38176  * @class Roo.TabPanel
38177  * @extends Roo.util.Observable
38178  * A lightweight tab container.
38179  * <br><br>
38180  * Usage:
38181  * <pre><code>
38182 // basic tabs 1, built from existing content
38183 var tabs = new Roo.TabPanel("tabs1");
38184 tabs.addTab("script", "View Script");
38185 tabs.addTab("markup", "View Markup");
38186 tabs.activate("script");
38187
38188 // more advanced tabs, built from javascript
38189 var jtabs = new Roo.TabPanel("jtabs");
38190 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
38191
38192 // set up the UpdateManager
38193 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
38194 var updater = tab2.getUpdateManager();
38195 updater.setDefaultUrl("ajax1.htm");
38196 tab2.on('activate', updater.refresh, updater, true);
38197
38198 // Use setUrl for Ajax loading
38199 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
38200 tab3.setUrl("ajax2.htm", null, true);
38201
38202 // Disabled tab
38203 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
38204 tab4.disable();
38205
38206 jtabs.activate("jtabs-1");
38207  * </code></pre>
38208  * @constructor
38209  * Create a new TabPanel.
38210  * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
38211  * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
38212  */
38213 Roo.bootstrap.panel.Tabs = function(config){
38214     /**
38215     * The container element for this TabPanel.
38216     * @type Roo.Element
38217     */
38218     this.el = Roo.get(config.el);
38219     delete config.el;
38220     if(config){
38221         if(typeof config == "boolean"){
38222             this.tabPosition = config ? "bottom" : "top";
38223         }else{
38224             Roo.apply(this, config);
38225         }
38226     }
38227     
38228     if(this.tabPosition == "bottom"){
38229         // if tabs are at the bottom = create the body first.
38230         this.bodyEl = Roo.get(this.createBody(this.el.dom));
38231         this.el.addClass("roo-tabs-bottom");
38232     }
38233     // next create the tabs holders
38234     
38235     if (this.tabPosition == "west"){
38236         
38237         var reg = this.region; // fake it..
38238         while (reg) {
38239             if (!reg.mgr.parent) {
38240                 break;
38241             }
38242             reg = reg.mgr.parent.region;
38243         }
38244         Roo.log("got nest?");
38245         Roo.log(reg);
38246         if (reg.mgr.getRegion('west')) {
38247             var ctrdom = reg.mgr.getRegion('west').bodyEl.dom;
38248             this.stripWrap = Roo.get(this.createStrip(ctrdom ), true);
38249             this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
38250             this.stripEl.setVisibilityMode(Roo.Element.DISPLAY);
38251             this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
38252         
38253             
38254         }
38255         
38256         
38257     } else {
38258      
38259         this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
38260         this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
38261         this.stripEl.setVisibilityMode(Roo.Element.DISPLAY);
38262         this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
38263     }
38264     
38265     
38266     if(Roo.isIE){
38267         Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
38268     }
38269     
38270     // finally - if tabs are at the top, then create the body last..
38271     if(this.tabPosition != "bottom"){
38272         /** The body element that contains {@link Roo.TabPanelItem} bodies. +
38273          * @type Roo.Element
38274          */
38275         this.bodyEl = Roo.get(this.createBody(this.el.dom));
38276         this.el.addClass("roo-tabs-top");
38277     }
38278     this.items = [];
38279
38280     this.bodyEl.setStyle("position", "relative");
38281
38282     this.active = null;
38283     this.activateDelegate = this.activate.createDelegate(this);
38284
38285     this.addEvents({
38286         /**
38287          * @event tabchange
38288          * Fires when the active tab changes
38289          * @param {Roo.TabPanel} this
38290          * @param {Roo.TabPanelItem} activePanel The new active tab
38291          */
38292         "tabchange": true,
38293         /**
38294          * @event beforetabchange
38295          * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
38296          * @param {Roo.TabPanel} this
38297          * @param {Object} e Set cancel to true on this object to cancel the tab change
38298          * @param {Roo.TabPanelItem} tab The tab being changed to
38299          */
38300         "beforetabchange" : true
38301     });
38302
38303     Roo.EventManager.onWindowResize(this.onResize, this);
38304     this.cpad = this.el.getPadding("lr");
38305     this.hiddenCount = 0;
38306
38307
38308     // toolbar on the tabbar support...
38309     if (this.toolbar) {
38310         alert("no toolbar support yet");
38311         this.toolbar  = false;
38312         /*
38313         var tcfg = this.toolbar;
38314         tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');  
38315         this.toolbar = new Roo.Toolbar(tcfg);
38316         if (Roo.isSafari) {
38317             var tbl = tcfg.container.child('table', true);
38318             tbl.setAttribute('width', '100%');
38319         }
38320         */
38321         
38322     }
38323    
38324
38325
38326     Roo.bootstrap.panel.Tabs.superclass.constructor.call(this);
38327 };
38328
38329 Roo.extend(Roo.bootstrap.panel.Tabs, Roo.util.Observable, {
38330     /*
38331      *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
38332      */
38333     tabPosition : "top",
38334     /*
38335      *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
38336      */
38337     currentTabWidth : 0,
38338     /*
38339      *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
38340      */
38341     minTabWidth : 40,
38342     /*
38343      *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
38344      */
38345     maxTabWidth : 250,
38346     /*
38347      *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
38348      */
38349     preferredTabWidth : 175,
38350     /*
38351      *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
38352      */
38353     resizeTabs : false,
38354     /*
38355      *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
38356      */
38357     monitorResize : true,
38358     /*
38359      *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar. 
38360      */
38361     toolbar : false,  // set by caller..
38362     
38363     region : false, /// set by caller
38364     
38365     disableTooltips : true, // not used yet...
38366
38367     /**
38368      * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
38369      * @param {String} id The id of the div to use <b>or create</b>
38370      * @param {String} text The text for the tab
38371      * @param {String} content (optional) Content to put in the TabPanelItem body
38372      * @param {Boolean} closable (optional) True to create a close icon on the tab
38373      * @return {Roo.TabPanelItem} The created TabPanelItem
38374      */
38375     addTab : function(id, text, content, closable, tpl)
38376     {
38377         var item = new Roo.bootstrap.panel.TabItem({
38378             panel: this,
38379             id : id,
38380             text : text,
38381             closable : closable,
38382             tpl : tpl
38383         });
38384         this.addTabItem(item);
38385         if(content){
38386             item.setContent(content);
38387         }
38388         return item;
38389     },
38390
38391     /**
38392      * Returns the {@link Roo.TabPanelItem} with the specified id/index
38393      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
38394      * @return {Roo.TabPanelItem}
38395      */
38396     getTab : function(id){
38397         return this.items[id];
38398     },
38399
38400     /**
38401      * Hides the {@link Roo.TabPanelItem} with the specified id/index
38402      * @param {String/Number} id The id or index of the TabPanelItem to hide.
38403      */
38404     hideTab : function(id){
38405         var t = this.items[id];
38406         if(!t.isHidden()){
38407            t.setHidden(true);
38408            this.hiddenCount++;
38409            this.autoSizeTabs();
38410         }
38411     },
38412
38413     /**
38414      * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
38415      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
38416      */
38417     unhideTab : function(id){
38418         var t = this.items[id];
38419         if(t.isHidden()){
38420            t.setHidden(false);
38421            this.hiddenCount--;
38422            this.autoSizeTabs();
38423         }
38424     },
38425
38426     /**
38427      * Adds an existing {@link Roo.TabPanelItem}.
38428      * @param {Roo.TabPanelItem} item The TabPanelItem to add
38429      */
38430     addTabItem : function(item)
38431     {
38432         this.items[item.id] = item;
38433         this.items.push(item);
38434         this.autoSizeTabs();
38435       //  if(this.resizeTabs){
38436     //       item.setWidth(this.currentTabWidth || this.preferredTabWidth);
38437   //         this.autoSizeTabs();
38438 //        }else{
38439 //            item.autoSize();
38440        // }
38441     },
38442
38443     /**
38444      * Removes a {@link Roo.TabPanelItem}.
38445      * @param {String/Number} id The id or index of the TabPanelItem to remove.
38446      */
38447     removeTab : function(id){
38448         var items = this.items;
38449         var tab = items[id];
38450         if(!tab) { return; }
38451         var index = items.indexOf(tab);
38452         if(this.active == tab && items.length > 1){
38453             var newTab = this.getNextAvailable(index);
38454             if(newTab) {
38455                 newTab.activate();
38456             }
38457         }
38458         this.stripEl.dom.removeChild(tab.pnode.dom);
38459         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
38460             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
38461         }
38462         items.splice(index, 1);
38463         delete this.items[tab.id];
38464         tab.fireEvent("close", tab);
38465         tab.purgeListeners();
38466         this.autoSizeTabs();
38467     },
38468
38469     getNextAvailable : function(start){
38470         var items = this.items;
38471         var index = start;
38472         // look for a next tab that will slide over to
38473         // replace the one being removed
38474         while(index < items.length){
38475             var item = items[++index];
38476             if(item && !item.isHidden()){
38477                 return item;
38478             }
38479         }
38480         // if one isn't found select the previous tab (on the left)
38481         index = start;
38482         while(index >= 0){
38483             var item = items[--index];
38484             if(item && !item.isHidden()){
38485                 return item;
38486             }
38487         }
38488         return null;
38489     },
38490
38491     /**
38492      * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
38493      * @param {String/Number} id The id or index of the TabPanelItem to disable.
38494      */
38495     disableTab : function(id){
38496         var tab = this.items[id];
38497         if(tab && this.active != tab){
38498             tab.disable();
38499         }
38500     },
38501
38502     /**
38503      * Enables a {@link Roo.TabPanelItem} that is disabled.
38504      * @param {String/Number} id The id or index of the TabPanelItem to enable.
38505      */
38506     enableTab : function(id){
38507         var tab = this.items[id];
38508         tab.enable();
38509     },
38510
38511     /**
38512      * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
38513      * @param {String/Number} id The id or index of the TabPanelItem to activate.
38514      * @return {Roo.TabPanelItem} The TabPanelItem.
38515      */
38516     activate : function(id)
38517     {
38518         //Roo.log('activite:'  + id);
38519         
38520         var tab = this.items[id];
38521         if(!tab){
38522             return null;
38523         }
38524         if(tab == this.active || tab.disabled){
38525             return tab;
38526         }
38527         var e = {};
38528         this.fireEvent("beforetabchange", this, e, tab);
38529         if(e.cancel !== true && !tab.disabled){
38530             if(this.active){
38531                 this.active.hide();
38532             }
38533             this.active = this.items[id];
38534             this.active.show();
38535             this.fireEvent("tabchange", this, this.active);
38536         }
38537         return tab;
38538     },
38539
38540     /**
38541      * Gets the active {@link Roo.TabPanelItem}.
38542      * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
38543      */
38544     getActiveTab : function(){
38545         return this.active;
38546     },
38547
38548     /**
38549      * Updates the tab body element to fit the height of the container element
38550      * for overflow scrolling
38551      * @param {Number} targetHeight (optional) Override the starting height from the elements height
38552      */
38553     syncHeight : function(targetHeight){
38554         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
38555         var bm = this.bodyEl.getMargins();
38556         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
38557         this.bodyEl.setHeight(newHeight);
38558         return newHeight;
38559     },
38560
38561     onResize : function(){
38562         if(this.monitorResize){
38563             this.autoSizeTabs();
38564         }
38565     },
38566
38567     /**
38568      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
38569      */
38570     beginUpdate : function(){
38571         this.updating = true;
38572     },
38573
38574     /**
38575      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
38576      */
38577     endUpdate : function(){
38578         this.updating = false;
38579         this.autoSizeTabs();
38580     },
38581
38582     /**
38583      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
38584      */
38585     autoSizeTabs : function()
38586     {
38587         var count = this.items.length;
38588         var vcount = count - this.hiddenCount;
38589         
38590         if (vcount < 2) {
38591             this.stripEl.hide();
38592         } else {
38593             this.stripEl.show();
38594         }
38595         
38596         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
38597             return;
38598         }
38599         
38600         
38601         var w = Math.max(this.el.getWidth() - this.cpad, 10);
38602         var availWidth = Math.floor(w / vcount);
38603         var b = this.stripBody;
38604         if(b.getWidth() > w){
38605             var tabs = this.items;
38606             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
38607             if(availWidth < this.minTabWidth){
38608                 /*if(!this.sleft){    // incomplete scrolling code
38609                     this.createScrollButtons();
38610                 }
38611                 this.showScroll();
38612                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
38613             }
38614         }else{
38615             if(this.currentTabWidth < this.preferredTabWidth){
38616                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
38617             }
38618         }
38619     },
38620
38621     /**
38622      * Returns the number of tabs in this TabPanel.
38623      * @return {Number}
38624      */
38625      getCount : function(){
38626          return this.items.length;
38627      },
38628
38629     /**
38630      * Resizes all the tabs to the passed width
38631      * @param {Number} The new width
38632      */
38633     setTabWidth : function(width){
38634         this.currentTabWidth = width;
38635         for(var i = 0, len = this.items.length; i < len; i++) {
38636                 if(!this.items[i].isHidden()) {
38637                 this.items[i].setWidth(width);
38638             }
38639         }
38640     },
38641
38642     /**
38643      * Destroys this TabPanel
38644      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
38645      */
38646     destroy : function(removeEl){
38647         Roo.EventManager.removeResizeListener(this.onResize, this);
38648         for(var i = 0, len = this.items.length; i < len; i++){
38649             this.items[i].purgeListeners();
38650         }
38651         if(removeEl === true){
38652             this.el.update("");
38653             this.el.remove();
38654         }
38655     },
38656     
38657     createStrip : function(container)
38658     {
38659         var strip = document.createElement("nav");
38660         strip.className = Roo.bootstrap.version == 4 ?
38661             "navbar-light bg-light" : 
38662             "navbar navbar-default"; //"x-tabs-wrap";
38663         container.appendChild(strip);
38664         return strip;
38665     },
38666     
38667     createStripList : function(strip)
38668     {
38669         // div wrapper for retard IE
38670         // returns the "tr" element.
38671         strip.innerHTML = '<ul class="nav nav-tabs" role="tablist"></ul>';
38672         //'<div class="x-tabs-strip-wrap">'+
38673           //  '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
38674           //  '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
38675         return strip.firstChild; //.firstChild.firstChild.firstChild;
38676     },
38677     createBody : function(container)
38678     {
38679         var body = document.createElement("div");
38680         Roo.id(body, "tab-body");
38681         //Roo.fly(body).addClass("x-tabs-body");
38682         Roo.fly(body).addClass("tab-content");
38683         container.appendChild(body);
38684         return body;
38685     },
38686     createItemBody :function(bodyEl, id){
38687         var body = Roo.getDom(id);
38688         if(!body){
38689             body = document.createElement("div");
38690             body.id = id;
38691         }
38692         //Roo.fly(body).addClass("x-tabs-item-body");
38693         Roo.fly(body).addClass("tab-pane");
38694          bodyEl.insertBefore(body, bodyEl.firstChild);
38695         return body;
38696     },
38697     /** @private */
38698     createStripElements :  function(stripEl, text, closable, tpl)
38699     {
38700         var td = document.createElement("li"); // was td..
38701         td.className = 'nav-item';
38702         
38703         //stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
38704         
38705         
38706         stripEl.appendChild(td);
38707         /*if(closable){
38708             td.className = "x-tabs-closable";
38709             if(!this.closeTpl){
38710                 this.closeTpl = new Roo.Template(
38711                    '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
38712                    '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
38713                    '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
38714                 );
38715             }
38716             var el = this.closeTpl.overwrite(td, {"text": text});
38717             var close = el.getElementsByTagName("div")[0];
38718             var inner = el.getElementsByTagName("em")[0];
38719             return {"el": el, "close": close, "inner": inner};
38720         } else {
38721         */
38722         // not sure what this is..
38723 //            if(!this.tabTpl){
38724                 //this.tabTpl = new Roo.Template(
38725                 //   '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
38726                 //   '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
38727                 //);
38728 //                this.tabTpl = new Roo.Template(
38729 //                   '<a href="#">' +
38730 //                   '<span unselectable="on"' +
38731 //                            (this.disableTooltips ? '' : ' title="{text}"') +
38732 //                            ' >{text}</span></a>'
38733 //                );
38734 //                
38735 //            }
38736
38737
38738             var template = tpl || this.tabTpl || false;
38739             
38740             if(!template){
38741                 template =  new Roo.Template(
38742                         Roo.bootstrap.version == 4 ? 
38743                             (
38744                                 '<a class="nav-link" href="#" unselectable="on"' +
38745                                      (this.disableTooltips ? '' : ' title="{text}"') +
38746                                      ' >{text}</a>'
38747                             ) : (
38748                                 '<a class="nav-link" href="#">' +
38749                                 '<span unselectable="on"' +
38750                                          (this.disableTooltips ? '' : ' title="{text}"') +
38751                                     ' >{text}</span></a>'
38752                             )
38753                 );
38754             }
38755             
38756             switch (typeof(template)) {
38757                 case 'object' :
38758                     break;
38759                 case 'string' :
38760                     template = new Roo.Template(template);
38761                     break;
38762                 default :
38763                     break;
38764             }
38765             
38766             var el = template.overwrite(td, {"text": text});
38767             
38768             var inner = el.getElementsByTagName("span")[0];
38769             
38770             return {"el": el, "inner": inner};
38771             
38772     }
38773         
38774     
38775 });
38776
38777 /**
38778  * @class Roo.TabPanelItem
38779  * @extends Roo.util.Observable
38780  * Represents an individual item (tab plus body) in a TabPanel.
38781  * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
38782  * @param {String} id The id of this TabPanelItem
38783  * @param {String} text The text for the tab of this TabPanelItem
38784  * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
38785  */
38786 Roo.bootstrap.panel.TabItem = function(config){
38787     /**
38788      * The {@link Roo.TabPanel} this TabPanelItem belongs to
38789      * @type Roo.TabPanel
38790      */
38791     this.tabPanel = config.panel;
38792     /**
38793      * The id for this TabPanelItem
38794      * @type String
38795      */
38796     this.id = config.id;
38797     /** @private */
38798     this.disabled = false;
38799     /** @private */
38800     this.text = config.text;
38801     /** @private */
38802     this.loaded = false;
38803     this.closable = config.closable;
38804
38805     /**
38806      * The body element for this TabPanelItem.
38807      * @type Roo.Element
38808      */
38809     this.bodyEl = Roo.get(this.tabPanel.createItemBody(this.tabPanel.bodyEl.dom, config.id));
38810     this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
38811     this.bodyEl.setStyle("display", "block");
38812     this.bodyEl.setStyle("zoom", "1");
38813     //this.hideAction();
38814
38815     var els = this.tabPanel.createStripElements(this.tabPanel.stripEl.dom, config.text, config.closable, config.tpl);
38816     /** @private */
38817     this.el = Roo.get(els.el);
38818     this.inner = Roo.get(els.inner, true);
38819      this.textEl = Roo.bootstrap.version == 4 ?
38820         this.el : Roo.get(this.el.dom.firstChild, true);
38821
38822     this.pnode = this.linode = Roo.get(els.el.parentNode, true);
38823     this.status_node = Roo.bootstrap.version == 4 ? this.el : this.linode;
38824
38825     
38826 //    this.el.on("mousedown", this.onTabMouseDown, this);
38827     this.el.on("click", this.onTabClick, this);
38828     /** @private */
38829     if(config.closable){
38830         var c = Roo.get(els.close, true);
38831         c.dom.title = this.closeText;
38832         c.addClassOnOver("close-over");
38833         c.on("click", this.closeClick, this);
38834      }
38835
38836     this.addEvents({
38837          /**
38838          * @event activate
38839          * Fires when this tab becomes the active tab.
38840          * @param {Roo.TabPanel} tabPanel The parent TabPanel
38841          * @param {Roo.TabPanelItem} this
38842          */
38843         "activate": true,
38844         /**
38845          * @event beforeclose
38846          * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
38847          * @param {Roo.TabPanelItem} this
38848          * @param {Object} e Set cancel to true on this object to cancel the close.
38849          */
38850         "beforeclose": true,
38851         /**
38852          * @event close
38853          * Fires when this tab is closed.
38854          * @param {Roo.TabPanelItem} this
38855          */
38856          "close": true,
38857         /**
38858          * @event deactivate
38859          * Fires when this tab is no longer the active tab.
38860          * @param {Roo.TabPanel} tabPanel The parent TabPanel
38861          * @param {Roo.TabPanelItem} this
38862          */
38863          "deactivate" : true
38864     });
38865     this.hidden = false;
38866
38867     Roo.bootstrap.panel.TabItem.superclass.constructor.call(this);
38868 };
38869
38870 Roo.extend(Roo.bootstrap.panel.TabItem, Roo.util.Observable,
38871            {
38872     purgeListeners : function(){
38873        Roo.util.Observable.prototype.purgeListeners.call(this);
38874        this.el.removeAllListeners();
38875     },
38876     /**
38877      * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
38878      */
38879     show : function(){
38880         this.status_node.addClass("active");
38881         this.showAction();
38882         if(Roo.isOpera){
38883             this.tabPanel.stripWrap.repaint();
38884         }
38885         this.fireEvent("activate", this.tabPanel, this);
38886     },
38887
38888     /**
38889      * Returns true if this tab is the active tab.
38890      * @return {Boolean}
38891      */
38892     isActive : function(){
38893         return this.tabPanel.getActiveTab() == this;
38894     },
38895
38896     /**
38897      * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
38898      */
38899     hide : function(){
38900         this.status_node.removeClass("active");
38901         this.hideAction();
38902         this.fireEvent("deactivate", this.tabPanel, this);
38903     },
38904
38905     hideAction : function(){
38906         this.bodyEl.hide();
38907         this.bodyEl.setStyle("position", "absolute");
38908         this.bodyEl.setLeft("-20000px");
38909         this.bodyEl.setTop("-20000px");
38910     },
38911
38912     showAction : function(){
38913         this.bodyEl.setStyle("position", "relative");
38914         this.bodyEl.setTop("");
38915         this.bodyEl.setLeft("");
38916         this.bodyEl.show();
38917     },
38918
38919     /**
38920      * Set the tooltip for the tab.
38921      * @param {String} tooltip The tab's tooltip
38922      */
38923     setTooltip : function(text){
38924         if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
38925             this.textEl.dom.qtip = text;
38926             this.textEl.dom.removeAttribute('title');
38927         }else{
38928             this.textEl.dom.title = text;
38929         }
38930     },
38931
38932     onTabClick : function(e){
38933         e.preventDefault();
38934         this.tabPanel.activate(this.id);
38935     },
38936
38937     onTabMouseDown : function(e){
38938         e.preventDefault();
38939         this.tabPanel.activate(this.id);
38940     },
38941 /*
38942     getWidth : function(){
38943         return this.inner.getWidth();
38944     },
38945
38946     setWidth : function(width){
38947         var iwidth = width - this.linode.getPadding("lr");
38948         this.inner.setWidth(iwidth);
38949         this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
38950         this.linode.setWidth(width);
38951     },
38952 */
38953     /**
38954      * Show or hide the tab
38955      * @param {Boolean} hidden True to hide or false to show.
38956      */
38957     setHidden : function(hidden){
38958         this.hidden = hidden;
38959         this.linode.setStyle("display", hidden ? "none" : "");
38960     },
38961
38962     /**
38963      * Returns true if this tab is "hidden"
38964      * @return {Boolean}
38965      */
38966     isHidden : function(){
38967         return this.hidden;
38968     },
38969
38970     /**
38971      * Returns the text for this tab
38972      * @return {String}
38973      */
38974     getText : function(){
38975         return this.text;
38976     },
38977     /*
38978     autoSize : function(){
38979         //this.el.beginMeasure();
38980         this.textEl.setWidth(1);
38981         /*
38982          *  #2804 [new] Tabs in Roojs
38983          *  increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
38984          */
38985         //this.setWidth(this.textEl.dom.scrollWidth+this.linode.getPadding("lr")+this.inner.getPadding("lr") + 2);
38986         //this.el.endMeasure();
38987     //},
38988
38989     /**
38990      * Sets the text for the tab (Note: this also sets the tooltip text)
38991      * @param {String} text The tab's text and tooltip
38992      */
38993     setText : function(text){
38994         this.text = text;
38995         this.textEl.update(text);
38996         this.setTooltip(text);
38997         //if(!this.tabPanel.resizeTabs){
38998         //    this.autoSize();
38999         //}
39000     },
39001     /**
39002      * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
39003      */
39004     activate : function(){
39005         this.tabPanel.activate(this.id);
39006     },
39007
39008     /**
39009      * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
39010      */
39011     disable : function(){
39012         if(this.tabPanel.active != this){
39013             this.disabled = true;
39014             this.status_node.addClass("disabled");
39015         }
39016     },
39017
39018     /**
39019      * Enables this TabPanelItem if it was previously disabled.
39020      */
39021     enable : function(){
39022         this.disabled = false;
39023         this.status_node.removeClass("disabled");
39024     },
39025
39026     /**
39027      * Sets the content for this TabPanelItem.
39028      * @param {String} content The content
39029      * @param {Boolean} loadScripts true to look for and load scripts
39030      */
39031     setContent : function(content, loadScripts){
39032         this.bodyEl.update(content, loadScripts);
39033     },
39034
39035     /**
39036      * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
39037      * @return {Roo.UpdateManager} The UpdateManager
39038      */
39039     getUpdateManager : function(){
39040         return this.bodyEl.getUpdateManager();
39041     },
39042
39043     /**
39044      * Set a URL to be used to load the content for this TabPanelItem.
39045      * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
39046      * @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)
39047      * @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)
39048      * @return {Roo.UpdateManager} The UpdateManager
39049      */
39050     setUrl : function(url, params, loadOnce){
39051         if(this.refreshDelegate){
39052             this.un('activate', this.refreshDelegate);
39053         }
39054         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
39055         this.on("activate", this.refreshDelegate);
39056         return this.bodyEl.getUpdateManager();
39057     },
39058
39059     /** @private */
39060     _handleRefresh : function(url, params, loadOnce){
39061         if(!loadOnce || !this.loaded){
39062             var updater = this.bodyEl.getUpdateManager();
39063             updater.update(url, params, this._setLoaded.createDelegate(this));
39064         }
39065     },
39066
39067     /**
39068      *   Forces a content refresh from the URL specified in the {@link #setUrl} method.
39069      *   Will fail silently if the setUrl method has not been called.
39070      *   This does not activate the panel, just updates its content.
39071      */
39072     refresh : function(){
39073         if(this.refreshDelegate){
39074            this.loaded = false;
39075            this.refreshDelegate();
39076         }
39077     },
39078
39079     /** @private */
39080     _setLoaded : function(){
39081         this.loaded = true;
39082     },
39083
39084     /** @private */
39085     closeClick : function(e){
39086         var o = {};
39087         e.stopEvent();
39088         this.fireEvent("beforeclose", this, o);
39089         if(o.cancel !== true){
39090             this.tabPanel.removeTab(this.id);
39091         }
39092     },
39093     /**
39094      * The text displayed in the tooltip for the close icon.
39095      * @type String
39096      */
39097     closeText : "Close this tab"
39098 });
39099 /**
39100 *    This script refer to:
39101 *    Title: International Telephone Input
39102 *    Author: Jack O'Connor
39103 *    Code version:  v12.1.12
39104 *    Availability: https://github.com/jackocnr/intl-tel-input.git
39105 **/
39106
39107 Roo.bootstrap.PhoneInputData = function() {
39108     var d = [
39109       [
39110         "Afghanistan (‫افغانستان‬‎)",
39111         "af",
39112         "93"
39113       ],
39114       [
39115         "Albania (Shqipëri)",
39116         "al",
39117         "355"
39118       ],
39119       [
39120         "Algeria (‫الجزائر‬‎)",
39121         "dz",
39122         "213"
39123       ],
39124       [
39125         "American Samoa",
39126         "as",
39127         "1684"
39128       ],
39129       [
39130         "Andorra",
39131         "ad",
39132         "376"
39133       ],
39134       [
39135         "Angola",
39136         "ao",
39137         "244"
39138       ],
39139       [
39140         "Anguilla",
39141         "ai",
39142         "1264"
39143       ],
39144       [
39145         "Antigua and Barbuda",
39146         "ag",
39147         "1268"
39148       ],
39149       [
39150         "Argentina",
39151         "ar",
39152         "54"
39153       ],
39154       [
39155         "Armenia (Հայաստան)",
39156         "am",
39157         "374"
39158       ],
39159       [
39160         "Aruba",
39161         "aw",
39162         "297"
39163       ],
39164       [
39165         "Australia",
39166         "au",
39167         "61",
39168         0
39169       ],
39170       [
39171         "Austria (Österreich)",
39172         "at",
39173         "43"
39174       ],
39175       [
39176         "Azerbaijan (Azərbaycan)",
39177         "az",
39178         "994"
39179       ],
39180       [
39181         "Bahamas",
39182         "bs",
39183         "1242"
39184       ],
39185       [
39186         "Bahrain (‫البحرين‬‎)",
39187         "bh",
39188         "973"
39189       ],
39190       [
39191         "Bangladesh (বাংলাদেশ)",
39192         "bd",
39193         "880"
39194       ],
39195       [
39196         "Barbados",
39197         "bb",
39198         "1246"
39199       ],
39200       [
39201         "Belarus (Беларусь)",
39202         "by",
39203         "375"
39204       ],
39205       [
39206         "Belgium (België)",
39207         "be",
39208         "32"
39209       ],
39210       [
39211         "Belize",
39212         "bz",
39213         "501"
39214       ],
39215       [
39216         "Benin (Bénin)",
39217         "bj",
39218         "229"
39219       ],
39220       [
39221         "Bermuda",
39222         "bm",
39223         "1441"
39224       ],
39225       [
39226         "Bhutan (འབྲུག)",
39227         "bt",
39228         "975"
39229       ],
39230       [
39231         "Bolivia",
39232         "bo",
39233         "591"
39234       ],
39235       [
39236         "Bosnia and Herzegovina (Босна и Херцеговина)",
39237         "ba",
39238         "387"
39239       ],
39240       [
39241         "Botswana",
39242         "bw",
39243         "267"
39244       ],
39245       [
39246         "Brazil (Brasil)",
39247         "br",
39248         "55"
39249       ],
39250       [
39251         "British Indian Ocean Territory",
39252         "io",
39253         "246"
39254       ],
39255       [
39256         "British Virgin Islands",
39257         "vg",
39258         "1284"
39259       ],
39260       [
39261         "Brunei",
39262         "bn",
39263         "673"
39264       ],
39265       [
39266         "Bulgaria (България)",
39267         "bg",
39268         "359"
39269       ],
39270       [
39271         "Burkina Faso",
39272         "bf",
39273         "226"
39274       ],
39275       [
39276         "Burundi (Uburundi)",
39277         "bi",
39278         "257"
39279       ],
39280       [
39281         "Cambodia (កម្ពុជា)",
39282         "kh",
39283         "855"
39284       ],
39285       [
39286         "Cameroon (Cameroun)",
39287         "cm",
39288         "237"
39289       ],
39290       [
39291         "Canada",
39292         "ca",
39293         "1",
39294         1,
39295         ["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"]
39296       ],
39297       [
39298         "Cape Verde (Kabu Verdi)",
39299         "cv",
39300         "238"
39301       ],
39302       [
39303         "Caribbean Netherlands",
39304         "bq",
39305         "599",
39306         1
39307       ],
39308       [
39309         "Cayman Islands",
39310         "ky",
39311         "1345"
39312       ],
39313       [
39314         "Central African Republic (République centrafricaine)",
39315         "cf",
39316         "236"
39317       ],
39318       [
39319         "Chad (Tchad)",
39320         "td",
39321         "235"
39322       ],
39323       [
39324         "Chile",
39325         "cl",
39326         "56"
39327       ],
39328       [
39329         "China (中国)",
39330         "cn",
39331         "86"
39332       ],
39333       [
39334         "Christmas Island",
39335         "cx",
39336         "61",
39337         2
39338       ],
39339       [
39340         "Cocos (Keeling) Islands",
39341         "cc",
39342         "61",
39343         1
39344       ],
39345       [
39346         "Colombia",
39347         "co",
39348         "57"
39349       ],
39350       [
39351         "Comoros (‫جزر القمر‬‎)",
39352         "km",
39353         "269"
39354       ],
39355       [
39356         "Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)",
39357         "cd",
39358         "243"
39359       ],
39360       [
39361         "Congo (Republic) (Congo-Brazzaville)",
39362         "cg",
39363         "242"
39364       ],
39365       [
39366         "Cook Islands",
39367         "ck",
39368         "682"
39369       ],
39370       [
39371         "Costa Rica",
39372         "cr",
39373         "506"
39374       ],
39375       [
39376         "Côte d’Ivoire",
39377         "ci",
39378         "225"
39379       ],
39380       [
39381         "Croatia (Hrvatska)",
39382         "hr",
39383         "385"
39384       ],
39385       [
39386         "Cuba",
39387         "cu",
39388         "53"
39389       ],
39390       [
39391         "Curaçao",
39392         "cw",
39393         "599",
39394         0
39395       ],
39396       [
39397         "Cyprus (Κύπρος)",
39398         "cy",
39399         "357"
39400       ],
39401       [
39402         "Czech Republic (Česká republika)",
39403         "cz",
39404         "420"
39405       ],
39406       [
39407         "Denmark (Danmark)",
39408         "dk",
39409         "45"
39410       ],
39411       [
39412         "Djibouti",
39413         "dj",
39414         "253"
39415       ],
39416       [
39417         "Dominica",
39418         "dm",
39419         "1767"
39420       ],
39421       [
39422         "Dominican Republic (República Dominicana)",
39423         "do",
39424         "1",
39425         2,
39426         ["809", "829", "849"]
39427       ],
39428       [
39429         "Ecuador",
39430         "ec",
39431         "593"
39432       ],
39433       [
39434         "Egypt (‫مصر‬‎)",
39435         "eg",
39436         "20"
39437       ],
39438       [
39439         "El Salvador",
39440         "sv",
39441         "503"
39442       ],
39443       [
39444         "Equatorial Guinea (Guinea Ecuatorial)",
39445         "gq",
39446         "240"
39447       ],
39448       [
39449         "Eritrea",
39450         "er",
39451         "291"
39452       ],
39453       [
39454         "Estonia (Eesti)",
39455         "ee",
39456         "372"
39457       ],
39458       [
39459         "Ethiopia",
39460         "et",
39461         "251"
39462       ],
39463       [
39464         "Falkland Islands (Islas Malvinas)",
39465         "fk",
39466         "500"
39467       ],
39468       [
39469         "Faroe Islands (Føroyar)",
39470         "fo",
39471         "298"
39472       ],
39473       [
39474         "Fiji",
39475         "fj",
39476         "679"
39477       ],
39478       [
39479         "Finland (Suomi)",
39480         "fi",
39481         "358",
39482         0
39483       ],
39484       [
39485         "France",
39486         "fr",
39487         "33"
39488       ],
39489       [
39490         "French Guiana (Guyane française)",
39491         "gf",
39492         "594"
39493       ],
39494       [
39495         "French Polynesia (Polynésie française)",
39496         "pf",
39497         "689"
39498       ],
39499       [
39500         "Gabon",
39501         "ga",
39502         "241"
39503       ],
39504       [
39505         "Gambia",
39506         "gm",
39507         "220"
39508       ],
39509       [
39510         "Georgia (საქართველო)",
39511         "ge",
39512         "995"
39513       ],
39514       [
39515         "Germany (Deutschland)",
39516         "de",
39517         "49"
39518       ],
39519       [
39520         "Ghana (Gaana)",
39521         "gh",
39522         "233"
39523       ],
39524       [
39525         "Gibraltar",
39526         "gi",
39527         "350"
39528       ],
39529       [
39530         "Greece (Ελλάδα)",
39531         "gr",
39532         "30"
39533       ],
39534       [
39535         "Greenland (Kalaallit Nunaat)",
39536         "gl",
39537         "299"
39538       ],
39539       [
39540         "Grenada",
39541         "gd",
39542         "1473"
39543       ],
39544       [
39545         "Guadeloupe",
39546         "gp",
39547         "590",
39548         0
39549       ],
39550       [
39551         "Guam",
39552         "gu",
39553         "1671"
39554       ],
39555       [
39556         "Guatemala",
39557         "gt",
39558         "502"
39559       ],
39560       [
39561         "Guernsey",
39562         "gg",
39563         "44",
39564         1
39565       ],
39566       [
39567         "Guinea (Guinée)",
39568         "gn",
39569         "224"
39570       ],
39571       [
39572         "Guinea-Bissau (Guiné Bissau)",
39573         "gw",
39574         "245"
39575       ],
39576       [
39577         "Guyana",
39578         "gy",
39579         "592"
39580       ],
39581       [
39582         "Haiti",
39583         "ht",
39584         "509"
39585       ],
39586       [
39587         "Honduras",
39588         "hn",
39589         "504"
39590       ],
39591       [
39592         "Hong Kong (香港)",
39593         "hk",
39594         "852"
39595       ],
39596       [
39597         "Hungary (Magyarország)",
39598         "hu",
39599         "36"
39600       ],
39601       [
39602         "Iceland (Ísland)",
39603         "is",
39604         "354"
39605       ],
39606       [
39607         "India (भारत)",
39608         "in",
39609         "91"
39610       ],
39611       [
39612         "Indonesia",
39613         "id",
39614         "62"
39615       ],
39616       [
39617         "Iran (‫ایران‬‎)",
39618         "ir",
39619         "98"
39620       ],
39621       [
39622         "Iraq (‫العراق‬‎)",
39623         "iq",
39624         "964"
39625       ],
39626       [
39627         "Ireland",
39628         "ie",
39629         "353"
39630       ],
39631       [
39632         "Isle of Man",
39633         "im",
39634         "44",
39635         2
39636       ],
39637       [
39638         "Israel (‫ישראל‬‎)",
39639         "il",
39640         "972"
39641       ],
39642       [
39643         "Italy (Italia)",
39644         "it",
39645         "39",
39646         0
39647       ],
39648       [
39649         "Jamaica",
39650         "jm",
39651         "1876"
39652       ],
39653       [
39654         "Japan (日本)",
39655         "jp",
39656         "81"
39657       ],
39658       [
39659         "Jersey",
39660         "je",
39661         "44",
39662         3
39663       ],
39664       [
39665         "Jordan (‫الأردن‬‎)",
39666         "jo",
39667         "962"
39668       ],
39669       [
39670         "Kazakhstan (Казахстан)",
39671         "kz",
39672         "7",
39673         1
39674       ],
39675       [
39676         "Kenya",
39677         "ke",
39678         "254"
39679       ],
39680       [
39681         "Kiribati",
39682         "ki",
39683         "686"
39684       ],
39685       [
39686         "Kosovo",
39687         "xk",
39688         "383"
39689       ],
39690       [
39691         "Kuwait (‫الكويت‬‎)",
39692         "kw",
39693         "965"
39694       ],
39695       [
39696         "Kyrgyzstan (Кыргызстан)",
39697         "kg",
39698         "996"
39699       ],
39700       [
39701         "Laos (ລາວ)",
39702         "la",
39703         "856"
39704       ],
39705       [
39706         "Latvia (Latvija)",
39707         "lv",
39708         "371"
39709       ],
39710       [
39711         "Lebanon (‫لبنان‬‎)",
39712         "lb",
39713         "961"
39714       ],
39715       [
39716         "Lesotho",
39717         "ls",
39718         "266"
39719       ],
39720       [
39721         "Liberia",
39722         "lr",
39723         "231"
39724       ],
39725       [
39726         "Libya (‫ليبيا‬‎)",
39727         "ly",
39728         "218"
39729       ],
39730       [
39731         "Liechtenstein",
39732         "li",
39733         "423"
39734       ],
39735       [
39736         "Lithuania (Lietuva)",
39737         "lt",
39738         "370"
39739       ],
39740       [
39741         "Luxembourg",
39742         "lu",
39743         "352"
39744       ],
39745       [
39746         "Macau (澳門)",
39747         "mo",
39748         "853"
39749       ],
39750       [
39751         "Macedonia (FYROM) (Македонија)",
39752         "mk",
39753         "389"
39754       ],
39755       [
39756         "Madagascar (Madagasikara)",
39757         "mg",
39758         "261"
39759       ],
39760       [
39761         "Malawi",
39762         "mw",
39763         "265"
39764       ],
39765       [
39766         "Malaysia",
39767         "my",
39768         "60"
39769       ],
39770       [
39771         "Maldives",
39772         "mv",
39773         "960"
39774       ],
39775       [
39776         "Mali",
39777         "ml",
39778         "223"
39779       ],
39780       [
39781         "Malta",
39782         "mt",
39783         "356"
39784       ],
39785       [
39786         "Marshall Islands",
39787         "mh",
39788         "692"
39789       ],
39790       [
39791         "Martinique",
39792         "mq",
39793         "596"
39794       ],
39795       [
39796         "Mauritania (‫موريتانيا‬‎)",
39797         "mr",
39798         "222"
39799       ],
39800       [
39801         "Mauritius (Moris)",
39802         "mu",
39803         "230"
39804       ],
39805       [
39806         "Mayotte",
39807         "yt",
39808         "262",
39809         1
39810       ],
39811       [
39812         "Mexico (México)",
39813         "mx",
39814         "52"
39815       ],
39816       [
39817         "Micronesia",
39818         "fm",
39819         "691"
39820       ],
39821       [
39822         "Moldova (Republica Moldova)",
39823         "md",
39824         "373"
39825       ],
39826       [
39827         "Monaco",
39828         "mc",
39829         "377"
39830       ],
39831       [
39832         "Mongolia (Монгол)",
39833         "mn",
39834         "976"
39835       ],
39836       [
39837         "Montenegro (Crna Gora)",
39838         "me",
39839         "382"
39840       ],
39841       [
39842         "Montserrat",
39843         "ms",
39844         "1664"
39845       ],
39846       [
39847         "Morocco (‫المغرب‬‎)",
39848         "ma",
39849         "212",
39850         0
39851       ],
39852       [
39853         "Mozambique (Moçambique)",
39854         "mz",
39855         "258"
39856       ],
39857       [
39858         "Myanmar (Burma) (မြန်မာ)",
39859         "mm",
39860         "95"
39861       ],
39862       [
39863         "Namibia (Namibië)",
39864         "na",
39865         "264"
39866       ],
39867       [
39868         "Nauru",
39869         "nr",
39870         "674"
39871       ],
39872       [
39873         "Nepal (नेपाल)",
39874         "np",
39875         "977"
39876       ],
39877       [
39878         "Netherlands (Nederland)",
39879         "nl",
39880         "31"
39881       ],
39882       [
39883         "New Caledonia (Nouvelle-Calédonie)",
39884         "nc",
39885         "687"
39886       ],
39887       [
39888         "New Zealand",
39889         "nz",
39890         "64"
39891       ],
39892       [
39893         "Nicaragua",
39894         "ni",
39895         "505"
39896       ],
39897       [
39898         "Niger (Nijar)",
39899         "ne",
39900         "227"
39901       ],
39902       [
39903         "Nigeria",
39904         "ng",
39905         "234"
39906       ],
39907       [
39908         "Niue",
39909         "nu",
39910         "683"
39911       ],
39912       [
39913         "Norfolk Island",
39914         "nf",
39915         "672"
39916       ],
39917       [
39918         "North Korea (조선 민주주의 인민 공화국)",
39919         "kp",
39920         "850"
39921       ],
39922       [
39923         "Northern Mariana Islands",
39924         "mp",
39925         "1670"
39926       ],
39927       [
39928         "Norway (Norge)",
39929         "no",
39930         "47",
39931         0
39932       ],
39933       [
39934         "Oman (‫عُمان‬‎)",
39935         "om",
39936         "968"
39937       ],
39938       [
39939         "Pakistan (‫پاکستان‬‎)",
39940         "pk",
39941         "92"
39942       ],
39943       [
39944         "Palau",
39945         "pw",
39946         "680"
39947       ],
39948       [
39949         "Palestine (‫فلسطين‬‎)",
39950         "ps",
39951         "970"
39952       ],
39953       [
39954         "Panama (Panamá)",
39955         "pa",
39956         "507"
39957       ],
39958       [
39959         "Papua New Guinea",
39960         "pg",
39961         "675"
39962       ],
39963       [
39964         "Paraguay",
39965         "py",
39966         "595"
39967       ],
39968       [
39969         "Peru (Perú)",
39970         "pe",
39971         "51"
39972       ],
39973       [
39974         "Philippines",
39975         "ph",
39976         "63"
39977       ],
39978       [
39979         "Poland (Polska)",
39980         "pl",
39981         "48"
39982       ],
39983       [
39984         "Portugal",
39985         "pt",
39986         "351"
39987       ],
39988       [
39989         "Puerto Rico",
39990         "pr",
39991         "1",
39992         3,
39993         ["787", "939"]
39994       ],
39995       [
39996         "Qatar (‫قطر‬‎)",
39997         "qa",
39998         "974"
39999       ],
40000       [
40001         "Réunion (La Réunion)",
40002         "re",
40003         "262",
40004         0
40005       ],
40006       [
40007         "Romania (România)",
40008         "ro",
40009         "40"
40010       ],
40011       [
40012         "Russia (Россия)",
40013         "ru",
40014         "7",
40015         0
40016       ],
40017       [
40018         "Rwanda",
40019         "rw",
40020         "250"
40021       ],
40022       [
40023         "Saint Barthélemy",
40024         "bl",
40025         "590",
40026         1
40027       ],
40028       [
40029         "Saint Helena",
40030         "sh",
40031         "290"
40032       ],
40033       [
40034         "Saint Kitts and Nevis",
40035         "kn",
40036         "1869"
40037       ],
40038       [
40039         "Saint Lucia",
40040         "lc",
40041         "1758"
40042       ],
40043       [
40044         "Saint Martin (Saint-Martin (partie française))",
40045         "mf",
40046         "590",
40047         2
40048       ],
40049       [
40050         "Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)",
40051         "pm",
40052         "508"
40053       ],
40054       [
40055         "Saint Vincent and the Grenadines",
40056         "vc",
40057         "1784"
40058       ],
40059       [
40060         "Samoa",
40061         "ws",
40062         "685"
40063       ],
40064       [
40065         "San Marino",
40066         "sm",
40067         "378"
40068       ],
40069       [
40070         "São Tomé and Príncipe (São Tomé e Príncipe)",
40071         "st",
40072         "239"
40073       ],
40074       [
40075         "Saudi Arabia (‫المملكة العربية السعودية‬‎)",
40076         "sa",
40077         "966"
40078       ],
40079       [
40080         "Senegal (Sénégal)",
40081         "sn",
40082         "221"
40083       ],
40084       [
40085         "Serbia (Србија)",
40086         "rs",
40087         "381"
40088       ],
40089       [
40090         "Seychelles",
40091         "sc",
40092         "248"
40093       ],
40094       [
40095         "Sierra Leone",
40096         "sl",
40097         "232"
40098       ],
40099       [
40100         "Singapore",
40101         "sg",
40102         "65"
40103       ],
40104       [
40105         "Sint Maarten",
40106         "sx",
40107         "1721"
40108       ],
40109       [
40110         "Slovakia (Slovensko)",
40111         "sk",
40112         "421"
40113       ],
40114       [
40115         "Slovenia (Slovenija)",
40116         "si",
40117         "386"
40118       ],
40119       [
40120         "Solomon Islands",
40121         "sb",
40122         "677"
40123       ],
40124       [
40125         "Somalia (Soomaaliya)",
40126         "so",
40127         "252"
40128       ],
40129       [
40130         "South Africa",
40131         "za",
40132         "27"
40133       ],
40134       [
40135         "South Korea (대한민국)",
40136         "kr",
40137         "82"
40138       ],
40139       [
40140         "South Sudan (‫جنوب السودان‬‎)",
40141         "ss",
40142         "211"
40143       ],
40144       [
40145         "Spain (España)",
40146         "es",
40147         "34"
40148       ],
40149       [
40150         "Sri Lanka (ශ්‍රී ලංකාව)",
40151         "lk",
40152         "94"
40153       ],
40154       [
40155         "Sudan (‫السودان‬‎)",
40156         "sd",
40157         "249"
40158       ],
40159       [
40160         "Suriname",
40161         "sr",
40162         "597"
40163       ],
40164       [
40165         "Svalbard and Jan Mayen",
40166         "sj",
40167         "47",
40168         1
40169       ],
40170       [
40171         "Swaziland",
40172         "sz",
40173         "268"
40174       ],
40175       [
40176         "Sweden (Sverige)",
40177         "se",
40178         "46"
40179       ],
40180       [
40181         "Switzerland (Schweiz)",
40182         "ch",
40183         "41"
40184       ],
40185       [
40186         "Syria (‫سوريا‬‎)",
40187         "sy",
40188         "963"
40189       ],
40190       [
40191         "Taiwan (台灣)",
40192         "tw",
40193         "886"
40194       ],
40195       [
40196         "Tajikistan",
40197         "tj",
40198         "992"
40199       ],
40200       [
40201         "Tanzania",
40202         "tz",
40203         "255"
40204       ],
40205       [
40206         "Thailand (ไทย)",
40207         "th",
40208         "66"
40209       ],
40210       [
40211         "Timor-Leste",
40212         "tl",
40213         "670"
40214       ],
40215       [
40216         "Togo",
40217         "tg",
40218         "228"
40219       ],
40220       [
40221         "Tokelau",
40222         "tk",
40223         "690"
40224       ],
40225       [
40226         "Tonga",
40227         "to",
40228         "676"
40229       ],
40230       [
40231         "Trinidad and Tobago",
40232         "tt",
40233         "1868"
40234       ],
40235       [
40236         "Tunisia (‫تونس‬‎)",
40237         "tn",
40238         "216"
40239       ],
40240       [
40241         "Turkey (Türkiye)",
40242         "tr",
40243         "90"
40244       ],
40245       [
40246         "Turkmenistan",
40247         "tm",
40248         "993"
40249       ],
40250       [
40251         "Turks and Caicos Islands",
40252         "tc",
40253         "1649"
40254       ],
40255       [
40256         "Tuvalu",
40257         "tv",
40258         "688"
40259       ],
40260       [
40261         "U.S. Virgin Islands",
40262         "vi",
40263         "1340"
40264       ],
40265       [
40266         "Uganda",
40267         "ug",
40268         "256"
40269       ],
40270       [
40271         "Ukraine (Україна)",
40272         "ua",
40273         "380"
40274       ],
40275       [
40276         "United Arab Emirates (‫الإمارات العربية المتحدة‬‎)",
40277         "ae",
40278         "971"
40279       ],
40280       [
40281         "United Kingdom",
40282         "gb",
40283         "44",
40284         0
40285       ],
40286       [
40287         "United States",
40288         "us",
40289         "1",
40290         0
40291       ],
40292       [
40293         "Uruguay",
40294         "uy",
40295         "598"
40296       ],
40297       [
40298         "Uzbekistan (Oʻzbekiston)",
40299         "uz",
40300         "998"
40301       ],
40302       [
40303         "Vanuatu",
40304         "vu",
40305         "678"
40306       ],
40307       [
40308         "Vatican City (Città del Vaticano)",
40309         "va",
40310         "39",
40311         1
40312       ],
40313       [
40314         "Venezuela",
40315         "ve",
40316         "58"
40317       ],
40318       [
40319         "Vietnam (Việt Nam)",
40320         "vn",
40321         "84"
40322       ],
40323       [
40324         "Wallis and Futuna (Wallis-et-Futuna)",
40325         "wf",
40326         "681"
40327       ],
40328       [
40329         "Western Sahara (‫الصحراء الغربية‬‎)",
40330         "eh",
40331         "212",
40332         1
40333       ],
40334       [
40335         "Yemen (‫اليمن‬‎)",
40336         "ye",
40337         "967"
40338       ],
40339       [
40340         "Zambia",
40341         "zm",
40342         "260"
40343       ],
40344       [
40345         "Zimbabwe",
40346         "zw",
40347         "263"
40348       ],
40349       [
40350         "Åland Islands",
40351         "ax",
40352         "358",
40353         1
40354       ]
40355   ];
40356   
40357   return d;
40358 }/**
40359 *    This script refer to:
40360 *    Title: International Telephone Input
40361 *    Author: Jack O'Connor
40362 *    Code version:  v12.1.12
40363 *    Availability: https://github.com/jackocnr/intl-tel-input.git
40364 **/
40365
40366 /**
40367  * @class Roo.bootstrap.PhoneInput
40368  * @extends Roo.bootstrap.TriggerField
40369  * An input with International dial-code selection
40370  
40371  * @cfg {String} defaultDialCode default '+852'
40372  * @cfg {Array} preferedCountries default []
40373   
40374  * @constructor
40375  * Create a new PhoneInput.
40376  * @param {Object} config Configuration options
40377  */
40378
40379 Roo.bootstrap.PhoneInput = function(config) {
40380     Roo.bootstrap.PhoneInput.superclass.constructor.call(this, config);
40381 };
40382
40383 Roo.extend(Roo.bootstrap.PhoneInput, Roo.bootstrap.TriggerField, {
40384         
40385         listWidth: undefined,
40386         
40387         selectedClass: 'active',
40388         
40389         invalidClass : "has-warning",
40390         
40391         validClass: 'has-success',
40392         
40393         allowed: '0123456789',
40394         
40395         max_length: 15,
40396         
40397         /**
40398          * @cfg {String} defaultDialCode The default dial code when initializing the input
40399          */
40400         defaultDialCode: '+852',
40401         
40402         /**
40403          * @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
40404          */
40405         preferedCountries: false,
40406         
40407         getAutoCreate : function()
40408         {
40409             var data = Roo.bootstrap.PhoneInputData();
40410             var align = this.labelAlign || this.parentLabelAlign();
40411             var id = Roo.id();
40412             
40413             this.allCountries = [];
40414             this.dialCodeMapping = [];
40415             
40416             for (var i = 0; i < data.length; i++) {
40417               var c = data[i];
40418               this.allCountries[i] = {
40419                 name: c[0],
40420                 iso2: c[1],
40421                 dialCode: c[2],
40422                 priority: c[3] || 0,
40423                 areaCodes: c[4] || null
40424               };
40425               this.dialCodeMapping[c[2]] = {
40426                   name: c[0],
40427                   iso2: c[1],
40428                   priority: c[3] || 0,
40429                   areaCodes: c[4] || null
40430               };
40431             }
40432             
40433             var cfg = {
40434                 cls: 'form-group',
40435                 cn: []
40436             };
40437             
40438             var input =  {
40439                 tag: 'input',
40440                 id : id,
40441                 // type: 'number', -- do not use number - we get the flaky up/down arrows.
40442                 maxlength: this.max_length,
40443                 cls : 'form-control tel-input',
40444                 autocomplete: 'new-password'
40445             };
40446             
40447             var hiddenInput = {
40448                 tag: 'input',
40449                 type: 'hidden',
40450                 cls: 'hidden-tel-input'
40451             };
40452             
40453             if (this.name) {
40454                 hiddenInput.name = this.name;
40455             }
40456             
40457             if (this.disabled) {
40458                 input.disabled = true;
40459             }
40460             
40461             var flag_container = {
40462                 tag: 'div',
40463                 cls: 'flag-box',
40464                 cn: [
40465                     {
40466                         tag: 'div',
40467                         cls: 'flag'
40468                     },
40469                     {
40470                         tag: 'div',
40471                         cls: 'caret'
40472                     }
40473                 ]
40474             };
40475             
40476             var box = {
40477                 tag: 'div',
40478                 cls: this.hasFeedback ? 'has-feedback' : '',
40479                 cn: [
40480                     hiddenInput,
40481                     input,
40482                     {
40483                         tag: 'input',
40484                         cls: 'dial-code-holder',
40485                         disabled: true
40486                     }
40487                 ]
40488             };
40489             
40490             var container = {
40491                 cls: 'roo-select2-container input-group',
40492                 cn: [
40493                     flag_container,
40494                     box
40495                 ]
40496             };
40497             
40498             if (this.fieldLabel.length) {
40499                 var indicator = {
40500                     tag: 'i',
40501                     tooltip: 'This field is required'
40502                 };
40503                 
40504                 var label = {
40505                     tag: 'label',
40506                     'for':  id,
40507                     cls: 'control-label',
40508                     cn: []
40509                 };
40510                 
40511                 var label_text = {
40512                     tag: 'span',
40513                     html: this.fieldLabel
40514                 };
40515                 
40516                 indicator.cls = 'roo-required-indicator text-danger fa fa-lg fa-star left-indicator';
40517                 label.cn = [
40518                     indicator,
40519                     label_text
40520                 ];
40521                 
40522                 if(this.indicatorpos == 'right') {
40523                     indicator.cls = 'roo-required-indicator text-danger fa fa-lg fa-star right-indicator';
40524                     label.cn = [
40525                         label_text,
40526                         indicator
40527                     ];
40528                 }
40529                 
40530                 if(align == 'left') {
40531                     container = {
40532                         tag: 'div',
40533                         cn: [
40534                             container
40535                         ]
40536                     };
40537                     
40538                     if(this.labelWidth > 12){
40539                         label.style = "width: " + this.labelWidth + 'px';
40540                     }
40541                     if(this.labelWidth < 13 && this.labelmd == 0){
40542                         this.labelmd = this.labelWidth;
40543                     }
40544                     if(this.labellg > 0){
40545                         label.cls += ' col-lg-' + this.labellg;
40546                         input.cls += ' col-lg-' + (12 - this.labellg);
40547                     }
40548                     if(this.labelmd > 0){
40549                         label.cls += ' col-md-' + this.labelmd;
40550                         container.cls += ' col-md-' + (12 - this.labelmd);
40551                     }
40552                     if(this.labelsm > 0){
40553                         label.cls += ' col-sm-' + this.labelsm;
40554                         container.cls += ' col-sm-' + (12 - this.labelsm);
40555                     }
40556                     if(this.labelxs > 0){
40557                         label.cls += ' col-xs-' + this.labelxs;
40558                         container.cls += ' col-xs-' + (12 - this.labelxs);
40559                     }
40560                 }
40561             }
40562             
40563             cfg.cn = [
40564                 label,
40565                 container
40566             ];
40567             
40568             var settings = this;
40569             
40570             ['xs','sm','md','lg'].map(function(size){
40571                 if (settings[size]) {
40572                     cfg.cls += ' col-' + size + '-' + settings[size];
40573                 }
40574             });
40575             
40576             this.store = new Roo.data.Store({
40577                 proxy : new Roo.data.MemoryProxy({}),
40578                 reader : new Roo.data.JsonReader({
40579                     fields : [
40580                         {
40581                             'name' : 'name',
40582                             'type' : 'string'
40583                         },
40584                         {
40585                             'name' : 'iso2',
40586                             'type' : 'string'
40587                         },
40588                         {
40589                             'name' : 'dialCode',
40590                             'type' : 'string'
40591                         },
40592                         {
40593                             'name' : 'priority',
40594                             'type' : 'string'
40595                         },
40596                         {
40597                             'name' : 'areaCodes',
40598                             'type' : 'string'
40599                         }
40600                     ]
40601                 })
40602             });
40603             
40604             if(!this.preferedCountries) {
40605                 this.preferedCountries = [
40606                     'hk',
40607                     'gb',
40608                     'us'
40609                 ];
40610             }
40611             
40612             var p = this.preferedCountries.reverse();
40613             
40614             if(p) {
40615                 for (var i = 0; i < p.length; i++) {
40616                     for (var j = 0; j < this.allCountries.length; j++) {
40617                         if(this.allCountries[j].iso2 == p[i]) {
40618                             var t = this.allCountries[j];
40619                             this.allCountries.splice(j,1);
40620                             this.allCountries.unshift(t);
40621                         }
40622                     } 
40623                 }
40624             }
40625             
40626             this.store.proxy.data = {
40627                 success: true,
40628                 data: this.allCountries
40629             };
40630             
40631             return cfg;
40632         },
40633         
40634         initEvents : function()
40635         {
40636             this.createList();
40637             Roo.bootstrap.PhoneInput.superclass.initEvents.call(this);
40638             
40639             this.indicator = this.indicatorEl();
40640             this.flag = this.flagEl();
40641             this.dialCodeHolder = this.dialCodeHolderEl();
40642             
40643             this.trigger = this.el.select('div.flag-box',true).first();
40644             this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
40645             
40646             var _this = this;
40647             
40648             (function(){
40649                 var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
40650                 _this.list.setWidth(lw);
40651             }).defer(100);
40652             
40653             this.list.on('mouseover', this.onViewOver, this);
40654             this.list.on('mousemove', this.onViewMove, this);
40655             this.inputEl().on("keyup", this.onKeyUp, this);
40656             this.inputEl().on("keypress", this.onKeyPress, this);
40657             
40658             this.tpl = '<li><a href="#"><div class="flag {iso2}"></div>{name} <span class="dial-code">+{dialCode}</span></a></li>';
40659
40660             this.view = new Roo.View(this.list, this.tpl, {
40661                 singleSelect:true, store: this.store, selectedClass: this.selectedClass
40662             });
40663             
40664             this.view.on('click', this.onViewClick, this);
40665             this.setValue(this.defaultDialCode);
40666         },
40667         
40668         onTriggerClick : function(e)
40669         {
40670             Roo.log('trigger click');
40671             if(this.disabled){
40672                 return;
40673             }
40674             
40675             if(this.isExpanded()){
40676                 this.collapse();
40677                 this.hasFocus = false;
40678             }else {
40679                 this.store.load({});
40680                 this.hasFocus = true;
40681                 this.expand();
40682             }
40683         },
40684         
40685         isExpanded : function()
40686         {
40687             return this.list.isVisible();
40688         },
40689         
40690         collapse : function()
40691         {
40692             if(!this.isExpanded()){
40693                 return;
40694             }
40695             this.list.hide();
40696             Roo.get(document).un('mousedown', this.collapseIf, this);
40697             Roo.get(document).un('mousewheel', this.collapseIf, this);
40698             this.fireEvent('collapse', this);
40699             this.validate();
40700         },
40701         
40702         expand : function()
40703         {
40704             Roo.log('expand');
40705
40706             if(this.isExpanded() || !this.hasFocus){
40707                 return;
40708             }
40709             
40710             var lw = this.listWidth || Math.max(this.inputEl().getWidth(), this.minListWidth);
40711             this.list.setWidth(lw);
40712             
40713             this.list.show();
40714             this.restrictHeight();
40715             
40716             Roo.get(document).on('mousedown', this.collapseIf, this);
40717             Roo.get(document).on('mousewheel', this.collapseIf, this);
40718             
40719             this.fireEvent('expand', this);
40720         },
40721         
40722         restrictHeight : function()
40723         {
40724             this.list.alignTo(this.inputEl(), this.listAlign);
40725             this.list.alignTo(this.inputEl(), this.listAlign);
40726         },
40727         
40728         onViewOver : function(e, t)
40729         {
40730             if(this.inKeyMode){
40731                 return;
40732             }
40733             var item = this.view.findItemFromChild(t);
40734             
40735             if(item){
40736                 var index = this.view.indexOf(item);
40737                 this.select(index, false);
40738             }
40739         },
40740
40741         // private
40742         onViewClick : function(view, doFocus, el, e)
40743         {
40744             var index = this.view.getSelectedIndexes()[0];
40745             
40746             var r = this.store.getAt(index);
40747             
40748             if(r){
40749                 this.onSelect(r, index);
40750             }
40751             if(doFocus !== false && !this.blockFocus){
40752                 this.inputEl().focus();
40753             }
40754         },
40755         
40756         onViewMove : function(e, t)
40757         {
40758             this.inKeyMode = false;
40759         },
40760         
40761         select : function(index, scrollIntoView)
40762         {
40763             this.selectedIndex = index;
40764             this.view.select(index);
40765             if(scrollIntoView !== false){
40766                 var el = this.view.getNode(index);
40767                 if(el){
40768                     this.list.scrollChildIntoView(el, false);
40769                 }
40770             }
40771         },
40772         
40773         createList : function()
40774         {
40775             this.list = Roo.get(document.body).createChild({
40776                 tag: 'ul',
40777                 cls: 'typeahead typeahead-long dropdown-menu tel-list',
40778                 style: 'display:none'
40779             });
40780             
40781             this.list.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
40782         },
40783         
40784         collapseIf : function(e)
40785         {
40786             var in_combo  = e.within(this.el);
40787             var in_list =  e.within(this.list);
40788             var is_list = (Roo.get(e.getTarget()).id == this.list.id) ? true : false;
40789             
40790             if (in_combo || in_list || is_list) {
40791                 return;
40792             }
40793             this.collapse();
40794         },
40795         
40796         onSelect : function(record, index)
40797         {
40798             if(this.fireEvent('beforeselect', this, record, index) !== false){
40799                 
40800                 this.setFlagClass(record.data.iso2);
40801                 this.setDialCode(record.data.dialCode);
40802                 this.hasFocus = false;
40803                 this.collapse();
40804                 this.fireEvent('select', this, record, index);
40805             }
40806         },
40807         
40808         flagEl : function()
40809         {
40810             var flag = this.el.select('div.flag',true).first();
40811             if(!flag){
40812                 return false;
40813             }
40814             return flag;
40815         },
40816         
40817         dialCodeHolderEl : function()
40818         {
40819             var d = this.el.select('input.dial-code-holder',true).first();
40820             if(!d){
40821                 return false;
40822             }
40823             return d;
40824         },
40825         
40826         setDialCode : function(v)
40827         {
40828             this.dialCodeHolder.dom.value = '+'+v;
40829         },
40830         
40831         setFlagClass : function(n)
40832         {
40833             this.flag.dom.className = 'flag '+n;
40834         },
40835         
40836         getValue : function()
40837         {
40838             var v = this.inputEl().getValue();
40839             if(this.dialCodeHolder) {
40840                 v = this.dialCodeHolder.dom.value+this.inputEl().getValue();
40841             }
40842             return v;
40843         },
40844         
40845         setValue : function(v)
40846         {
40847             var d = this.getDialCode(v);
40848             
40849             //invalid dial code
40850             if(v.length == 0 || !d || d.length == 0) {
40851                 if(this.rendered){
40852                     this.inputEl().dom.value = (v === null || v === undefined ? '' : v);
40853                     this.hiddenEl().dom.value = (v === null || v === undefined ? '' : v);
40854                 }
40855                 return;
40856             }
40857             
40858             //valid dial code
40859             this.setFlagClass(this.dialCodeMapping[d].iso2);
40860             this.setDialCode(d);
40861             this.inputEl().dom.value = v.replace('+'+d,'');
40862             this.hiddenEl().dom.value = this.getValue();
40863             
40864             this.validate();
40865         },
40866         
40867         getDialCode : function(v)
40868         {
40869             v = v ||  '';
40870             
40871             if (v.length == 0) {
40872                 return this.dialCodeHolder.dom.value;
40873             }
40874             
40875             var dialCode = "";
40876             if (v.charAt(0) != "+") {
40877                 return false;
40878             }
40879             var numericChars = "";
40880             for (var i = 1; i < v.length; i++) {
40881               var c = v.charAt(i);
40882               if (!isNaN(c)) {
40883                 numericChars += c;
40884                 if (this.dialCodeMapping[numericChars]) {
40885                   dialCode = v.substr(1, i);
40886                 }
40887                 if (numericChars.length == 4) {
40888                   break;
40889                 }
40890               }
40891             }
40892             return dialCode;
40893         },
40894         
40895         reset : function()
40896         {
40897             this.setValue(this.defaultDialCode);
40898             this.validate();
40899         },
40900         
40901         hiddenEl : function()
40902         {
40903             return this.el.select('input.hidden-tel-input',true).first();
40904         },
40905         
40906         // after setting val
40907         onKeyUp : function(e){
40908             this.setValue(this.getValue());
40909         },
40910         
40911         onKeyPress : function(e){
40912             if(this.allowed.indexOf(String.fromCharCode(e.getCharCode())) === -1){
40913                 e.stopEvent();
40914             }
40915         }
40916         
40917 });
40918 /**
40919  * @class Roo.bootstrap.MoneyField
40920  * @extends Roo.bootstrap.ComboBox
40921  * Bootstrap MoneyField class
40922  * 
40923  * @constructor
40924  * Create a new MoneyField.
40925  * @param {Object} config Configuration options
40926  */
40927
40928 Roo.bootstrap.MoneyField = function(config) {
40929     
40930     Roo.bootstrap.MoneyField.superclass.constructor.call(this, config);
40931     
40932 };
40933
40934 Roo.extend(Roo.bootstrap.MoneyField, Roo.bootstrap.ComboBox, {
40935     
40936     /**
40937      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
40938      */
40939     allowDecimals : true,
40940     /**
40941      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
40942      */
40943     decimalSeparator : ".",
40944     /**
40945      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
40946      */
40947     decimalPrecision : 0,
40948     /**
40949      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
40950      */
40951     allowNegative : true,
40952     /**
40953      * @cfg {Boolean} allowZero False to blank out if the user enters '0' (defaults to true)
40954      */
40955     allowZero: true,
40956     /**
40957      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
40958      */
40959     minValue : Number.NEGATIVE_INFINITY,
40960     /**
40961      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
40962      */
40963     maxValue : Number.MAX_VALUE,
40964     /**
40965      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
40966      */
40967     minText : "The minimum value for this field is {0}",
40968     /**
40969      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
40970      */
40971     maxText : "The maximum value for this field is {0}",
40972     /**
40973      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
40974      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
40975      */
40976     nanText : "{0} is not a valid number",
40977     /**
40978      * @cfg {Boolean} castInt (true|false) cast int if true (defalut true)
40979      */
40980     castInt : true,
40981     /**
40982      * @cfg {String} defaults currency of the MoneyField
40983      * value should be in lkey
40984      */
40985     defaultCurrency : false,
40986     /**
40987      * @cfg {String} thousandsDelimiter Symbol of thousandsDelimiter
40988      */
40989     thousandsDelimiter : false,
40990     /**
40991      * @cfg {Number} max_length Maximum input field length allowed (defaults to Number.MAX_VALUE)
40992      */
40993     max_length: false,
40994     
40995     inputlg : 9,
40996     inputmd : 9,
40997     inputsm : 9,
40998     inputxs : 6,
40999     
41000     store : false,
41001     
41002     getAutoCreate : function()
41003     {
41004         var align = this.labelAlign || this.parentLabelAlign();
41005         
41006         var id = Roo.id();
41007
41008         var cfg = {
41009             cls: 'form-group',
41010             cn: []
41011         };
41012
41013         var input =  {
41014             tag: 'input',
41015             id : id,
41016             cls : 'form-control roo-money-amount-input',
41017             autocomplete: 'new-password'
41018         };
41019         
41020         var hiddenInput = {
41021             tag: 'input',
41022             type: 'hidden',
41023             id: Roo.id(),
41024             cls: 'hidden-number-input'
41025         };
41026         
41027         if(this.max_length) {
41028             input.maxlength = this.max_length; 
41029         }
41030         
41031         if (this.name) {
41032             hiddenInput.name = this.name;
41033         }
41034
41035         if (this.disabled) {
41036             input.disabled = true;
41037         }
41038
41039         var clg = 12 - this.inputlg;
41040         var cmd = 12 - this.inputmd;
41041         var csm = 12 - this.inputsm;
41042         var cxs = 12 - this.inputxs;
41043         
41044         var container = {
41045             tag : 'div',
41046             cls : 'row roo-money-field',
41047             cn : [
41048                 {
41049                     tag : 'div',
41050                     cls : 'roo-money-currency column col-lg-' + clg + ' col-md-' + cmd + ' col-sm-' + csm + ' col-xs-' + cxs,
41051                     cn : [
41052                         {
41053                             tag : 'div',
41054                             cls: 'roo-select2-container input-group',
41055                             cn: [
41056                                 {
41057                                     tag : 'input',
41058                                     cls : 'form-control roo-money-currency-input',
41059                                     autocomplete: 'new-password',
41060                                     readOnly : 1,
41061                                     name : this.currencyName
41062                                 },
41063                                 {
41064                                     tag :'span',
41065                                     cls : 'input-group-addon',
41066                                     cn : [
41067                                         {
41068                                             tag: 'span',
41069                                             cls: 'caret'
41070                                         }
41071                                     ]
41072                                 }
41073                             ]
41074                         }
41075                     ]
41076                 },
41077                 {
41078                     tag : 'div',
41079                     cls : 'roo-money-amount column col-lg-' + this.inputlg + ' col-md-' + this.inputmd + ' col-sm-' + this.inputsm + ' col-xs-' + this.inputxs,
41080                     cn : [
41081                         {
41082                             tag: 'div',
41083                             cls: this.hasFeedback ? 'has-feedback' : '',
41084                             cn: [
41085                                 input
41086                             ]
41087                         }
41088                     ]
41089                 }
41090             ]
41091             
41092         };
41093         
41094         if (this.fieldLabel.length) {
41095             var indicator = {
41096                 tag: 'i',
41097                 tooltip: 'This field is required'
41098             };
41099
41100             var label = {
41101                 tag: 'label',
41102                 'for':  id,
41103                 cls: 'control-label',
41104                 cn: []
41105             };
41106
41107             var label_text = {
41108                 tag: 'span',
41109                 html: this.fieldLabel
41110             };
41111
41112             indicator.cls = 'roo-required-indicator text-danger fa fa-lg fa-star left-indicator';
41113             label.cn = [
41114                 indicator,
41115                 label_text
41116             ];
41117
41118             if(this.indicatorpos == 'right') {
41119                 indicator.cls = 'roo-required-indicator text-danger fa fa-lg fa-star right-indicator';
41120                 label.cn = [
41121                     label_text,
41122                     indicator
41123                 ];
41124             }
41125
41126             if(align == 'left') {
41127                 container = {
41128                     tag: 'div',
41129                     cn: [
41130                         container
41131                     ]
41132                 };
41133
41134                 if(this.labelWidth > 12){
41135                     label.style = "width: " + this.labelWidth + 'px';
41136                 }
41137                 if(this.labelWidth < 13 && this.labelmd == 0){
41138                     this.labelmd = this.labelWidth;
41139                 }
41140                 if(this.labellg > 0){
41141                     label.cls += ' col-lg-' + this.labellg;
41142                     input.cls += ' col-lg-' + (12 - this.labellg);
41143                 }
41144                 if(this.labelmd > 0){
41145                     label.cls += ' col-md-' + this.labelmd;
41146                     container.cls += ' col-md-' + (12 - this.labelmd);
41147                 }
41148                 if(this.labelsm > 0){
41149                     label.cls += ' col-sm-' + this.labelsm;
41150                     container.cls += ' col-sm-' + (12 - this.labelsm);
41151                 }
41152                 if(this.labelxs > 0){
41153                     label.cls += ' col-xs-' + this.labelxs;
41154                     container.cls += ' col-xs-' + (12 - this.labelxs);
41155                 }
41156             }
41157         }
41158
41159         cfg.cn = [
41160             label,
41161             container,
41162             hiddenInput
41163         ];
41164         
41165         var settings = this;
41166
41167         ['xs','sm','md','lg'].map(function(size){
41168             if (settings[size]) {
41169                 cfg.cls += ' col-' + size + '-' + settings[size];
41170             }
41171         });
41172         
41173         return cfg;
41174     },
41175     
41176     initEvents : function()
41177     {
41178         this.indicator = this.indicatorEl();
41179         
41180         this.initCurrencyEvent();
41181         
41182         this.initNumberEvent();
41183     },
41184     
41185     initCurrencyEvent : function()
41186     {
41187         if (!this.store) {
41188             throw "can not find store for combo";
41189         }
41190         
41191         this.store = Roo.factory(this.store, Roo.data);
41192         this.store.parent = this;
41193         
41194         this.createList();
41195         
41196         this.triggerEl = this.el.select('.input-group-addon', true).first();
41197         
41198         this.triggerEl.on("click", this.onTriggerClick, this, { preventDefault : true });
41199         
41200         var _this = this;
41201         
41202         (function(){
41203             var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
41204             _this.list.setWidth(lw);
41205         }).defer(100);
41206         
41207         this.list.on('mouseover', this.onViewOver, this);
41208         this.list.on('mousemove', this.onViewMove, this);
41209         this.list.on('scroll', this.onViewScroll, this);
41210         
41211         if(!this.tpl){
41212             this.tpl = '<li><a href="#">{' + this.currencyField + '}</a></li>';
41213         }
41214         
41215         this.view = new Roo.View(this.list, this.tpl, {
41216             singleSelect:true, store: this.store, selectedClass: this.selectedClass
41217         });
41218         
41219         this.view.on('click', this.onViewClick, this);
41220         
41221         this.store.on('beforeload', this.onBeforeLoad, this);
41222         this.store.on('load', this.onLoad, this);
41223         this.store.on('loadexception', this.onLoadException, this);
41224         
41225         this.keyNav = new Roo.KeyNav(this.currencyEl(), {
41226             "up" : function(e){
41227                 this.inKeyMode = true;
41228                 this.selectPrev();
41229             },
41230
41231             "down" : function(e){
41232                 if(!this.isExpanded()){
41233                     this.onTriggerClick();
41234                 }else{
41235                     this.inKeyMode = true;
41236                     this.selectNext();
41237                 }
41238             },
41239
41240             "enter" : function(e){
41241                 this.collapse();
41242                 
41243                 if(this.fireEvent("specialkey", this, e)){
41244                     this.onViewClick(false);
41245                 }
41246                 
41247                 return true;
41248             },
41249
41250             "esc" : function(e){
41251                 this.collapse();
41252             },
41253
41254             "tab" : function(e){
41255                 this.collapse();
41256                 
41257                 if(this.fireEvent("specialkey", this, e)){
41258                     this.onViewClick(false);
41259                 }
41260                 
41261                 return true;
41262             },
41263
41264             scope : this,
41265
41266             doRelay : function(foo, bar, hname){
41267                 if(hname == 'down' || this.scope.isExpanded()){
41268                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
41269                 }
41270                 return true;
41271             },
41272
41273             forceKeyDown: true
41274         });
41275         
41276         this.currencyEl().on("click", this.onTriggerClick, this, { preventDefault : true });
41277         
41278     },
41279     
41280     initNumberEvent : function(e)
41281     {
41282         this.inputEl().on("keydown" , this.fireKey,  this);
41283         this.inputEl().on("focus", this.onFocus,  this);
41284         this.inputEl().on("blur", this.onBlur,  this);
41285         
41286         this.inputEl().relayEvent('keyup', this);
41287         
41288         if(this.indicator){
41289             this.indicator.addClass('invisible');
41290         }
41291  
41292         this.originalValue = this.getValue();
41293         
41294         if(this.validationEvent == 'keyup'){
41295             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
41296             this.inputEl().on('keyup', this.filterValidation, this);
41297         }
41298         else if(this.validationEvent !== false){
41299             this.inputEl().on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
41300         }
41301         
41302         if(this.selectOnFocus){
41303             this.on("focus", this.preFocus, this);
41304             
41305         }
41306         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
41307             this.inputEl().on("keypress", this.filterKeys, this);
41308         } else {
41309             this.inputEl().relayEvent('keypress', this);
41310         }
41311         
41312         var allowed = "0123456789";
41313         
41314         if(this.allowDecimals){
41315             allowed += this.decimalSeparator;
41316         }
41317         
41318         if(this.allowNegative){
41319             allowed += "-";
41320         }
41321         
41322         if(this.thousandsDelimiter) {
41323             allowed += ",";
41324         }
41325         
41326         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
41327         
41328         var keyPress = function(e){
41329             
41330             var k = e.getKey();
41331             
41332             var c = e.getCharCode();
41333             
41334             if(
41335                     (String.fromCharCode(c) == '.' || String.fromCharCode(c) == '-') &&
41336                     allowed.indexOf(String.fromCharCode(c)) === -1
41337             ){
41338                 e.stopEvent();
41339                 return;
41340             }
41341             
41342             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
41343                 return;
41344             }
41345             
41346             if(allowed.indexOf(String.fromCharCode(c)) === -1){
41347                 e.stopEvent();
41348             }
41349         };
41350         
41351         this.inputEl().on("keypress", keyPress, this);
41352         
41353     },
41354     
41355     onTriggerClick : function(e)
41356     {   
41357         if(this.disabled){
41358             return;
41359         }
41360         
41361         this.page = 0;
41362         this.loadNext = false;
41363         
41364         if(this.isExpanded()){
41365             this.collapse();
41366             return;
41367         }
41368         
41369         this.hasFocus = true;
41370         
41371         if(this.triggerAction == 'all') {
41372             this.doQuery(this.allQuery, true);
41373             return;
41374         }
41375         
41376         this.doQuery(this.getRawValue());
41377     },
41378     
41379     getCurrency : function()
41380     {   
41381         var v = this.currencyEl().getValue();
41382         
41383         return v;
41384     },
41385     
41386     restrictHeight : function()
41387     {
41388         this.list.alignTo(this.currencyEl(), this.listAlign);
41389         this.list.alignTo(this.currencyEl(), this.listAlign);
41390     },
41391     
41392     onViewClick : function(view, doFocus, el, e)
41393     {
41394         var index = this.view.getSelectedIndexes()[0];
41395         
41396         var r = this.store.getAt(index);
41397         
41398         if(r){
41399             this.onSelect(r, index);
41400         }
41401     },
41402     
41403     onSelect : function(record, index){
41404         
41405         if(this.fireEvent('beforeselect', this, record, index) !== false){
41406         
41407             this.setFromCurrencyData(index > -1 ? record.data : false);
41408             
41409             this.collapse();
41410             
41411             this.fireEvent('select', this, record, index);
41412         }
41413     },
41414     
41415     setFromCurrencyData : function(o)
41416     {
41417         var currency = '';
41418         
41419         this.lastCurrency = o;
41420         
41421         if (this.currencyField) {
41422             currency = !o || typeof(o[this.currencyField]) == 'undefined' ? '' : o[this.currencyField];
41423         } else {
41424             Roo.log('no  currencyField value set for '+ (this.name ? this.name : this.id));
41425         }
41426         
41427         this.lastSelectionText = currency;
41428         
41429         //setting default currency
41430         if(o[this.currencyField] * 1 == 0 && this.defaultCurrency) {
41431             this.setCurrency(this.defaultCurrency);
41432             return;
41433         }
41434         
41435         this.setCurrency(currency);
41436     },
41437     
41438     setFromData : function(o)
41439     {
41440         var c = {};
41441         
41442         c[this.currencyField] = !o || typeof(o[this.currencyName]) == 'undefined' ? '' : o[this.currencyName];
41443         
41444         this.setFromCurrencyData(c);
41445         
41446         var value = '';
41447         
41448         if (this.name) {
41449             value = !o || typeof(o[this.name]) == 'undefined' ? '' : o[this.name];
41450         } else {
41451             Roo.log('no value set for '+ (this.name ? this.name : this.id));
41452         }
41453         
41454         this.setValue(value);
41455         
41456     },
41457     
41458     setCurrency : function(v)
41459     {   
41460         this.currencyValue = v;
41461         
41462         if(this.rendered){
41463             this.currencyEl().dom.value = (v === null || v === undefined ? '' : v);
41464             this.validate();
41465         }
41466     },
41467     
41468     setValue : function(v)
41469     {
41470         v = String(this.fixPrecision(v)).replace(".", this.decimalSeparator);
41471         
41472         this.value = v;
41473         
41474         if(this.rendered){
41475             
41476             this.hiddenEl().dom.value = (v === null || v === undefined ? '' : v);
41477             
41478             this.inputEl().dom.value = (v == '') ? '' :
41479                 Roo.util.Format.number(v, this.decimalPrecision, this.thousandsDelimiter || '');
41480             
41481             if(!this.allowZero && v === '0') {
41482                 this.hiddenEl().dom.value = '';
41483                 this.inputEl().dom.value = '';
41484             }
41485             
41486             this.validate();
41487         }
41488     },
41489     
41490     getRawValue : function()
41491     {
41492         var v = this.inputEl().getValue();
41493         
41494         return v;
41495     },
41496     
41497     getValue : function()
41498     {
41499         return this.fixPrecision(this.parseValue(this.getRawValue()));
41500     },
41501     
41502     parseValue : function(value)
41503     {
41504         if(this.thousandsDelimiter) {
41505             value += "";
41506             r = new RegExp(",", "g");
41507             value = value.replace(r, "");
41508         }
41509         
41510         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
41511         return isNaN(value) ? '' : value;
41512         
41513     },
41514     
41515     fixPrecision : function(value)
41516     {
41517         if(this.thousandsDelimiter) {
41518             value += "";
41519             r = new RegExp(",", "g");
41520             value = value.replace(r, "");
41521         }
41522         
41523         var nan = isNaN(value);
41524         
41525         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
41526             return nan ? '' : value;
41527         }
41528         return parseFloat(value).toFixed(this.decimalPrecision);
41529     },
41530     
41531     decimalPrecisionFcn : function(v)
41532     {
41533         return Math.floor(v);
41534     },
41535     
41536     validateValue : function(value)
41537     {
41538         if(!Roo.bootstrap.MoneyField.superclass.validateValue.call(this, value)){
41539             return false;
41540         }
41541         
41542         var num = this.parseValue(value);
41543         
41544         if(isNaN(num)){
41545             this.markInvalid(String.format(this.nanText, value));
41546             return false;
41547         }
41548         
41549         if(num < this.minValue){
41550             this.markInvalid(String.format(this.minText, this.minValue));
41551             return false;
41552         }
41553         
41554         if(num > this.maxValue){
41555             this.markInvalid(String.format(this.maxText, this.maxValue));
41556             return false;
41557         }
41558         
41559         return true;
41560     },
41561     
41562     validate : function()
41563     {
41564         if(this.disabled || this.allowBlank){
41565             this.markValid();
41566             return true;
41567         }
41568         
41569         var currency = this.getCurrency();
41570         
41571         if(this.validateValue(this.getRawValue()) && currency.length){
41572             this.markValid();
41573             return true;
41574         }
41575         
41576         this.markInvalid();
41577         return false;
41578     },
41579     
41580     getName: function()
41581     {
41582         return this.name;
41583     },
41584     
41585     beforeBlur : function()
41586     {
41587         if(!this.castInt){
41588             return;
41589         }
41590         
41591         var v = this.parseValue(this.getRawValue());
41592         
41593         if(v || v == 0){
41594             this.setValue(v);
41595         }
41596     },
41597     
41598     onBlur : function()
41599     {
41600         this.beforeBlur();
41601         
41602         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
41603             //this.el.removeClass(this.focusClass);
41604         }
41605         
41606         this.hasFocus = false;
41607         
41608         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
41609             this.validate();
41610         }
41611         
41612         var v = this.getValue();
41613         
41614         if(String(v) !== String(this.startValue)){
41615             this.fireEvent('change', this, v, this.startValue);
41616         }
41617         
41618         this.fireEvent("blur", this);
41619     },
41620     
41621     inputEl : function()
41622     {
41623         return this.el.select('.roo-money-amount-input', true).first();
41624     },
41625     
41626     currencyEl : function()
41627     {
41628         return this.el.select('.roo-money-currency-input', true).first();
41629     },
41630     
41631     hiddenEl : function()
41632     {
41633         return this.el.select('input.hidden-number-input',true).first();
41634     }
41635     
41636 });/**
41637  * @class Roo.bootstrap.BezierSignature
41638  * @extends Roo.bootstrap.Component
41639  * Bootstrap BezierSignature class
41640  * This script refer to:
41641  *    Title: Signature Pad
41642  *    Author: szimek
41643  *    Availability: https://github.com/szimek/signature_pad
41644  *
41645  * @constructor
41646  * Create a new BezierSignature
41647  * @param {Object} config The config object
41648  */
41649
41650 Roo.bootstrap.BezierSignature = function(config){
41651     Roo.bootstrap.BezierSignature.superclass.constructor.call(this, config);
41652     this.addEvents({
41653         "resize" : true
41654     });
41655 };
41656
41657 Roo.extend(Roo.bootstrap.BezierSignature, Roo.bootstrap.Component,
41658 {
41659      
41660     curve_data: [],
41661     
41662     is_empty: true,
41663     
41664     mouse_btn_down: true,
41665     
41666     /**
41667      * @cfg {int} canvas height
41668      */
41669     canvas_height: '200px',
41670     
41671     /**
41672      * @cfg {float|function} Radius of a single dot.
41673      */ 
41674     dot_size: false,
41675     
41676     /**
41677      * @cfg {float} Minimum width of a line. Defaults to 0.5.
41678      */
41679     min_width: 0.5,
41680     
41681     /**
41682      * @cfg {float} Maximum width of a line. Defaults to 2.5.
41683      */
41684     max_width: 2.5,
41685     
41686     /**
41687      * @cfg {integer} Draw the next point at most once per every x milliseconds. Set it to 0 to turn off throttling. Defaults to 16.
41688      */
41689     throttle: 16,
41690     
41691     /**
41692      * @cfg {integer} Add the next point only if the previous one is farther than x pixels. Defaults to 5.
41693      */
41694     min_distance: 5,
41695     
41696     /**
41697      * @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.
41698      */
41699     bg_color: 'rgba(0, 0, 0, 0)',
41700     
41701     /**
41702      * @cfg {string} Color used to draw the lines. Can be any color format accepted by context.fillStyle. Defaults to "black".
41703      */
41704     dot_color: 'black',
41705     
41706     /**
41707      * @cfg {float} Weight used to modify new velocity based on the previous velocity. Defaults to 0.7.
41708      */ 
41709     velocity_filter_weight: 0.7,
41710     
41711     /**
41712      * @cfg {function} Callback when stroke begin. 
41713      */
41714     onBegin: false,
41715     
41716     /**
41717      * @cfg {function} Callback when stroke end.
41718      */
41719     onEnd: false,
41720     
41721     getAutoCreate : function()
41722     {
41723         var cls = 'roo-signature column';
41724         
41725         if(this.cls){
41726             cls += ' ' + this.cls;
41727         }
41728         
41729         var col_sizes = [
41730             'lg',
41731             'md',
41732             'sm',
41733             'xs'
41734         ];
41735         
41736         for(var i = 0; i < col_sizes.length; i++) {
41737             if(this[col_sizes[i]]) {
41738                 cls += " col-"+col_sizes[i]+"-"+this[col_sizes[i]];
41739             }
41740         }
41741         
41742         var cfg = {
41743             tag: 'div',
41744             cls: cls,
41745             cn: [
41746                 {
41747                     tag: 'div',
41748                     cls: 'roo-signature-body',
41749                     cn: [
41750                         {
41751                             tag: 'canvas',
41752                             cls: 'roo-signature-body-canvas',
41753                             height: this.canvas_height,
41754                             width: this.canvas_width
41755                         }
41756                     ]
41757                 },
41758                 {
41759                     tag: 'input',
41760                     type: 'file',
41761                     style: 'display: none'
41762                 }
41763             ]
41764         };
41765         
41766         return cfg;
41767     },
41768     
41769     initEvents: function() 
41770     {
41771         Roo.bootstrap.BezierSignature.superclass.initEvents.call(this);
41772         
41773         var canvas = this.canvasEl();
41774         
41775         // mouse && touch event swapping...
41776         canvas.dom.style.touchAction = 'none';
41777         canvas.dom.style.msTouchAction = 'none';
41778         
41779         this.mouse_btn_down = false;
41780         canvas.on('mousedown', this._handleMouseDown, this);
41781         canvas.on('mousemove', this._handleMouseMove, this);
41782         Roo.select('html').first().on('mouseup', this._handleMouseUp, this);
41783         
41784         if (window.PointerEvent) {
41785             canvas.on('pointerdown', this._handleMouseDown, this);
41786             canvas.on('pointermove', this._handleMouseMove, this);
41787             Roo.select('html').first().on('pointerup', this._handleMouseUp, this);
41788         }
41789         
41790         if ('ontouchstart' in window) {
41791             canvas.on('touchstart', this._handleTouchStart, this);
41792             canvas.on('touchmove', this._handleTouchMove, this);
41793             canvas.on('touchend', this._handleTouchEnd, this);
41794         }
41795         
41796         Roo.EventManager.onWindowResize(this.resize, this, true);
41797         
41798         // file input event
41799         this.fileEl().on('change', this.uploadImage, this);
41800         
41801         this.clear();
41802         
41803         this.resize();
41804     },
41805     
41806     resize: function(){
41807         
41808         var canvas = this.canvasEl().dom;
41809         var ctx = this.canvasElCtx();
41810         var img_data = false;
41811         
41812         if(canvas.width > 0) {
41813             var img_data = ctx.getImageData(0, 0, canvas.width, canvas.height);
41814         }
41815         // setting canvas width will clean img data
41816         canvas.width = 0;
41817         
41818         var style = window.getComputedStyle ? 
41819             getComputedStyle(this.el.dom, null) : this.el.dom.currentStyle;
41820             
41821         var padding_left = parseInt(style.paddingLeft) || 0;
41822         var padding_right = parseInt(style.paddingRight) || 0;
41823         
41824         canvas.width = this.el.dom.clientWidth - padding_left - padding_right;
41825         
41826         if(img_data) {
41827             ctx.putImageData(img_data, 0, 0);
41828         }
41829     },
41830     
41831     _handleMouseDown: function(e)
41832     {
41833         if (e.browserEvent.which === 1) {
41834             this.mouse_btn_down = true;
41835             this.strokeBegin(e);
41836         }
41837     },
41838     
41839     _handleMouseMove: function (e)
41840     {
41841         if (this.mouse_btn_down) {
41842             this.strokeMoveUpdate(e);
41843         }
41844     },
41845     
41846     _handleMouseUp: function (e)
41847     {
41848         if (e.browserEvent.which === 1 && this.mouse_btn_down) {
41849             this.mouse_btn_down = false;
41850             this.strokeEnd(e);
41851         }
41852     },
41853     
41854     _handleTouchStart: function (e) {
41855         
41856         e.preventDefault();
41857         if (e.browserEvent.targetTouches.length === 1) {
41858             // var touch = e.browserEvent.changedTouches[0];
41859             // this.strokeBegin(touch);
41860             
41861              this.strokeBegin(e); // assume e catching the correct xy...
41862         }
41863     },
41864     
41865     _handleTouchMove: function (e) {
41866         e.preventDefault();
41867         // var touch = event.targetTouches[0];
41868         // _this._strokeMoveUpdate(touch);
41869         this.strokeMoveUpdate(e);
41870     },
41871     
41872     _handleTouchEnd: function (e) {
41873         var wasCanvasTouched = e.target === this.canvasEl().dom;
41874         if (wasCanvasTouched) {
41875             e.preventDefault();
41876             // var touch = event.changedTouches[0];
41877             // _this._strokeEnd(touch);
41878             this.strokeEnd(e);
41879         }
41880     },
41881     
41882     reset: function () {
41883         this._lastPoints = [];
41884         this._lastVelocity = 0;
41885         this._lastWidth = (this.min_width + this.max_width) / 2;
41886         this.canvasElCtx().fillStyle = this.dot_color;
41887     },
41888     
41889     strokeMoveUpdate: function(e)
41890     {
41891         this.strokeUpdate(e);
41892         
41893         if (this.throttle) {
41894             this.throttleStroke(this.strokeUpdate, this.throttle);
41895         }
41896         else {
41897             this.strokeUpdate(e);
41898         }
41899     },
41900     
41901     strokeBegin: function(e)
41902     {
41903         var newPointGroup = {
41904             color: this.dot_color,
41905             points: []
41906         };
41907         
41908         if (typeof this.onBegin === 'function') {
41909             this.onBegin(e);
41910         }
41911         
41912         this.curve_data.push(newPointGroup);
41913         this.reset();
41914         this.strokeUpdate(e);
41915     },
41916     
41917     strokeUpdate: function(e)
41918     {
41919         var rect = this.canvasEl().dom.getBoundingClientRect();
41920         var point = new this.Point(e.xy[0] - rect.left, e.xy[1] - rect.top, new Date().getTime());
41921         var lastPointGroup = this.curve_data[this.curve_data.length - 1];
41922         var lastPoints = lastPointGroup.points;
41923         var lastPoint = lastPoints.length > 0 && lastPoints[lastPoints.length - 1];
41924         var isLastPointTooClose = lastPoint
41925             ? point.distanceTo(lastPoint) <= this.min_distance
41926             : false;
41927         var color = lastPointGroup.color;
41928         if (!lastPoint || !(lastPoint && isLastPointTooClose)) {
41929             var curve = this.addPoint(point);
41930             if (!lastPoint) {
41931                 this.drawDot({color: color, point: point});
41932             }
41933             else if (curve) {
41934                 this.drawCurve({color: color, curve: curve});
41935             }
41936             lastPoints.push({
41937                 time: point.time,
41938                 x: point.x,
41939                 y: point.y
41940             });
41941         }
41942     },
41943     
41944     strokeEnd: function(e)
41945     {
41946         this.strokeUpdate(e);
41947         if (typeof this.onEnd === 'function') {
41948             this.onEnd(e);
41949         }
41950     },
41951     
41952     addPoint:  function (point) {
41953         var _lastPoints = this._lastPoints;
41954         _lastPoints.push(point);
41955         if (_lastPoints.length > 2) {
41956             if (_lastPoints.length === 3) {
41957                 _lastPoints.unshift(_lastPoints[0]);
41958             }
41959             var widths = this.calculateCurveWidths(_lastPoints[1], _lastPoints[2]);
41960             var curve = this.Bezier.fromPoints(_lastPoints, widths, this);
41961             _lastPoints.shift();
41962             return curve;
41963         }
41964         return null;
41965     },
41966     
41967     calculateCurveWidths: function (startPoint, endPoint) {
41968         var velocity = this.velocity_filter_weight * endPoint.velocityFrom(startPoint) +
41969             (1 - this.velocity_filter_weight) * this._lastVelocity;
41970
41971         var newWidth = Math.max(this.max_width / (velocity + 1), this.min_width);
41972         var widths = {
41973             end: newWidth,
41974             start: this._lastWidth
41975         };
41976         
41977         this._lastVelocity = velocity;
41978         this._lastWidth = newWidth;
41979         return widths;
41980     },
41981     
41982     drawDot: function (_a) {
41983         var color = _a.color, point = _a.point;
41984         var ctx = this.canvasElCtx();
41985         var width = typeof this.dot_size === 'function' ? this.dot_size() : this.dot_size;
41986         ctx.beginPath();
41987         this.drawCurveSegment(point.x, point.y, width);
41988         ctx.closePath();
41989         ctx.fillStyle = color;
41990         ctx.fill();
41991     },
41992     
41993     drawCurve: function (_a) {
41994         var color = _a.color, curve = _a.curve;
41995         var ctx = this.canvasElCtx();
41996         var widthDelta = curve.endWidth - curve.startWidth;
41997         var drawSteps = Math.floor(curve.length()) * 2;
41998         ctx.beginPath();
41999         ctx.fillStyle = color;
42000         for (var i = 0; i < drawSteps; i += 1) {
42001         var t = i / drawSteps;
42002         var tt = t * t;
42003         var ttt = tt * t;
42004         var u = 1 - t;
42005         var uu = u * u;
42006         var uuu = uu * u;
42007         var x = uuu * curve.startPoint.x;
42008         x += 3 * uu * t * curve.control1.x;
42009         x += 3 * u * tt * curve.control2.x;
42010         x += ttt * curve.endPoint.x;
42011         var y = uuu * curve.startPoint.y;
42012         y += 3 * uu * t * curve.control1.y;
42013         y += 3 * u * tt * curve.control2.y;
42014         y += ttt * curve.endPoint.y;
42015         var width = curve.startWidth + ttt * widthDelta;
42016         this.drawCurveSegment(x, y, width);
42017         }
42018         ctx.closePath();
42019         ctx.fill();
42020     },
42021     
42022     drawCurveSegment: function (x, y, width) {
42023         var ctx = this.canvasElCtx();
42024         ctx.moveTo(x, y);
42025         ctx.arc(x, y, width, 0, 2 * Math.PI, false);
42026         this.is_empty = false;
42027     },
42028     
42029     clear: function()
42030     {
42031         var ctx = this.canvasElCtx();
42032         var canvas = this.canvasEl().dom;
42033         ctx.fillStyle = this.bg_color;
42034         ctx.clearRect(0, 0, canvas.width, canvas.height);
42035         ctx.fillRect(0, 0, canvas.width, canvas.height);
42036         this.curve_data = [];
42037         this.reset();
42038         this.is_empty = true;
42039     },
42040     
42041     fileEl: function()
42042     {
42043         return  this.el.select('input',true).first();
42044     },
42045     
42046     canvasEl: function()
42047     {
42048         return this.el.select('canvas',true).first();
42049     },
42050     
42051     canvasElCtx: function()
42052     {
42053         return this.el.select('canvas',true).first().dom.getContext('2d');
42054     },
42055     
42056     getImage: function(type)
42057     {
42058         if(this.is_empty) {
42059             return false;
42060         }
42061         
42062         // encryption ?
42063         return this.canvasEl().dom.toDataURL('image/'+type, 1);
42064     },
42065     
42066     drawFromImage: function(img_src)
42067     {
42068         var img = new Image();
42069         
42070         img.onload = function(){
42071             this.canvasElCtx().drawImage(img, 0, 0);
42072         }.bind(this);
42073         
42074         img.src = img_src;
42075         
42076         this.is_empty = false;
42077     },
42078     
42079     selectImage: function()
42080     {
42081         this.fileEl().dom.click();
42082     },
42083     
42084     uploadImage: function(e)
42085     {
42086         var reader = new FileReader();
42087         
42088         reader.onload = function(e){
42089             var img = new Image();
42090             img.onload = function(){
42091                 this.reset();
42092                 this.canvasElCtx().drawImage(img, 0, 0);
42093             }.bind(this);
42094             img.src = e.target.result;
42095         }.bind(this);
42096         
42097         reader.readAsDataURL(e.target.files[0]);
42098     },
42099     
42100     // Bezier Point Constructor
42101     Point: (function () {
42102         function Point(x, y, time) {
42103             this.x = x;
42104             this.y = y;
42105             this.time = time || Date.now();
42106         }
42107         Point.prototype.distanceTo = function (start) {
42108             return Math.sqrt(Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2));
42109         };
42110         Point.prototype.equals = function (other) {
42111             return this.x === other.x && this.y === other.y && this.time === other.time;
42112         };
42113         Point.prototype.velocityFrom = function (start) {
42114             return this.time !== start.time
42115             ? this.distanceTo(start) / (this.time - start.time)
42116             : 0;
42117         };
42118         return Point;
42119     }()),
42120     
42121     
42122     // Bezier Constructor
42123     Bezier: (function () {
42124         function Bezier(startPoint, control2, control1, endPoint, startWidth, endWidth) {
42125             this.startPoint = startPoint;
42126             this.control2 = control2;
42127             this.control1 = control1;
42128             this.endPoint = endPoint;
42129             this.startWidth = startWidth;
42130             this.endWidth = endWidth;
42131         }
42132         Bezier.fromPoints = function (points, widths, scope) {
42133             var c2 = this.calculateControlPoints(points[0], points[1], points[2], scope).c2;
42134             var c3 = this.calculateControlPoints(points[1], points[2], points[3], scope).c1;
42135             return new Bezier(points[1], c2, c3, points[2], widths.start, widths.end);
42136         };
42137         Bezier.calculateControlPoints = function (s1, s2, s3, scope) {
42138             var dx1 = s1.x - s2.x;
42139             var dy1 = s1.y - s2.y;
42140             var dx2 = s2.x - s3.x;
42141             var dy2 = s2.y - s3.y;
42142             var m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };
42143             var m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };
42144             var l1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);
42145             var l2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);
42146             var dxm = m1.x - m2.x;
42147             var dym = m1.y - m2.y;
42148             var k = l2 / (l1 + l2);
42149             var cm = { x: m2.x + dxm * k, y: m2.y + dym * k };
42150             var tx = s2.x - cm.x;
42151             var ty = s2.y - cm.y;
42152             return {
42153                 c1: new scope.Point(m1.x + tx, m1.y + ty),
42154                 c2: new scope.Point(m2.x + tx, m2.y + ty)
42155             };
42156         };
42157         Bezier.prototype.length = function () {
42158             var steps = 10;
42159             var length = 0;
42160             var px;
42161             var py;
42162             for (var i = 0; i <= steps; i += 1) {
42163                 var t = i / steps;
42164                 var cx = this.point(t, this.startPoint.x, this.control1.x, this.control2.x, this.endPoint.x);
42165                 var cy = this.point(t, this.startPoint.y, this.control1.y, this.control2.y, this.endPoint.y);
42166                 if (i > 0) {
42167                     var xdiff = cx - px;
42168                     var ydiff = cy - py;
42169                     length += Math.sqrt(xdiff * xdiff + ydiff * ydiff);
42170                 }
42171                 px = cx;
42172                 py = cy;
42173             }
42174             return length;
42175         };
42176         Bezier.prototype.point = function (t, start, c1, c2, end) {
42177             return (start * (1.0 - t) * (1.0 - t) * (1.0 - t))
42178             + (3.0 * c1 * (1.0 - t) * (1.0 - t) * t)
42179             + (3.0 * c2 * (1.0 - t) * t * t)
42180             + (end * t * t * t);
42181         };
42182         return Bezier;
42183     }()),
42184     
42185     throttleStroke: function(fn, wait) {
42186       if (wait === void 0) { wait = 250; }
42187       var previous = 0;
42188       var timeout = null;
42189       var result;
42190       var storedContext;
42191       var storedArgs;
42192       var later = function () {
42193           previous = Date.now();
42194           timeout = null;
42195           result = fn.apply(storedContext, storedArgs);
42196           if (!timeout) {
42197               storedContext = null;
42198               storedArgs = [];
42199           }
42200       };
42201       return function wrapper() {
42202           var args = [];
42203           for (var _i = 0; _i < arguments.length; _i++) {
42204               args[_i] = arguments[_i];
42205           }
42206           var now = Date.now();
42207           var remaining = wait - (now - previous);
42208           storedContext = this;
42209           storedArgs = args;
42210           if (remaining <= 0 || remaining > wait) {
42211               if (timeout) {
42212                   clearTimeout(timeout);
42213                   timeout = null;
42214               }
42215               previous = now;
42216               result = fn.apply(storedContext, storedArgs);
42217               if (!timeout) {
42218                   storedContext = null;
42219                   storedArgs = [];
42220               }
42221           }
42222           else if (!timeout) {
42223               timeout = window.setTimeout(later, remaining);
42224           }
42225           return result;
42226       };
42227   }
42228   
42229 });
42230
42231  
42232
42233