css-bootstrap/roojs-bootstrap-debug.css.map
[roojs1] / roojs-bootstrap-debug.js
1 /*
2  * - LGPL
3  *
4  * base class for bootstrap elements.
5  * 
6  */
7
8 Roo.bootstrap = Roo.bootstrap || {};
9 /**
10  * @class Roo.bootstrap.Component
11  * @extends Roo.Component
12  * Bootstrap Component base class
13  * @cfg {String} cls css class
14  * @cfg {String} style any extra css
15  * @cfg {Object} xattr extra attributes to add to 'element' (used by builder to store stuff.)
16  * @cfg {Boolean} can_build_overlaid  True if element can be rebuild from a HTML page
17  * @cfg {string} dataId cutomer id
18  * @cfg {string} name Specifies name attribute
19  * @cfg {string} tooltip  Text for the tooltip
20  * @cfg {string} container_method method to fetch parents container element (used by NavHeaderbar -  getHeaderChildContainer)
21  * 
22  * @constructor
23  * Do not use directly - it does not do anything..
24  * @param {Object} config The config object
25  */
26
27
28
29 Roo.bootstrap.Component = function(config){
30     Roo.bootstrap.Component.superclass.constructor.call(this, config);
31        
32     this.addEvents({
33         /**
34          * @event childrenrendered
35          * Fires when the children have been rendered..
36          * @param {Roo.bootstrap.Component} this
37          */
38         "childrenrendered" : true
39         
40         
41         
42     });
43     
44     
45 };
46
47 Roo.extend(Roo.bootstrap.Component, Roo.BoxComponent,  {
48     
49     
50     allowDomMove : false, // to stop relocations in parent onRender...
51     
52     cls : false,
53     
54     style : false,
55     
56     autoCreate : false,
57     
58     tooltip : null,
59     /**
60      * Initialize Events for the element
61      */
62     initEvents : function() { },
63     
64     xattr : false,
65     
66     parentId : false,
67     
68     can_build_overlaid : true,
69     
70     container_method : false,
71     
72     dataId : false,
73     
74     name : false,
75     
76     parent: function() {
77         // returns the parent component..
78         return Roo.ComponentMgr.get(this.parentId)
79         
80         
81     },
82     
83     // private
84     onRender : function(ct, position)
85     {
86        // Roo.log("Call onRender: " + this.xtype);
87         
88         Roo.bootstrap.Component.superclass.onRender.call(this, ct, position);
89         
90         if(this.el){
91             if (this.el.attr('xtype')) {
92                 this.el.attr('xtypex', this.el.attr('xtype'));
93                 this.el.dom.removeAttribute('xtype');
94                 
95                 this.initEvents();
96             }
97             
98             return;
99         }
100         
101          
102         
103         var cfg = Roo.apply({},  this.getAutoCreate());
104         
105         cfg.id = this.id || Roo.id();
106         
107         // fill in the extra attributes 
108         if (this.xattr && typeof(this.xattr) =='object') {
109             for (var i in this.xattr) {
110                 cfg[i] = this.xattr[i];
111             }
112         }
113         
114         if(this.dataId){
115             cfg.dataId = this.dataId;
116         }
117         
118         if (this.cls) {
119             cfg.cls = (typeof(cfg.cls) == 'undefined') ? this.cls : cfg.cls + ' ' + this.cls;
120         }
121         
122         if (this.style) { // fixme needs to support more complex style data.
123             cfg.style = this.style;
124         }
125         
126         if(this.name){
127             cfg.name = this.name;
128         }
129         
130         this.el = ct.createChild(cfg, position);
131         
132         if (this.tooltip) {
133             this.tooltipEl().attr('tooltip', this.tooltip);
134         }
135         
136         if(this.tabIndex !== undefined){
137             this.el.dom.setAttribute('tabIndex', this.tabIndex);
138         }
139         
140         this.initEvents();
141         
142     },
143     /**
144      * Fetch the element to add children to
145      * @return {Roo.Element} defaults to this.el
146      */
147     getChildContainer : function()
148     {
149         return this.el;
150     },
151     /**
152      * Fetch the element to display the tooltip on.
153      * @return {Roo.Element} defaults to this.el
154      */
155     tooltipEl : function()
156     {
157         return this.el;
158     },
159         
160     addxtype  : function(tree,cntr)
161     {
162         var cn = this;
163         
164         cn = Roo.factory(tree);
165         //Roo.log(['addxtype', cn]);
166            
167         cn.parentType = this.xtype; //??
168         cn.parentId = this.id;
169         
170         cntr = (typeof(cntr) == 'undefined' ) ? 'getChildContainer' : cntr;
171         if (typeof(cn.container_method) == 'string') {
172             cntr = cn.container_method;
173         }
174         
175         
176         var has_flexy_each =  (typeof(tree['flexy:foreach']) != 'undefined');
177         
178         var has_flexy_if =  (typeof(tree['flexy:if']) != 'undefined');
179         
180         var build_from_html =  Roo.XComponent.build_from_html;
181           
182         var is_body  = (tree.xtype == 'Body') ;
183           
184         var page_has_body = (Roo.get(document.body).attr('xtype') == 'Roo.bootstrap.Body');
185           
186         var self_cntr_el = Roo.get(this[cntr](false));
187         
188         // do not try and build conditional elements 
189         if ((has_flexy_each || has_flexy_if || this.can_build_overlaid == false ) && build_from_html) {
190             return false;
191         }
192         
193         if (!has_flexy_each || !build_from_html || is_body || !page_has_body) {
194             if(!has_flexy_if || typeof(tree.name) == 'undefined' || !build_from_html || is_body || !page_has_body){
195                 return this.addxtypeChild(tree,cntr, is_body);
196             }
197             
198             var echild =self_cntr_el ? self_cntr_el.child('>*[name=' + tree.name + ']') : false;
199                 
200             if(echild){
201                 return this.addxtypeChild(Roo.apply({}, tree),cntr);
202             }
203             
204             Roo.log('skipping render');
205             return cn;
206             
207         }
208         
209         var ret = false;
210         if (!build_from_html) {
211             return false;
212         }
213         
214         // this i think handles overlaying multiple children of the same type
215         // with the sam eelement.. - which might be buggy..
216         while (true) {
217             var echild =self_cntr_el ? self_cntr_el.child('>*[xtype]') : false;
218             
219             if (!echild) {
220                 break;
221             }
222             
223             if (echild && echild.attr('xtype').split('.').pop() != cn.xtype) {
224                 break;
225             }
226             
227             ret = this.addxtypeChild(Roo.apply({}, tree),cntr);
228         }
229        
230         return ret;
231     },
232     
233     
234     addxtypeChild : function (tree, cntr, is_body)
235     {
236         Roo.debug && Roo.log('addxtypeChild:' + cntr);
237         var cn = this;
238         cntr = (typeof(cntr) == 'undefined' ) ? 'getChildContainer' : cntr;
239         
240         
241         var has_flexy = (typeof(tree['flexy:if']) != 'undefined') ||
242                     (typeof(tree['flexy:foreach']) != 'undefined');
243           
244         
245         
246          skip_children = false;
247         // render the element if it's not BODY.
248         if (!is_body) {
249            
250             cn = Roo.factory(tree);
251            
252             cn.parentType = this.xtype; //??
253             cn.parentId = this.id;
254             
255             var build_from_html =  Roo.XComponent.build_from_html;
256             
257             
258             // does the container contain child eleemnts with 'xtype' attributes.
259             // that match this xtype..
260             // note - when we render we create these as well..
261             // so we should check to see if body has xtype set.
262             if (build_from_html && Roo.get(document.body).attr('xtype') == 'Roo.bootstrap.Body') {
263                
264                 var self_cntr_el = Roo.get(this[cntr](false));
265                 var echild =self_cntr_el ? self_cntr_el.child('>*[xtype]') : false;
266                 if (echild) { 
267                     //Roo.log(Roo.XComponent.build_from_html);
268                     //Roo.log("got echild:");
269                     //Roo.log(echild);
270                 }
271                 // there is a scenario where some of the child elements are flexy:if (and all of the same type)
272                 // and are not displayed -this causes this to use up the wrong element when matching.
273                 // at present the only work around for this is to nest flexy:if elements in another element that is always rendered.
274                 
275                 
276                 if (echild && echild.attr('xtype').split('.').pop() == cn.xtype) {
277                   //  Roo.log("found child for " + this.xtype +": " + echild.attr('xtype') );
278                   
279                   
280                   
281                     cn.el = echild;
282                   //  Roo.log("GOT");
283                     //echild.dom.removeAttribute('xtype');
284                 } else {
285                     Roo.debug && Roo.log("MISSING " + cn.xtype + " on child of " + (this.el ? this.el.attr('xbuilderid') : 'no parent'));
286                     Roo.debug && Roo.log(self_cntr_el);
287                     Roo.debug && Roo.log(echild);
288                     Roo.debug && Roo.log(cn);
289                 }
290             }
291            
292             
293            
294             // if object has flexy:if - then it may or may not be rendered.
295             if (build_from_html && has_flexy && !cn.el &&  cn.can_build_overlaid) {
296                 // skip a flexy if element.
297                 Roo.debug && Roo.log('skipping render');
298                 Roo.debug && Roo.log(tree);
299                 if (!cn.el) {
300                     Roo.debug && Roo.log('skipping all children');
301                     skip_children = true;
302                 }
303                 
304              } else {
305                  
306                 // actually if flexy:foreach is found, we really want to create 
307                 // multiple copies here...
308                 //Roo.log('render');
309                 //Roo.log(this[cntr]());
310                 // some elements do not have render methods.. like the layouts...
311                 cn.render && cn.render(this[cntr](true));
312              }
313             // then add the element..
314         }
315         
316         
317         // handle the kids..
318         
319         var nitems = [];
320         /*
321         if (typeof (tree.menu) != 'undefined') {
322             tree.menu.parentType = cn.xtype;
323             tree.menu.triggerEl = cn.el;
324             nitems.push(cn.addxtype(Roo.apply({}, tree.menu)));
325             
326         }
327         */
328         if (!tree.items || !tree.items.length) {
329             cn.items = nitems;
330             //Roo.log(["no children", this]);
331             
332             return cn;
333         }
334          
335         var items = tree.items;
336         delete tree.items;
337         
338         //Roo.log(items.length);
339             // add the items..
340         if (!skip_children) {    
341             for(var i =0;i < items.length;i++) {
342               //  Roo.log(['add child', items[i]]);
343                 nitems.push(cn.addxtype(Roo.apply({}, items[i])));
344             }
345         }
346         
347         cn.items = nitems;
348         
349         //Roo.log("fire childrenrendered");
350         
351         cn.fireEvent('childrenrendered', this);
352         
353         return cn;
354     },
355     /**
356      * Show a component - removes 'hidden' class
357      */
358     show : function()
359     {
360         if (this.el) {
361             this.el.removeClass('hidden');
362         }
363     },
364     /**
365      * Hide a component - adds 'hidden' class
366      */
367     hide: function()
368     {
369         if (this.el && !this.el.hasClass('hidden')) {
370             this.el.addClass('hidden');
371         }
372     }
373 });
374
375  /*
376  * - LGPL
377  *
378  * Body
379  *
380  */
381
382 /**
383  * @class Roo.bootstrap.Body
384  * @extends Roo.bootstrap.Component
385  * Bootstrap Body class
386  *
387  * @constructor
388  * Create a new body
389  * @param {Object} config The config object
390  */
391
392 Roo.bootstrap.Body = function(config){
393
394     config = config || {};
395
396     Roo.bootstrap.Body.superclass.constructor.call(this, config);
397     this.el = Roo.get(config.el ? config.el : document.body );
398     if (this.cls && this.cls.length) {
399         Roo.get(document.body).addClass(this.cls);
400     }
401 };
402
403 Roo.extend(Roo.bootstrap.Body, Roo.bootstrap.Component,  {
404
405     is_body : true,// just to make sure it's constructed?
406
407         autoCreate : {
408         cls: 'container'
409     },
410     onRender : function(ct, position)
411     {
412        /* Roo.log("Roo.bootstrap.Body - onRender");
413         if (this.cls && this.cls.length) {
414             Roo.get(document.body).addClass(this.cls);
415         }
416         // style??? xttr???
417         */
418     }
419
420
421
422
423 });
424 /*
425  * - LGPL
426  *
427  * button group
428  * 
429  */
430
431
432 /**
433  * @class Roo.bootstrap.ButtonGroup
434  * @extends Roo.bootstrap.Component
435  * Bootstrap ButtonGroup class
436  * @cfg {String} size lg | sm | xs (default empty normal)
437  * @cfg {String} align vertical | justified  (default none)
438  * @cfg {String} direction up | down (default down)
439  * @cfg {Boolean} toolbar false | true
440  * @cfg {Boolean} btn true | false
441  * 
442  * 
443  * @constructor
444  * Create a new Input
445  * @param {Object} config The config object
446  */
447
448 Roo.bootstrap.ButtonGroup = function(config){
449     Roo.bootstrap.ButtonGroup.superclass.constructor.call(this, config);
450 };
451
452 Roo.extend(Roo.bootstrap.ButtonGroup, Roo.bootstrap.Component,  {
453     
454     size: '',
455     align: '',
456     direction: '',
457     toolbar: false,
458     btn: true,
459
460     getAutoCreate : function(){
461         var cfg = {
462             cls: 'btn-group',
463             html : null
464         };
465         
466         cfg.html = this.html || cfg.html;
467         
468         if (this.toolbar) {
469             cfg = {
470                 cls: 'btn-toolbar',
471                 html: null
472             };
473             
474             return cfg;
475         }
476         
477         if (['vertical','justified'].indexOf(this.align)!==-1) {
478             cfg.cls = 'btn-group-' + this.align;
479             
480             if (this.align == 'justified') {
481                 console.log(this.items);
482             }
483         }
484         
485         if (['lg','sm','xs'].indexOf(this.size)!==-1) {
486             cfg.cls += ' btn-group-' + this.size;
487         }
488         
489         if (this.direction == 'up') {
490             cfg.cls += ' dropup' ;
491         }
492         
493         return cfg;
494     }
495    
496 });
497
498  /*
499  * - LGPL
500  *
501  * button
502  * 
503  */
504
505 /**
506  * @class Roo.bootstrap.Button
507  * @extends Roo.bootstrap.Component
508  * Bootstrap Button class
509  * @cfg {String} html The button content
510  * @cfg {String} weight (default | primary | success | info | warning | danger | link ) default 
511  * @cfg {String} size ( lg | sm | xs)
512  * @cfg {String} tag ( a | input | submit)
513  * @cfg {String} href empty or href
514  * @cfg {Boolean} disabled default false;
515  * @cfg {Boolean} isClose default false;
516  * @cfg {String} glyphicon (| adjust | align-center | align-justify | align-left | align-right | arrow-down | arrow-left | arrow-right | arrow-up | asterisk | backward | ban-circle | barcode | bell | bold | book | bookmark | briefcase | bullhorn | calendar | camera | certificate | check | chevron-down | chevron-left | chevron-right | chevron-up | circle-arrow-down | circle-arrow-left | circle-arrow-right | circle-arrow-up | cloud | cloud-download | cloud-upload | cog | collapse-down | collapse-up | comment | compressed | copyright-mark | credit-card | cutlery | dashboard | download | download-alt | earphone | edit | eject | envelope | euro | exclamation-sign | expand | export | eye-close | eye-open | facetime-video | fast-backward | fast-forward | file | film | filter | fire | flag | flash | floppy-disk | floppy-open | floppy-remove | floppy-save | floppy-saved | folder-close | folder-open | font | forward | fullscreen | gbp | gift | glass | globe | hand-down | hand-left | hand-right | hand-up | hd-video | hdd | header | headphones | heart | heart-empty | home | import | inbox | indent-left | indent-right | info-sign | italic | leaf | link | list | list-alt | lock | log-in | log-out | magnet | map-marker | minus | minus-sign | move | music | new-window | off | ok | ok-circle | ok-sign | open | paperclip | pause | pencil | phone | phone-alt | picture | plane | play | play-circle | plus | plus-sign | print | pushpin | qrcode | question-sign | random | record | refresh | registration-mark | remove | remove-circle | remove-sign | repeat | resize-full | resize-horizontal | resize-small | resize-vertical | retweet | road | save | saved | screenshot | sd-video | search | send | share | share-alt | shopping-cart | signal | sort | sort-by-alphabet | sort-by-alphabet-alt | sort-by-attributes | sort-by-attributes-alt | sort-by-order | sort-by-order-alt | sound-5-1 | sound-6-1 | sound-7-1 | sound-dolby | sound-stereo | star | star-empty | stats | step-backward | step-forward | stop | subtitles | tag | tags | tasks | text-height | text-width | th | th-large | th-list | thumbs-down | thumbs-up | time | tint | tower | transfer | trash | tree-conifer | tree-deciduous | unchecked | upload | usd | user | volume-down | volume-off | volume-up | warning-sign | wrench | zoom-in | zoom-out)
517  * @cfg {String} badge text for badge
518  * @cfg {String} theme default 
519  * @cfg {Boolean} inverse 
520  * @cfg {Boolean} toggle 
521  * @cfg {String} ontext text for on toggle state
522  * @cfg {String} offtext text for off toggle state
523  * @cfg {Boolean} defaulton 
524  * @cfg {Boolean} preventDefault  default true
525  * @cfg {Boolean} removeClass remove the standard class..
526  * @cfg {String} target  target for a href. (_self|_blank|_parent|_top| other)
527  * 
528  * @constructor
529  * Create a new button
530  * @param {Object} config The config object
531  */
532
533
534 Roo.bootstrap.Button = function(config){
535     Roo.bootstrap.Button.superclass.constructor.call(this, config);
536     this.weightClass = ["btn-default", 
537                        "btn-primary", 
538                        "btn-success", 
539                        "btn-info", 
540                        "btn-warning",
541                        "btn-danger",
542                        "btn-link"
543                       ],  
544     this.addEvents({
545         // raw events
546         /**
547          * @event click
548          * When a butotn is pressed
549          * @param {Roo.bootstrap.Button} this
550          * @param {Roo.EventObject} e
551          */
552         "click" : true,
553          /**
554          * @event toggle
555          * After the button has been toggles
556          * @param {Roo.EventObject} e
557          * @param {boolean} pressed (also available as button.pressed)
558          */
559         "toggle" : true
560     });
561 };
562
563 Roo.extend(Roo.bootstrap.Button, Roo.bootstrap.Component,  {
564     html: false,
565     active: false,
566     weight: '',
567     size: '',
568     tag: 'button',
569     href: '',
570     disabled: false,
571     isClose: false,
572     glyphicon: '',
573     badge: '',
574     theme: 'default',
575     inverse: false,
576     
577     toggle: false,
578     ontext: 'ON',
579     offtext: 'OFF',
580     defaulton: true,
581     preventDefault: true,
582     removeClass: false,
583     name: false,
584     target: false,
585     
586     
587     pressed : null,
588      
589     
590     getAutoCreate : function(){
591         
592         var cfg = {
593             tag : 'button',
594             cls : 'roo-button',
595             html: ''
596         };
597         
598         if (['a', 'button', 'input', 'submit'].indexOf(this.tag) < 0) {
599             throw "Invalid value for tag: " + this.tag + ". must be a, button, input or submit.";
600             this.tag = 'button';
601         } else {
602             cfg.tag = this.tag;
603         }
604         cfg.html = '<span class="roo-button-text">' + (this.html || cfg.html) + '</span>';
605         
606         if (this.toggle == true) {
607             cfg={
608                 tag: 'div',
609                 cls: 'slider-frame roo-button',
610                 cn: [
611                     {
612                         tag: 'span',
613                         'data-on-text':'ON',
614                         'data-off-text':'OFF',
615                         cls: 'slider-button',
616                         html: this.offtext
617                     }
618                 ]
619             };
620             
621             if (['default', 'primary', 'success', 'info', 'warning', 'danger', 'link'].indexOf(this.weight) > -1) {
622                 cfg.cls += ' '+this.weight;
623             }
624             
625             return cfg;
626         }
627         
628         if (this.isClose) {
629             cfg.cls += ' close';
630             
631             cfg["aria-hidden"] = true;
632             
633             cfg.html = "&times;";
634             
635             return cfg;
636         }
637         
638          
639         if (this.theme==='default') {
640             cfg.cls = 'btn roo-button';
641             
642             //if (this.parentType != 'Navbar') {
643             this.weight = this.weight.length ?  this.weight : 'default';
644             //}
645             if (['default', 'primary', 'success', 'info', 'warning', 'danger', 'link'].indexOf(this.weight) > -1) {
646                 
647                 cfg.cls += ' btn-' + this.weight;
648             }
649         } else if (this.theme==='glow') {
650             
651             cfg.tag = 'a';
652             cfg.cls = 'btn-glow roo-button';
653             
654             if (['default', 'primary', 'success', 'info', 'warning', 'danger', 'link'].indexOf(this.weight) > -1) {
655                 
656                 cfg.cls += ' ' + this.weight;
657             }
658         }
659    
660         
661         if (this.inverse) {
662             this.cls += ' inverse';
663         }
664         
665         
666         if (this.active) {
667             cfg.cls += ' active';
668         }
669         
670         if (this.disabled) {
671             cfg.disabled = 'disabled';
672         }
673         
674         if (this.items) {
675             Roo.log('changing to ul' );
676             cfg.tag = 'ul';
677             this.glyphicon = 'caret';
678         }
679         
680         cfg.cls += this.size.length ? (' btn-' + this.size) : '';
681          
682         //gsRoo.log(this.parentType);
683         if (this.parentType === 'Navbar' && !this.parent().bar) {
684             Roo.log('changing to li?');
685             
686             cfg.tag = 'li';
687             
688             cfg.cls = '';
689             cfg.cn =  [{
690                 tag : 'a',
691                 cls : 'roo-button',
692                 html : this.html,
693                 href : this.href || '#'
694             }];
695             if (this.menu) {
696                 cfg.cn[0].html = this.html  + ' <span class="caret"></span>';
697                 cfg.cls += ' dropdown';
698             }   
699             
700             delete cfg.html;
701             
702         }
703         
704        cfg.cls += this.parentType === 'Navbar' ?  ' navbar-btn' : '';
705         
706         if (this.glyphicon) {
707             cfg.html = ' ' + cfg.html;
708             
709             cfg.cn = [
710                 {
711                     tag: 'span',
712                     cls: 'glyphicon glyphicon-' + this.glyphicon
713                 }
714             ];
715         }
716         
717         if (this.badge) {
718             cfg.html += ' ';
719             
720             cfg.tag = 'a';
721             
722 //            cfg.cls='btn roo-button';
723             
724             cfg.href=this.href;
725             
726             var value = cfg.html;
727             
728             if(this.glyphicon){
729                 value = {
730                             tag: 'span',
731                             cls: 'glyphicon glyphicon-' + this.glyphicon,
732                             html: this.html
733                         };
734                 
735             }
736             
737             cfg.cn = [
738                 value,
739                 {
740                     tag: 'span',
741                     cls: 'badge',
742                     html: this.badge
743                 }
744             ];
745             
746             cfg.html='';
747         }
748         
749         if (this.menu) {
750             cfg.cls += ' dropdown';
751             cfg.html = typeof(cfg.html) != 'undefined' ? cfg.html + ' <span class="caret"></span>' : '<span class="caret"></span>';
752         }
753         
754         if (cfg.tag !== 'a' && this.href !== '') {
755             throw "Tag must be a to set href.";
756         } else if (this.href.length > 0) {
757             cfg.href = this.href;
758         }
759         
760         if(this.removeClass){
761             cfg.cls = '';
762         }
763         
764         if(this.target){
765             cfg.target = this.target;
766         }
767         
768         return cfg;
769     },
770     initEvents: function() {
771        // Roo.log('init events?');
772 //        Roo.log(this.el.dom);
773         // add the menu...
774         
775         if (typeof (this.menu) != 'undefined') {
776             this.menu.parentType = this.xtype;
777             this.menu.triggerEl = this.el;
778             this.addxtype(Roo.apply({}, this.menu));
779         }
780
781
782        if (this.el.hasClass('roo-button')) {
783             this.el.on('click', this.onClick, this);
784        } else {
785             this.el.select('.roo-button').on('click', this.onClick, this);
786        }
787        
788        if(this.removeClass){
789            this.el.on('click', this.onClick, this);
790        }
791        
792        this.el.enableDisplayMode();
793         
794     },
795     onClick : function(e)
796     {
797         if (this.disabled) {
798             return;
799         }
800         
801         
802         Roo.log('button on click ');
803         if(this.preventDefault){
804             e.preventDefault();
805         }
806         if (this.pressed === true || this.pressed === false) {
807             this.pressed = !this.pressed;
808             this.el[this.pressed ? 'addClass' : 'removeClass']('active');
809             this.fireEvent('toggle', this, e, this.pressed);
810         }
811         
812         
813         this.fireEvent('click', this, e);
814     },
815     
816     /**
817      * Enables this button
818      */
819     enable : function()
820     {
821         this.disabled = false;
822         this.el.removeClass('disabled');
823     },
824     
825     /**
826      * Disable this button
827      */
828     disable : function()
829     {
830         this.disabled = true;
831         this.el.addClass('disabled');
832     },
833      /**
834      * sets the active state on/off, 
835      * @param {Boolean} state (optional) Force a particular state
836      */
837     setActive : function(v) {
838         
839         this.el[v ? 'addClass' : 'removeClass']('active');
840     },
841      /**
842      * toggles the current active state 
843      */
844     toggleActive : function()
845     {
846        var active = this.el.hasClass('active');
847        this.setActive(!active);
848        
849         
850     },
851     setText : function(str)
852     {
853         this.el.select('.roo-button-text',true).first().dom.innerHTML = str;
854     },
855     getText : function()
856     {
857         return this.el.select('.roo-button-text',true).first().dom.innerHTML;
858     },
859     hide: function() {
860        
861      
862         this.el.hide();   
863     },
864     show: function() {
865        
866         this.el.show();   
867     },
868     setWeight : function(str)
869     {
870           this.el.removeClass(this.weightClass);
871         this.el.addClass('btn-' + str);        
872     }
873     
874     
875 });
876
877  /*
878  * - LGPL
879  *
880  * column
881  * 
882  */
883
884 /**
885  * @class Roo.bootstrap.Column
886  * @extends Roo.bootstrap.Component
887  * Bootstrap Column class
888  * @cfg {Number} xs colspan out of 12 for mobile-sized screens or 0 for hidden
889  * @cfg {Number} sm colspan out of 12 for tablet-sized screens or 0 for hidden
890  * @cfg {Number} md colspan out of 12 for computer-sized screens or 0 for hidden
891  * @cfg {Number} lg colspan out of 12 for large computer-sized screens or 0 for hidden
892  * @cfg {Number} xsoff colspan offset out of 12 for mobile-sized screens or 0 for hidden
893  * @cfg {Number} smoff colspan offset out of 12 for tablet-sized screens or 0 for hidden
894  * @cfg {Number} mdoff colspan offset out of 12 for computer-sized screens or 0 for hidden
895  * @cfg {Number} lgoff colspan offset out of 12 for large computer-sized screens or 0 for hidden
896  *
897  * 
898  * @cfg {Boolean} hidden (true|false) hide the element
899  * @cfg {String} alert (success|info|warning|danger) type alert (changes background / border...)
900  * @cfg {String} fa (ban|check|...) font awesome icon
901  * @cfg {Number} fasize (1|2|....) font awsome size
902
903  * @cfg {String} icon (info-sign|check|...) glyphicon name
904
905  * @cfg {String} html content of column.
906  * 
907  * @constructor
908  * Create a new Column
909  * @param {Object} config The config object
910  */
911
912 Roo.bootstrap.Column = function(config){
913     Roo.bootstrap.Column.superclass.constructor.call(this, config);
914 };
915
916 Roo.extend(Roo.bootstrap.Column, Roo.bootstrap.Component,  {
917     
918     xs: false,
919     sm: false,
920     md: false,
921     lg: false,
922     xsoff: false,
923     smoff: false,
924     mdoff: false,
925     lgoff: false,
926     html: '',
927     offset: 0,
928     alert: false,
929     fa: false,
930     icon : false,
931     hidden : false,
932     fasize : 1,
933     
934     getAutoCreate : function(){
935         var cfg = Roo.apply({}, Roo.bootstrap.Column.superclass.getAutoCreate.call(this));
936         
937         cfg = {
938             tag: 'div',
939             cls: 'column'
940         };
941         
942         var settings=this;
943         ['xs','sm','md','lg'].map(function(size){
944             //Roo.log( size + ':' + settings[size]);
945             
946             if (settings[size+'off'] !== false) {
947                 cfg.cls += ' col-' + size + '-offset-' + settings[size+'off'] ;
948             }
949             
950             if (settings[size] === false) {
951                 return;
952             }
953             
954             if (!settings[size]) { // 0 = hidden
955                 cfg.cls += ' hidden-' + size;
956                 return;
957             }
958             cfg.cls += ' col-' + size + '-' + settings[size];
959             
960         });
961         
962         if (this.hidden) {
963             cfg.cls += ' hidden';
964         }
965         
966         if (this.alert && ["success","info","warning", "danger"].indexOf(this.alert) > -1) {
967             cfg.cls +=' alert alert-' + this.alert;
968         }
969         
970         
971         if (this.html.length) {
972             cfg.html = this.html;
973         }
974         if (this.fa) {
975             var fasize = '';
976             if (this.fasize > 1) {
977                 fasize = ' fa-' + this.fasize + 'x';
978             }
979             cfg.html = '<i class="fa fa-'+this.fa + fasize + '"></i>' + (cfg.html || '');
980             
981             
982         }
983         if (this.icon) {
984             cfg.html = '<i class="glyphicon glyphicon-'+this.icon + '"></i>' +  (cfg.html || '');
985         }
986         
987         return cfg;
988     }
989    
990 });
991
992  
993
994  /*
995  * - LGPL
996  *
997  * page container.
998  * 
999  */
1000
1001
1002 /**
1003  * @class Roo.bootstrap.Container
1004  * @extends Roo.bootstrap.Component
1005  * Bootstrap Container class
1006  * @cfg {Boolean} jumbotron is it a jumbotron element
1007  * @cfg {String} html content of element
1008  * @cfg {String} well (lg|sm|md) a well, large, small or medium.
1009  * @cfg {String} panel (primary|success|info|warning|danger) render as panel  - type - primary/success.....
1010  * @cfg {String} header content of header (for panel)
1011  * @cfg {String} footer content of footer (for panel)
1012  * @cfg {String} sticky (footer|wrap|push) block to use as footer or body- needs css-bootstrap/sticky-footer.css
1013  * @cfg {String} tag (header|aside|section) type of HTML tag.
1014  * @cfg {String} alert (success|info|warning|danger) type alert (changes background / border...)
1015  * @cfg {String} fa font awesome icon
1016  * @cfg {String} icon (info-sign|check|...) glyphicon name
1017  * @cfg {Boolean} hidden (true|false) hide the element
1018  * @cfg {Boolean} expandable (true|false) default false
1019  * @cfg {Boolean} expanded (true|false) default true
1020  * @cfg {String} rheader contet on the right of header
1021  * @cfg {Boolean} clickable (true|false) default false
1022
1023  *     
1024  * @constructor
1025  * Create a new Container
1026  * @param {Object} config The config object
1027  */
1028
1029 Roo.bootstrap.Container = function(config){
1030     Roo.bootstrap.Container.superclass.constructor.call(this, config);
1031     
1032     this.addEvents({
1033         // raw events
1034          /**
1035          * @event expand
1036          * After the panel has been expand
1037          * 
1038          * @param {Roo.bootstrap.Container} this
1039          */
1040         "expand" : true,
1041         /**
1042          * @event collapse
1043          * After the panel has been collapsed
1044          * 
1045          * @param {Roo.bootstrap.Container} this
1046          */
1047         "collapse" : true,
1048         /**
1049          * @event click
1050          * When a element is chick
1051          * @param {Roo.bootstrap.Container} this
1052          * @param {Roo.EventObject} e
1053          */
1054         "click" : true
1055     });
1056 };
1057
1058 Roo.extend(Roo.bootstrap.Container, Roo.bootstrap.Component,  {
1059     
1060     jumbotron : false,
1061     well: '',
1062     panel : '',
1063     header: '',
1064     footer : '',
1065     sticky: '',
1066     tag : false,
1067     alert : false,
1068     fa: false,
1069     icon : false,
1070     expandable : false,
1071     rheader : '',
1072     expanded : true,
1073     clickable: false,
1074   
1075      
1076     getChildContainer : function() {
1077         
1078         if(!this.el){
1079             return false;
1080         }
1081         
1082         if (this.panel.length) {
1083             return this.el.select('.panel-body',true).first();
1084         }
1085         
1086         return this.el;
1087     },
1088     
1089     
1090     getAutoCreate : function(){
1091         
1092         var cfg = {
1093             tag : this.tag || 'div',
1094             html : '',
1095             cls : ''
1096         };
1097         if (this.jumbotron) {
1098             cfg.cls = 'jumbotron';
1099         }
1100         
1101         
1102         
1103         // - this is applied by the parent..
1104         //if (this.cls) {
1105         //    cfg.cls = this.cls + '';
1106         //}
1107         
1108         if (this.sticky.length) {
1109             
1110             var bd = Roo.get(document.body);
1111             if (!bd.hasClass('bootstrap-sticky')) {
1112                 bd.addClass('bootstrap-sticky');
1113                 Roo.select('html',true).setStyle('height', '100%');
1114             }
1115              
1116             cfg.cls += 'bootstrap-sticky-' + this.sticky;
1117         }
1118         
1119         
1120         if (this.well.length) {
1121             switch (this.well) {
1122                 case 'lg':
1123                 case 'sm':
1124                     cfg.cls +=' well well-' +this.well;
1125                     break;
1126                 default:
1127                     cfg.cls +=' well';
1128                     break;
1129             }
1130         }
1131         
1132         if (this.hidden) {
1133             cfg.cls += ' hidden';
1134         }
1135         
1136         
1137         if (this.alert && ["success","info","warning", "danger"].indexOf(this.alert) > -1) {
1138             cfg.cls +=' alert alert-' + this.alert;
1139         }
1140         
1141         var body = cfg;
1142         
1143         if (this.panel.length) {
1144             cfg.cls += ' panel panel-' + this.panel;
1145             cfg.cn = [];
1146             if (this.header.length) {
1147                 
1148                 var h = [];
1149                 
1150                 if(this.expandable){
1151                     
1152                     cfg.cls = cfg.cls + ' expandable';
1153                     
1154                     h.push({
1155                         tag: 'i',
1156                         cls: (this.expanded ? 'fa fa-minus' : 'fa fa-plus') 
1157                     });
1158                     
1159                 }
1160                 
1161                 h.push(
1162                     {
1163                         tag: 'span',
1164                         cls : 'panel-title',
1165                         html : (this.expandable ? '&nbsp;' : '') + this.header
1166                     },
1167                     {
1168                         tag: 'span',
1169                         cls: 'panel-header-right',
1170                         html: this.rheader
1171                     }
1172                 );
1173                 
1174                 cfg.cn.push({
1175                     cls : 'panel-heading',
1176                     style : this.expandable ? 'cursor: pointer' : '',
1177                     cn : h
1178                 });
1179                 
1180             }
1181             
1182             body = false;
1183             cfg.cn.push({
1184                 cls : 'panel-body' + (this.expanded ? '' : ' hide'),
1185                 html : this.html
1186             });
1187             
1188             
1189             if (this.footer.length) {
1190                 cfg.cn.push({
1191                     cls : 'panel-footer',
1192                     html : this.footer
1193                     
1194                 });
1195             }
1196             
1197         }
1198         
1199         if (body) {
1200             body.html = this.html || cfg.html;
1201             // prefix with the icons..
1202             if (this.fa) {
1203                 body.html = '<i class="fa fa-'+this.fa + '"></i>' + body.html ;
1204             }
1205             if (this.icon) {
1206                 body.html = '<i class="glyphicon glyphicon-'+this.icon + '"></i>' + body.html ;
1207             }
1208             
1209             
1210         }
1211         if ((!this.cls || !this.cls.length) && (!cfg.cls || !cfg.cls.length)) {
1212             cfg.cls =  'container';
1213         }
1214         
1215         return cfg;
1216     },
1217     
1218     initEvents: function() 
1219     {
1220         if(this.expandable){
1221             var headerEl = this.headerEl();
1222         
1223             if(headerEl){
1224                 headerEl.on('click', this.onToggleClick, this);
1225             }
1226         }
1227         
1228         if(this.clickable){
1229             this.el.on('click', this.onClick, this);
1230         }
1231         
1232     },
1233     
1234     onToggleClick : function()
1235     {
1236         var headerEl = this.headerEl();
1237         
1238         if(!headerEl){
1239             return;
1240         }
1241         
1242         if(this.expanded){
1243             this.collapse();
1244             return;
1245         }
1246         
1247         this.expand();
1248     },
1249     
1250     expand : function()
1251     {
1252         if(this.fireEvent('expand', this)) {
1253             
1254             this.expanded = true;
1255             
1256             //this.el.select('.panel-body',true).first().setVisibilityMode(Roo.Element.DISPLAY).show();
1257             
1258             this.el.select('.panel-body',true).first().removeClass('hide');
1259             
1260             var toggleEl = this.toggleEl();
1261
1262             if(!toggleEl){
1263                 return;
1264             }
1265
1266             toggleEl.removeClass(['fa-minus', 'fa-plus']).addClass(['fa-minus']);
1267         }
1268         
1269     },
1270     
1271     collapse : function()
1272     {
1273         if(this.fireEvent('collapse', this)) {
1274             
1275             this.expanded = false;
1276             
1277             //this.el.select('.panel-body',true).first().setVisibilityMode(Roo.Element.DISPLAY).hide();
1278             this.el.select('.panel-body',true).first().addClass('hide');
1279         
1280             var toggleEl = this.toggleEl();
1281
1282             if(!toggleEl){
1283                 return;
1284             }
1285
1286             toggleEl.removeClass(['fa-minus', 'fa-plus']).addClass(['fa-plus']);
1287         }
1288     },
1289     
1290     toggleEl : function()
1291     {
1292         if(!this.el || !this.panel.length || !this.header.length || !this.expandable){
1293             return;
1294         }
1295         
1296         return this.el.select('.panel-heading .fa',true).first();
1297     },
1298     
1299     headerEl : function()
1300     {
1301         if(!this.el || !this.panel.length || !this.header.length){
1302             return;
1303         }
1304         
1305         return this.el.select('.panel-heading',true).first()
1306     },
1307     
1308     bodyEl : function()
1309     {
1310         if(!this.el || !this.panel.length){
1311             return;
1312         }
1313         
1314         return this.el.select('.panel-body',true).first()
1315     },
1316     
1317     titleEl : function()
1318     {
1319         if(!this.el || !this.panel.length || !this.header.length){
1320             return;
1321         }
1322         
1323         return this.el.select('.panel-title',true).first();
1324     },
1325     
1326     setTitle : function(v)
1327     {
1328         var titleEl = this.titleEl();
1329         
1330         if(!titleEl){
1331             return;
1332         }
1333         
1334         titleEl.dom.innerHTML = v;
1335     },
1336     
1337     getTitle : function()
1338     {
1339         
1340         var titleEl = this.titleEl();
1341         
1342         if(!titleEl){
1343             return '';
1344         }
1345         
1346         return titleEl.dom.innerHTML;
1347     },
1348     
1349     setRightTitle : function(v)
1350     {
1351         var t = this.el.select('.panel-header-right',true).first();
1352         
1353         if(!t){
1354             return;
1355         }
1356         
1357         t.dom.innerHTML = v;
1358     },
1359     
1360     onClick : function(e)
1361     {
1362         e.preventDefault();
1363         
1364         this.fireEvent('click', this, e);
1365     }
1366    
1367 });
1368
1369  /*
1370  * - LGPL
1371  *
1372  * image
1373  * 
1374  */
1375
1376
1377 /**
1378  * @class Roo.bootstrap.Img
1379  * @extends Roo.bootstrap.Component
1380  * Bootstrap Img class
1381  * @cfg {Boolean} imgResponsive false | true
1382  * @cfg {String} border rounded | circle | thumbnail
1383  * @cfg {String} src image source
1384  * @cfg {String} alt image alternative text
1385  * @cfg {String} href a tag href
1386  * @cfg {String} target (_self|_blank|_parent|_top)target for a href.
1387  * @cfg {String} xsUrl xs image source
1388  * @cfg {String} smUrl sm image source
1389  * @cfg {String} mdUrl md image source
1390  * @cfg {String} lgUrl lg image source
1391  * 
1392  * @constructor
1393  * Create a new Input
1394  * @param {Object} config The config object
1395  */
1396
1397 Roo.bootstrap.Img = function(config){
1398     Roo.bootstrap.Img.superclass.constructor.call(this, config);
1399     
1400     this.addEvents({
1401         // img events
1402         /**
1403          * @event click
1404          * The img click event for the img.
1405          * @param {Roo.EventObject} e
1406          */
1407         "click" : true
1408     });
1409 };
1410
1411 Roo.extend(Roo.bootstrap.Img, Roo.bootstrap.Component,  {
1412     
1413     imgResponsive: true,
1414     border: '',
1415     src: 'about:blank',
1416     href: false,
1417     target: false,
1418     xsUrl: '',
1419     smUrl: '',
1420     mdUrl: '',
1421     lgUrl: '',
1422
1423     getAutoCreate : function()
1424     {   
1425         if(this.src || (!this.xsUrl && !this.smUrl && !this.mdUrl && !this.lgUrl)){
1426             return this.createSingleImg();
1427         }
1428         
1429         var cfg = {
1430             tag: 'div',
1431             cls: 'roo-image-responsive-group',
1432             cn: []
1433         };
1434         var _this = this;
1435         
1436         Roo.each(['xs', 'sm', 'md', 'lg'], function(size){
1437             
1438             if(!_this[size + 'Url']){
1439                 return;
1440             }
1441             
1442             var img = {
1443                 tag: 'img',
1444                 cls: (_this.imgResponsive) ? 'img-responsive' : '',
1445                 html: _this.html || cfg.html,
1446                 src: _this[size + 'Url']
1447             };
1448             
1449             img.cls += ' roo-image-responsive-' + size;
1450             
1451             var s = ['xs', 'sm', 'md', 'lg'];
1452             
1453             s.splice(s.indexOf(size), 1);
1454             
1455             Roo.each(s, function(ss){
1456                 img.cls += ' hidden-' + ss;
1457             });
1458             
1459             if (['rounded','circle','thumbnail'].indexOf(_this.border)>-1) {
1460                 cfg.cls += ' img-' + _this.border;
1461             }
1462             
1463             if(_this.alt){
1464                 cfg.alt = _this.alt;
1465             }
1466             
1467             if(_this.href){
1468                 var a = {
1469                     tag: 'a',
1470                     href: _this.href,
1471                     cn: [
1472                         img
1473                     ]
1474                 };
1475
1476                 if(this.target){
1477                     a.target = _this.target;
1478                 }
1479             }
1480             
1481             cfg.cn.push((_this.href) ? a : img);
1482             
1483         });
1484         
1485         return cfg;
1486     },
1487     
1488     createSingleImg : function()
1489     {
1490         var cfg = {
1491             tag: 'img',
1492             cls: (this.imgResponsive) ? 'img-responsive' : '',
1493             html : null,
1494             src : 'about:blank'  // just incase src get's set to undefined?!?
1495         };
1496         
1497         cfg.html = this.html || cfg.html;
1498         
1499         cfg.src = this.src || cfg.src;
1500         
1501         if (['rounded','circle','thumbnail'].indexOf(this.border)>-1) {
1502             cfg.cls += ' img-' + this.border;
1503         }
1504         
1505         if(this.alt){
1506             cfg.alt = this.alt;
1507         }
1508         
1509         if(this.href){
1510             var a = {
1511                 tag: 'a',
1512                 href: this.href,
1513                 cn: [
1514                     cfg
1515                 ]
1516             };
1517             
1518             if(this.target){
1519                 a.target = this.target;
1520             }
1521             
1522         }
1523         
1524         return (this.href) ? a : cfg;
1525     },
1526     
1527     initEvents: function() 
1528     {
1529         if(!this.href){
1530             this.el.on('click', this.onClick, this);
1531         }
1532         
1533     },
1534     
1535     onClick : function(e)
1536     {
1537         Roo.log('img onclick');
1538         this.fireEvent('click', this, e);
1539     },
1540     /**
1541      * Sets the url of the image - used to update it
1542      * @param {String} url the url of the image
1543      */
1544     
1545     setSrc : function(url)
1546     {
1547         this.src =  url;
1548         
1549         if(this.src || (!this.xsUrl && !this.smUrl && !this.mdUrl && !this.lgUrl)){
1550             this.el.dom.src =  url;
1551             return;
1552         }
1553         
1554         this.el.select('img', true).first().dom.src =  url;
1555     }
1556     
1557     
1558    
1559 });
1560
1561  /*
1562  * - LGPL
1563  *
1564  * image
1565  * 
1566  */
1567
1568
1569 /**
1570  * @class Roo.bootstrap.Link
1571  * @extends Roo.bootstrap.Component
1572  * Bootstrap Link Class
1573  * @cfg {String} alt image alternative text
1574  * @cfg {String} href a tag href
1575  * @cfg {String} target (_self|_blank|_parent|_top) target for a href.
1576  * @cfg {String} html the content of the link.
1577  * @cfg {String} anchor name for the anchor link
1578  * @cfg {String} fa - favicon
1579
1580  * @cfg {Boolean} preventDefault (true | false) default false
1581
1582  * 
1583  * @constructor
1584  * Create a new Input
1585  * @param {Object} config The config object
1586  */
1587
1588 Roo.bootstrap.Link = function(config){
1589     Roo.bootstrap.Link.superclass.constructor.call(this, config);
1590     
1591     this.addEvents({
1592         // img events
1593         /**
1594          * @event click
1595          * The img click event for the img.
1596          * @param {Roo.EventObject} e
1597          */
1598         "click" : true
1599     });
1600 };
1601
1602 Roo.extend(Roo.bootstrap.Link, Roo.bootstrap.Component,  {
1603     
1604     href: false,
1605     target: false,
1606     preventDefault: false,
1607     anchor : false,
1608     alt : false,
1609     fa: false,
1610
1611
1612     getAutoCreate : function()
1613     {
1614         var html = this.html || '';
1615         
1616         if (this.fa !== false) {
1617             html = '<i class="fa fa-' + this.fa + '"></i>';
1618         }
1619         var cfg = {
1620             tag: 'a'
1621         };
1622         // anchor's do not require html/href...
1623         if (this.anchor === false) {
1624             cfg.html = html;
1625             cfg.href = this.href || '#';
1626         } else {
1627             cfg.name = this.anchor;
1628             if (this.html !== false || this.fa !== false) {
1629                 cfg.html = html;
1630             }
1631             if (this.href !== false) {
1632                 cfg.href = this.href;
1633             }
1634         }
1635         
1636         if(this.alt !== false){
1637             cfg.alt = this.alt;
1638         }
1639         
1640         
1641         if(this.target !== false) {
1642             cfg.target = this.target;
1643         }
1644         
1645         return cfg;
1646     },
1647     
1648     initEvents: function() {
1649         
1650         if(!this.href || this.preventDefault){
1651             this.el.on('click', this.onClick, this);
1652         }
1653     },
1654     
1655     onClick : function(e)
1656     {
1657         if(this.preventDefault){
1658             e.preventDefault();
1659         }
1660         //Roo.log('img onclick');
1661         this.fireEvent('click', this, e);
1662     }
1663    
1664 });
1665
1666  /*
1667  * - LGPL
1668  *
1669  * header
1670  * 
1671  */
1672
1673 /**
1674  * @class Roo.bootstrap.Header
1675  * @extends Roo.bootstrap.Component
1676  * Bootstrap Header class
1677  * @cfg {String} html content of header
1678  * @cfg {Number} level (1|2|3|4|5|6) default 1
1679  * 
1680  * @constructor
1681  * Create a new Header
1682  * @param {Object} config The config object
1683  */
1684
1685
1686 Roo.bootstrap.Header  = function(config){
1687     Roo.bootstrap.Header.superclass.constructor.call(this, config);
1688 };
1689
1690 Roo.extend(Roo.bootstrap.Header, Roo.bootstrap.Component,  {
1691     
1692     //href : false,
1693     html : false,
1694     level : 1,
1695     
1696     
1697     
1698     getAutoCreate : function(){
1699         
1700         
1701         
1702         var cfg = {
1703             tag: 'h' + (1 *this.level),
1704             html: this.html || ''
1705         } ;
1706         
1707         return cfg;
1708     }
1709    
1710 });
1711
1712  
1713
1714  /*
1715  * Based on:
1716  * Ext JS Library 1.1.1
1717  * Copyright(c) 2006-2007, Ext JS, LLC.
1718  *
1719  * Originally Released Under LGPL - original licence link has changed is not relivant.
1720  *
1721  * Fork - LGPL
1722  * <script type="text/javascript">
1723  */
1724  
1725 /**
1726  * @class Roo.bootstrap.MenuMgr
1727  * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
1728  * @singleton
1729  */
1730 Roo.bootstrap.MenuMgr = function(){
1731    var menus, active, groups = {}, attached = false, lastShow = new Date();
1732
1733    // private - called when first menu is created
1734    function init(){
1735        menus = {};
1736        active = new Roo.util.MixedCollection();
1737        Roo.get(document).addKeyListener(27, function(){
1738            if(active.length > 0){
1739                hideAll();
1740            }
1741        });
1742    }
1743
1744    // private
1745    function hideAll(){
1746        if(active && active.length > 0){
1747            var c = active.clone();
1748            c.each(function(m){
1749                m.hide();
1750            });
1751        }
1752    }
1753
1754    // private
1755    function onHide(m){
1756        active.remove(m);
1757        if(active.length < 1){
1758            Roo.get(document).un("mouseup", onMouseDown);
1759             
1760            attached = false;
1761        }
1762    }
1763
1764    // private
1765    function onShow(m){
1766        var last = active.last();
1767        lastShow = new Date();
1768        active.add(m);
1769        if(!attached){
1770           Roo.get(document).on("mouseup", onMouseDown);
1771            
1772            attached = true;
1773        }
1774        if(m.parentMenu){
1775           //m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
1776           m.parentMenu.activeChild = m;
1777        }else if(last && last.isVisible()){
1778           //m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
1779        }
1780    }
1781
1782    // private
1783    function onBeforeHide(m){
1784        if(m.activeChild){
1785            m.activeChild.hide();
1786        }
1787        if(m.autoHideTimer){
1788            clearTimeout(m.autoHideTimer);
1789            delete m.autoHideTimer;
1790        }
1791    }
1792
1793    // private
1794    function onBeforeShow(m){
1795        var pm = m.parentMenu;
1796        if(!pm && !m.allowOtherMenus){
1797            hideAll();
1798        }else if(pm && pm.activeChild && active != m){
1799            pm.activeChild.hide();
1800        }
1801    }
1802
1803    // private this should really trigger on mouseup..
1804    function onMouseDown(e){
1805         Roo.log("on Mouse Up");
1806         
1807         if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".dropdown-menu") && !e.getTarget('.user-menu')){
1808             Roo.log("MenuManager hideAll");
1809             hideAll();
1810             e.stopEvent();
1811         }
1812         
1813         
1814    }
1815
1816    // private
1817    function onBeforeCheck(mi, state){
1818        if(state){
1819            var g = groups[mi.group];
1820            for(var i = 0, l = g.length; i < l; i++){
1821                if(g[i] != mi){
1822                    g[i].setChecked(false);
1823                }
1824            }
1825        }
1826    }
1827
1828    return {
1829
1830        /**
1831         * Hides all menus that are currently visible
1832         */
1833        hideAll : function(){
1834             hideAll();  
1835        },
1836
1837        // private
1838        register : function(menu){
1839            if(!menus){
1840                init();
1841            }
1842            menus[menu.id] = menu;
1843            menu.on("beforehide", onBeforeHide);
1844            menu.on("hide", onHide);
1845            menu.on("beforeshow", onBeforeShow);
1846            menu.on("show", onShow);
1847            var g = menu.group;
1848            if(g && menu.events["checkchange"]){
1849                if(!groups[g]){
1850                    groups[g] = [];
1851                }
1852                groups[g].push(menu);
1853                menu.on("checkchange", onCheck);
1854            }
1855        },
1856
1857         /**
1858          * Returns a {@link Roo.menu.Menu} object
1859          * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
1860          * be used to generate and return a new Menu instance.
1861          */
1862        get : function(menu){
1863            if(typeof menu == "string"){ // menu id
1864                return menus[menu];
1865            }else if(menu.events){  // menu instance
1866                return menu;
1867            }
1868            /*else if(typeof menu.length == 'number'){ // array of menu items?
1869                return new Roo.bootstrap.Menu({items:menu});
1870            }else{ // otherwise, must be a config
1871                return new Roo.bootstrap.Menu(menu);
1872            }
1873            */
1874            return false;
1875        },
1876
1877        // private
1878        unregister : function(menu){
1879            delete menus[menu.id];
1880            menu.un("beforehide", onBeforeHide);
1881            menu.un("hide", onHide);
1882            menu.un("beforeshow", onBeforeShow);
1883            menu.un("show", onShow);
1884            var g = menu.group;
1885            if(g && menu.events["checkchange"]){
1886                groups[g].remove(menu);
1887                menu.un("checkchange", onCheck);
1888            }
1889        },
1890
1891        // private
1892        registerCheckable : function(menuItem){
1893            var g = menuItem.group;
1894            if(g){
1895                if(!groups[g]){
1896                    groups[g] = [];
1897                }
1898                groups[g].push(menuItem);
1899                menuItem.on("beforecheckchange", onBeforeCheck);
1900            }
1901        },
1902
1903        // private
1904        unregisterCheckable : function(menuItem){
1905            var g = menuItem.group;
1906            if(g){
1907                groups[g].remove(menuItem);
1908                menuItem.un("beforecheckchange", onBeforeCheck);
1909            }
1910        }
1911    };
1912 }();/*
1913  * - LGPL
1914  *
1915  * menu
1916  * 
1917  */
1918
1919 /**
1920  * @class Roo.bootstrap.Menu
1921  * @extends Roo.bootstrap.Component
1922  * Bootstrap Menu class - container for MenuItems
1923  * @cfg {String} type (dropdown|treeview|submenu) type of menu
1924  * @cfg {bool} hidden  if the menu should be hidden when rendered.
1925  * @cfg {bool} stopEvent (true|false)  Stop event after trigger press (default true)
1926  * @cfg {bool} isLink (true|false)  the menu has link disable auto expand and collaspe (default false)
1927  * 
1928  * @constructor
1929  * Create a new Menu
1930  * @param {Object} config The config object
1931  */
1932
1933
1934 Roo.bootstrap.Menu = function(config){
1935     Roo.bootstrap.Menu.superclass.constructor.call(this, config);
1936     if (this.registerMenu && this.type != 'treeview')  {
1937         Roo.bootstrap.MenuMgr.register(this);
1938     }
1939     this.addEvents({
1940         /**
1941          * @event beforeshow
1942          * Fires before this menu is displayed
1943          * @param {Roo.menu.Menu} this
1944          */
1945         beforeshow : true,
1946         /**
1947          * @event beforehide
1948          * Fires before this menu is hidden
1949          * @param {Roo.menu.Menu} this
1950          */
1951         beforehide : true,
1952         /**
1953          * @event show
1954          * Fires after this menu is displayed
1955          * @param {Roo.menu.Menu} this
1956          */
1957         show : true,
1958         /**
1959          * @event hide
1960          * Fires after this menu is hidden
1961          * @param {Roo.menu.Menu} this
1962          */
1963         hide : true,
1964         /**
1965          * @event click
1966          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
1967          * @param {Roo.menu.Menu} this
1968          * @param {Roo.menu.Item} menuItem The menu item that was clicked
1969          * @param {Roo.EventObject} e
1970          */
1971         click : true,
1972         /**
1973          * @event mouseover
1974          * Fires when the mouse is hovering over this menu
1975          * @param {Roo.menu.Menu} this
1976          * @param {Roo.EventObject} e
1977          * @param {Roo.menu.Item} menuItem The menu item that was clicked
1978          */
1979         mouseover : true,
1980         /**
1981          * @event mouseout
1982          * Fires when the mouse exits this menu
1983          * @param {Roo.menu.Menu} this
1984          * @param {Roo.EventObject} e
1985          * @param {Roo.menu.Item} menuItem The menu item that was clicked
1986          */
1987         mouseout : true,
1988         /**
1989          * @event itemclick
1990          * Fires when a menu item contained in this menu is clicked
1991          * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
1992          * @param {Roo.EventObject} e
1993          */
1994         itemclick: true
1995     });
1996     this.menuitems = new Roo.util.MixedCollection(false, function(o) { return o.el.id; });
1997 };
1998
1999 Roo.extend(Roo.bootstrap.Menu, Roo.bootstrap.Component,  {
2000     
2001    /// html : false,
2002     //align : '',
2003     triggerEl : false,  // is this set by component builder? -- it should really be fetched from parent()???
2004     type: false,
2005     /**
2006      * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
2007      */
2008     registerMenu : true,
2009     
2010     menuItems :false, // stores the menu items..
2011     
2012     hidden:true,
2013         
2014     parentMenu : false,
2015     
2016     stopEvent : true,
2017     
2018     isLink : false,
2019     
2020     getChildContainer : function() {
2021         return this.el;  
2022     },
2023     
2024     getAutoCreate : function(){
2025          
2026         //if (['right'].indexOf(this.align)!==-1) {
2027         //    cfg.cn[1].cls += ' pull-right'
2028         //}
2029         
2030         
2031         var cfg = {
2032             tag : 'ul',
2033             cls : 'dropdown-menu' ,
2034             style : 'z-index:1000'
2035             
2036         };
2037         
2038         if (this.type === 'submenu') {
2039             cfg.cls = 'submenu active';
2040         }
2041         if (this.type === 'treeview') {
2042             cfg.cls = 'treeview-menu';
2043         }
2044         
2045         return cfg;
2046     },
2047     initEvents : function() {
2048         
2049        // Roo.log("ADD event");
2050        // Roo.log(this.triggerEl.dom);
2051         
2052         this.triggerEl.on('click', this.onTriggerClick, this);
2053         
2054         this.triggerEl.on(Roo.isTouch ? 'touchstart' : 'mouseup', this.onTriggerPress, this);
2055         
2056         this.triggerEl.addClass('dropdown-toggle');
2057         
2058         if (Roo.isTouch) {
2059             this.el.on('touchstart'  , this.onTouch, this);
2060         }
2061         this.el.on('click' , this.onClick, this);
2062
2063         this.el.on("mouseover", this.onMouseOver, this);
2064         this.el.on("mouseout", this.onMouseOut, this);
2065         
2066     },
2067     
2068     findTargetItem : function(e)
2069     {
2070         var t = e.getTarget(".dropdown-menu-item", this.el,  true);
2071         if(!t){
2072             return false;
2073         }
2074         //Roo.log(t);         Roo.log(t.id);
2075         if(t && t.id){
2076             //Roo.log(this.menuitems);
2077             return this.menuitems.get(t.id);
2078             
2079             //return this.items.get(t.menuItemId);
2080         }
2081         
2082         return false;
2083     },
2084     
2085     onTouch : function(e) 
2086     {
2087         Roo.log("menu.onTouch");
2088         //e.stopEvent(); this make the user popdown broken
2089         this.onClick(e);
2090     },
2091     
2092     onClick : function(e)
2093     {
2094         Roo.log("menu.onClick");
2095         
2096         var t = this.findTargetItem(e);
2097         if(!t || t.isContainer){
2098             return;
2099         }
2100         Roo.log(e);
2101         /*
2102         if (Roo.isTouch && e.type == 'touchstart' && t.menu  && !t.disabled) {
2103             if(t == this.activeItem && t.shouldDeactivate(e)){
2104                 this.activeItem.deactivate();
2105                 delete this.activeItem;
2106                 return;
2107             }
2108             if(t.canActivate){
2109                 this.setActiveItem(t, true);
2110             }
2111             return;
2112             
2113             
2114         }
2115         */
2116        
2117         Roo.log('pass click event');
2118         
2119         t.onClick(e);
2120         
2121         this.fireEvent("click", this, t, e);
2122         
2123         var _this = this;
2124         
2125         if(!t.href.length || t.href == '#'){
2126             (function() { _this.hide(); }).defer(100);
2127         }
2128         
2129     },
2130     
2131     onMouseOver : function(e){
2132         var t  = this.findTargetItem(e);
2133         //Roo.log(t);
2134         //if(t){
2135         //    if(t.canActivate && !t.disabled){
2136         //        this.setActiveItem(t, true);
2137         //    }
2138         //}
2139         
2140         this.fireEvent("mouseover", this, e, t);
2141     },
2142     isVisible : function(){
2143         return !this.hidden;
2144     },
2145      onMouseOut : function(e){
2146         var t  = this.findTargetItem(e);
2147         
2148         //if(t ){
2149         //    if(t == this.activeItem && t.shouldDeactivate(e)){
2150         //        this.activeItem.deactivate();
2151         //        delete this.activeItem;
2152         //    }
2153         //}
2154         this.fireEvent("mouseout", this, e, t);
2155     },
2156     
2157     
2158     /**
2159      * Displays this menu relative to another element
2160      * @param {String/HTMLElement/Roo.Element} element The element to align to
2161      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
2162      * the element (defaults to this.defaultAlign)
2163      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
2164      */
2165     show : function(el, pos, parentMenu){
2166         this.parentMenu = parentMenu;
2167         if(!this.el){
2168             this.render();
2169         }
2170         this.fireEvent("beforeshow", this);
2171         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
2172     },
2173      /**
2174      * Displays this menu at a specific xy position
2175      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
2176      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
2177      */
2178     showAt : function(xy, parentMenu, /* private: */_e){
2179         this.parentMenu = parentMenu;
2180         if(!this.el){
2181             this.render();
2182         }
2183         if(_e !== false){
2184             this.fireEvent("beforeshow", this);
2185             //xy = this.el.adjustForConstraints(xy);
2186         }
2187         
2188         //this.el.show();
2189         this.hideMenuItems();
2190         this.hidden = false;
2191         this.triggerEl.addClass('open');
2192         
2193         if(this.el.getWidth() + xy[0] > Roo.lib.Dom.getViewWidth()){
2194             xy[0] = xy[0] - this.el.getWidth() + this.triggerEl.getWidth();
2195         }
2196         
2197         if(this.el.getStyle('top') != 'auto' && this.el.getStyle('top').slice(-1) != "%"){
2198             this.el.setXY(xy);
2199         }
2200         
2201         this.focus();
2202         this.fireEvent("show", this);
2203     },
2204     
2205     focus : function(){
2206         return;
2207         if(!this.hidden){
2208             this.doFocus.defer(50, this);
2209         }
2210     },
2211
2212     doFocus : function(){
2213         if(!this.hidden){
2214             this.focusEl.focus();
2215         }
2216     },
2217
2218     /**
2219      * Hides this menu and optionally all parent menus
2220      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
2221      */
2222     hide : function(deep)
2223     {
2224         
2225         this.hideMenuItems();
2226         if(this.el && this.isVisible()){
2227             this.fireEvent("beforehide", this);
2228             if(this.activeItem){
2229                 this.activeItem.deactivate();
2230                 this.activeItem = null;
2231             }
2232             this.triggerEl.removeClass('open');;
2233             this.hidden = true;
2234             this.fireEvent("hide", this);
2235         }
2236         if(deep === true && this.parentMenu){
2237             this.parentMenu.hide(true);
2238         }
2239     },
2240     
2241     onTriggerClick : function(e)
2242     {
2243         Roo.log('trigger click');
2244         
2245         var target = e.getTarget();
2246         
2247         Roo.log(target.nodeName.toLowerCase());
2248         
2249         if(target.nodeName.toLowerCase() === 'i'){
2250             e.preventDefault();
2251         }
2252         
2253     },
2254     
2255     onTriggerPress  : function(e)
2256     {
2257         Roo.log('trigger press');
2258         //Roo.log(e.getTarget());
2259        // Roo.log(this.triggerEl.dom);
2260        
2261         // trigger only occurs on normal menu's -- if it's a treeview or dropdown... do not hide/show..
2262         var pel = Roo.get(e.getTarget());
2263         if (pel.findParent('.dropdown-menu') || pel.findParent('.treeview-menu') ) {
2264             Roo.log('is treeview or dropdown?');
2265             return;
2266         }
2267         
2268         if(e.getTarget().nodeName.toLowerCase() !== 'i' && this.isLink){
2269             return;
2270         }
2271         
2272         if (this.isVisible()) {
2273             Roo.log('hide');
2274             this.hide();
2275         } else {
2276             Roo.log('show');
2277             this.show(this.triggerEl, false, false);
2278         }
2279         
2280         if(this.stopEvent || e.getTarget().nodeName.toLowerCase() === 'i'){
2281             e.stopEvent();
2282         }
2283         
2284     },
2285        
2286     
2287     hideMenuItems : function()
2288     {
2289         Roo.log("hide Menu Items");
2290         if (!this.el) { 
2291             return;
2292         }
2293         //$(backdrop).remove()
2294         this.el.select('.open',true).each(function(aa) {
2295             
2296             aa.removeClass('open');
2297           //var parent = getParent($(this))
2298           //var relatedTarget = { relatedTarget: this }
2299           
2300            //$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
2301           //if (e.isDefaultPrevented()) return
2302            //$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
2303         });
2304     },
2305     addxtypeChild : function (tree, cntr) {
2306         var comp= Roo.bootstrap.Menu.superclass.addxtypeChild.call(this, tree, cntr);
2307           
2308         this.menuitems.add(comp);
2309         return comp;
2310
2311     },
2312     getEl : function()
2313     {
2314         Roo.log(this.el);
2315         return this.el;
2316     }
2317 });
2318
2319  
2320  /*
2321  * - LGPL
2322  *
2323  * menu item
2324  * 
2325  */
2326
2327
2328 /**
2329  * @class Roo.bootstrap.MenuItem
2330  * @extends Roo.bootstrap.Component
2331  * Bootstrap MenuItem class
2332  * @cfg {String} html the menu label
2333  * @cfg {String} href the link
2334  * @cfg {Boolean} preventDefault do not trigger A href on clicks (default false).
2335  * @cfg {Boolean} isContainer is it a container - just returns a drop down item..
2336  * @cfg {Boolean} active  used on sidebars to highlight active itesm
2337  * @cfg {String} fa favicon to show on left of menu item.
2338  * @cfg {Roo.bootsrap.Menu} menu the child menu.
2339  * 
2340  * 
2341  * @constructor
2342  * Create a new MenuItem
2343  * @param {Object} config The config object
2344  */
2345
2346
2347 Roo.bootstrap.MenuItem = function(config){
2348     Roo.bootstrap.MenuItem.superclass.constructor.call(this, config);
2349     this.addEvents({
2350         // raw events
2351         /**
2352          * @event click
2353          * The raw click event for the entire grid.
2354          * @param {Roo.bootstrap.MenuItem} this
2355          * @param {Roo.EventObject} e
2356          */
2357         "click" : true
2358     });
2359 };
2360
2361 Roo.extend(Roo.bootstrap.MenuItem, Roo.bootstrap.Component,  {
2362     
2363     href : false,
2364     html : false,
2365     preventDefault: false,
2366     isContainer : false,
2367     active : false,
2368     fa: false,
2369     
2370     getAutoCreate : function(){
2371         
2372         if(this.isContainer){
2373             return {
2374                 tag: 'li',
2375                 cls: 'dropdown-menu-item'
2376             };
2377         }
2378         var ctag = {
2379             tag: 'span',
2380             html: 'Link'
2381         };
2382         
2383         var anc = {
2384             tag : 'a',
2385             href : '#',
2386             cn : [  ]
2387         };
2388         
2389         if (this.fa !== false) {
2390             anc.cn.push({
2391                 tag : 'i',
2392                 cls : 'fa fa-' + this.fa
2393             });
2394         }
2395         
2396         anc.cn.push(ctag);
2397         
2398         
2399         var cfg= {
2400             tag: 'li',
2401             cls: 'dropdown-menu-item',
2402             cn: [ anc ]
2403         };
2404         if (this.parent().type == 'treeview') {
2405             cfg.cls = 'treeview-menu';
2406         }
2407         if (this.active) {
2408             cfg.cls += ' active';
2409         }
2410         
2411         
2412         
2413         anc.href = this.href || cfg.cn[0].href ;
2414         ctag.html = this.html || cfg.cn[0].html ;
2415         return cfg;
2416     },
2417     
2418     initEvents: function()
2419     {
2420         if (this.parent().type == 'treeview') {
2421             this.el.select('a').on('click', this.onClick, this);
2422         }
2423         
2424         if (this.menu) {
2425             this.menu.parentType = this.xtype;
2426             this.menu.triggerEl = this.el;
2427             this.menu = this.addxtype(Roo.apply({}, this.menu));
2428         }
2429         
2430     },
2431     onClick : function(e)
2432     {
2433         Roo.log('item on click ');
2434         
2435         if(this.preventDefault){
2436             e.preventDefault();
2437         }
2438         //this.parent().hideMenuItems();
2439         
2440         this.fireEvent('click', this, e);
2441     },
2442     getEl : function()
2443     {
2444         return this.el;
2445     } 
2446 });
2447
2448  
2449
2450  /*
2451  * - LGPL
2452  *
2453  * menu separator
2454  * 
2455  */
2456
2457
2458 /**
2459  * @class Roo.bootstrap.MenuSeparator
2460  * @extends Roo.bootstrap.Component
2461  * Bootstrap MenuSeparator class
2462  * 
2463  * @constructor
2464  * Create a new MenuItem
2465  * @param {Object} config The config object
2466  */
2467
2468
2469 Roo.bootstrap.MenuSeparator = function(config){
2470     Roo.bootstrap.MenuSeparator.superclass.constructor.call(this, config);
2471 };
2472
2473 Roo.extend(Roo.bootstrap.MenuSeparator, Roo.bootstrap.Component,  {
2474     
2475     getAutoCreate : function(){
2476         var cfg = {
2477             cls: 'divider',
2478             tag : 'li'
2479         };
2480         
2481         return cfg;
2482     }
2483    
2484 });
2485
2486  
2487
2488  
2489 /*
2490 * Licence: LGPL
2491 */
2492
2493 /**
2494  * @class Roo.bootstrap.Modal
2495  * @extends Roo.bootstrap.Component
2496  * Bootstrap Modal class
2497  * @cfg {String} title Title of dialog
2498  * @cfg {String} html - the body of the dialog (for simple ones) - you can also use template..
2499  * @cfg {Roo.Template} tmpl - a template with variables. to use it, add a handler in show:method  adn
2500  * @cfg {Boolean} specificTitle default false
2501  * @cfg {Array} buttons Array of buttons or standard button set..
2502  * @cfg {String} buttonPosition (left|right|center) default right
2503  * @cfg {Boolean} animate default true
2504  * @cfg {Boolean} allow_close default true
2505  * @cfg {Boolean} fitwindow default false
2506  * @cfg {String} size (sm|lg) default empty
2507  *
2508  *
2509  * @constructor
2510  * Create a new Modal Dialog
2511  * @param {Object} config The config object
2512  */
2513
2514 Roo.bootstrap.Modal = function(config){
2515     Roo.bootstrap.Modal.superclass.constructor.call(this, config);
2516     this.addEvents({
2517         // raw events
2518         /**
2519          * @event btnclick
2520          * The raw btnclick event for the button
2521          * @param {Roo.EventObject} e
2522          */
2523         "btnclick" : true,
2524         /**
2525          * @event resize
2526          * Fire when dialog resize
2527          * @param {Roo.bootstrap.Modal} this
2528          * @param {Roo.EventObject} e
2529          */
2530         "resize" : true
2531     });
2532     this.buttons = this.buttons || [];
2533
2534     if (this.tmpl) {
2535         this.tmpl = Roo.factory(this.tmpl);
2536     }
2537
2538 };
2539
2540 Roo.extend(Roo.bootstrap.Modal, Roo.bootstrap.Component,  {
2541
2542     title : 'test dialog',
2543
2544     buttons : false,
2545
2546     // set on load...
2547
2548     html: false,
2549
2550     tmp: false,
2551
2552     specificTitle: false,
2553
2554     buttonPosition: 'right',
2555
2556     allow_close : true,
2557
2558     animate : true,
2559
2560     fitwindow: false,
2561
2562
2563      // private
2564     dialogEl: false,
2565     bodyEl:  false,
2566     footerEl:  false,
2567     titleEl:  false,
2568     closeEl:  false,
2569
2570     size: '',
2571
2572
2573     onRender : function(ct, position)
2574     {
2575         Roo.bootstrap.Component.superclass.onRender.call(this, ct, position);
2576
2577         if(!this.el){
2578             var cfg = Roo.apply({},  this.getAutoCreate());
2579             cfg.id = Roo.id();
2580             //if(!cfg.name){
2581             //    cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
2582             //}
2583             //if (!cfg.name.length) {
2584             //    delete cfg.name;
2585            // }
2586             if (this.cls) {
2587                 cfg.cls += ' ' + this.cls;
2588             }
2589             if (this.style) {
2590                 cfg.style = this.style;
2591             }
2592             this.el = Roo.get(document.body).createChild(cfg, position);
2593         }
2594         //var type = this.el.dom.type;
2595
2596
2597         if(this.tabIndex !== undefined){
2598             this.el.dom.setAttribute('tabIndex', this.tabIndex);
2599         }
2600
2601         this.dialogEl = this.el.select('.modal-dialog',true).first();
2602         this.bodyEl = this.el.select('.modal-body',true).first();
2603         this.closeEl = this.el.select('.modal-header .close', true).first();
2604         this.headerEl = this.el.select('.modal-header',true).first();
2605         this.titleEl = this.el.select('.modal-title',true).first();
2606         this.footerEl = this.el.select('.modal-footer',true).first();
2607
2608         this.maskEl = Roo.DomHelper.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
2609         this.maskEl.enableDisplayMode("block");
2610         this.maskEl.hide();
2611         //this.el.addClass("x-dlg-modal");
2612
2613         if (this.buttons.length) {
2614             Roo.each(this.buttons, function(bb) {
2615                 var b = Roo.apply({}, bb);
2616                 b.xns = b.xns || Roo.bootstrap;
2617                 b.xtype = b.xtype || 'Button';
2618                 if (typeof(b.listeners) == 'undefined') {
2619                     b.listeners = { click : this.onButtonClick.createDelegate(this)  };
2620                 }
2621
2622                 var btn = Roo.factory(b);
2623
2624                 btn.render(this.el.select('.modal-footer div').first());
2625
2626             },this);
2627         }
2628         // render the children.
2629         var nitems = [];
2630
2631         if(typeof(this.items) != 'undefined'){
2632             var items = this.items;
2633             delete this.items;
2634
2635             for(var i =0;i < items.length;i++) {
2636                 nitems.push(this.addxtype(Roo.apply({}, items[i])));
2637             }
2638         }
2639
2640         this.items = nitems;
2641
2642         // where are these used - they used to be body/close/footer
2643
2644
2645         this.initEvents();
2646         //this.el.addClass([this.fieldClass, this.cls]);
2647
2648     },
2649
2650     getAutoCreate : function(){
2651
2652
2653         var bdy = {
2654                 cls : 'modal-body',
2655                 html : this.html || ''
2656         };
2657
2658         var title = {
2659             tag: 'h4',
2660             cls : 'modal-title',
2661             html : this.title
2662         };
2663
2664         if(this.specificTitle){
2665             title = this.title;
2666
2667         };
2668
2669         var header = [];
2670         if (this.allow_close) {
2671             header.push({
2672                 tag: 'button',
2673                 cls : 'close',
2674                 html : '&times'
2675             });
2676         }
2677
2678         header.push(title);
2679
2680         var size = '';
2681
2682         if(this.size.length){
2683             size = 'modal-' + this.size;
2684         }
2685
2686         var modal = {
2687             cls: "modal",
2688             style : 'display: none',
2689             cn : [
2690                 {
2691                     cls: "modal-dialog " + size,
2692                     cn : [
2693                         {
2694                             cls : "modal-content",
2695                             cn : [
2696                                 {
2697                                     cls : 'modal-header',
2698                                     cn : header
2699                                 },
2700                                 bdy,
2701                                 {
2702                                     cls : 'modal-footer',
2703                                     cn : [
2704                                         {
2705                                             tag: 'div',
2706                                             cls: 'btn-' + this.buttonPosition
2707                                         }
2708                                     ]
2709
2710                                 }
2711
2712
2713                             ]
2714
2715                         }
2716                     ]
2717
2718                 }
2719             ]
2720         };
2721
2722         if(this.animate){
2723             modal.cls += ' fade';
2724         }
2725
2726         return modal;
2727
2728     },
2729     getChildContainer : function() {
2730
2731          return this.bodyEl;
2732
2733     },
2734     getButtonContainer : function() {
2735          return this.el.select('.modal-footer div',true).first();
2736
2737     },
2738     initEvents : function()
2739     {
2740         if (this.allow_close) {
2741             this.closeEl.on('click', this.hide, this);
2742         }
2743         Roo.EventManager.onWindowResize(this.resize, this, true);
2744
2745
2746     },
2747
2748     resize : function()
2749     {
2750         this.maskEl.setSize(Roo.lib.Dom.getViewWidth(true),  Roo.lib.Dom.getViewHeight(true));
2751         if (this.fitwindow) {
2752             var w = this.width || Roo.lib.Dom.getViewportWidth(true) - 30;
2753             var h = this.height || Roo.lib.Dom.getViewportHeight(true) - 60;
2754             this.setSize(w,h);
2755         }
2756     },
2757
2758     setSize : function(w,h)
2759     {
2760         if (!w && !h) {
2761             return;
2762         }
2763         this.resizeTo(w,h);
2764     },
2765
2766     show : function() {
2767
2768         if (!this.rendered) {
2769             this.render();
2770         }
2771
2772         this.el.setStyle('display', 'block');
2773
2774         if(this.animate){  // element has 'fade'  - so stuff happens after .3s ?- not sure why the delay?
2775             var _this = this;
2776             (function(){
2777                 this.el.addClass('in');
2778             }).defer(50, this);
2779         }else{
2780             this.el.addClass('in');
2781
2782         }
2783
2784         // not sure how we can show data in here..
2785         //if (this.tmpl) {
2786         //    this.getChildContainer().dom.innerHTML = this.tmpl.applyTemplate(this);
2787         //}
2788
2789         Roo.get(document.body).addClass("x-body-masked");
2790         
2791         this.maskEl.setSize(Roo.lib.Dom.getViewWidth(true),   Roo.lib.Dom.getViewHeight(true));
2792         this.maskEl.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
2793         this.maskEl.show();
2794         
2795         this.resize();
2796         
2797         this.fireEvent('show', this);
2798
2799         // set zindex here - otherwise it appears to be ignored...
2800         this.el.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
2801
2802         (function () {
2803             this.items.forEach( function(e) {
2804                 e.layout ? e.layout() : false;
2805
2806             });
2807         }).defer(100,this);
2808
2809     },
2810     hide : function()
2811     {
2812         if(this.fireEvent("beforehide", this) !== false){
2813             this.maskEl.hide();
2814             Roo.get(document.body).removeClass("x-body-masked");
2815             this.el.removeClass('in');
2816             this.el.select('.modal-dialog', true).first().setStyle('transform','');
2817
2818             if(this.animate){ // why
2819                 var _this = this;
2820                 (function(){ _this.el.setStyle('display', 'none'); }).defer(150);
2821             }else{
2822                 this.el.setStyle('display', 'none');
2823             }
2824             this.fireEvent('hide', this);
2825         }
2826     },
2827
2828     addButton : function(str, cb)
2829     {
2830
2831
2832         var b = Roo.apply({}, { html : str } );
2833         b.xns = b.xns || Roo.bootstrap;
2834         b.xtype = b.xtype || 'Button';
2835         if (typeof(b.listeners) == 'undefined') {
2836             b.listeners = { click : cb.createDelegate(this)  };
2837         }
2838
2839         var btn = Roo.factory(b);
2840
2841         btn.render(this.el.select('.modal-footer div').first());
2842
2843         return btn;
2844
2845     },
2846
2847     setDefaultButton : function(btn)
2848     {
2849         //this.el.select('.modal-footer').()
2850     },
2851     diff : false,
2852
2853     resizeTo: function(w,h)
2854     {
2855         // skip.. ?? why??
2856
2857         this.dialogEl.setWidth(w);
2858         if (this.diff === false) {
2859             this.diff = this.dialogEl.getHeight() - this.bodyEl.getHeight();
2860         }
2861
2862         this.bodyEl.setHeight(h-this.diff);
2863
2864         this.fireEvent('resize', this);
2865
2866     },
2867     setContentSize  : function(w, h)
2868     {
2869
2870     },
2871     onButtonClick: function(btn,e)
2872     {
2873         //Roo.log([a,b,c]);
2874         this.fireEvent('btnclick', btn.name, e);
2875     },
2876      /**
2877      * Set the title of the Dialog
2878      * @param {String} str new Title
2879      */
2880     setTitle: function(str) {
2881         this.titleEl.dom.innerHTML = str;
2882     },
2883     /**
2884      * Set the body of the Dialog
2885      * @param {String} str new Title
2886      */
2887     setBody: function(str) {
2888         this.bodyEl.dom.innerHTML = str;
2889     },
2890     /**
2891      * Set the body of the Dialog using the template
2892      * @param {Obj} data - apply this data to the template and replace the body contents.
2893      */
2894     applyBody: function(obj)
2895     {
2896         if (!this.tmpl) {
2897             Roo.log("Error - using apply Body without a template");
2898             //code
2899         }
2900         this.tmpl.overwrite(this.bodyEl, obj);
2901     }
2902
2903 });
2904
2905
2906 Roo.apply(Roo.bootstrap.Modal,  {
2907     /**
2908          * Button config that displays a single OK button
2909          * @type Object
2910          */
2911         OK :  [{
2912             name : 'ok',
2913             weight : 'primary',
2914             html : 'OK'
2915         }],
2916         /**
2917          * Button config that displays Yes and No buttons
2918          * @type Object
2919          */
2920         YESNO : [
2921             {
2922                 name  : 'no',
2923                 html : 'No'
2924             },
2925             {
2926                 name  :'yes',
2927                 weight : 'primary',
2928                 html : 'Yes'
2929             }
2930         ],
2931
2932         /**
2933          * Button config that displays OK and Cancel buttons
2934          * @type Object
2935          */
2936         OKCANCEL : [
2937             {
2938                name : 'cancel',
2939                 html : 'Cancel'
2940             },
2941             {
2942                 name : 'ok',
2943                 weight : 'primary',
2944                 html : 'OK'
2945             }
2946         ],
2947         /**
2948          * Button config that displays Yes, No and Cancel buttons
2949          * @type Object
2950          */
2951         YESNOCANCEL : [
2952             {
2953                 name : 'yes',
2954                 weight : 'primary',
2955                 html : 'Yes'
2956             },
2957             {
2958                 name : 'no',
2959                 html : 'No'
2960             },
2961             {
2962                 name : 'cancel',
2963                 html : 'Cancel'
2964             }
2965         ],
2966         
2967         zIndex : 10001
2968 });
2969 /*
2970  * - LGPL
2971  *
2972  * messagebox - can be used as a replace
2973  * 
2974  */
2975 /**
2976  * @class Roo.MessageBox
2977  * Utility class for generating different styles of message boxes.  The alias Roo.Msg can also be used.
2978  * Example usage:
2979  *<pre><code>
2980 // Basic alert:
2981 Roo.Msg.alert('Status', 'Changes saved successfully.');
2982
2983 // Prompt for user data:
2984 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
2985     if (btn == 'ok'){
2986         // process text value...
2987     }
2988 });
2989
2990 // Show a dialog using config options:
2991 Roo.Msg.show({
2992    title:'Save Changes?',
2993    msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
2994    buttons: Roo.Msg.YESNOCANCEL,
2995    fn: processResult,
2996    animEl: 'elId'
2997 });
2998 </code></pre>
2999  * @singleton
3000  */
3001 Roo.bootstrap.MessageBox = function(){
3002     var dlg, opt, mask, waitTimer;
3003     var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
3004     var buttons, activeTextEl, bwidth;
3005
3006     
3007     // private
3008     var handleButton = function(button){
3009         dlg.hide();
3010         Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
3011     };
3012
3013     // private
3014     var handleHide = function(){
3015         if(opt && opt.cls){
3016             dlg.el.removeClass(opt.cls);
3017         }
3018         //if(waitTimer){
3019         //    Roo.TaskMgr.stop(waitTimer);
3020         //    waitTimer = null;
3021         //}
3022     };
3023
3024     // private
3025     var updateButtons = function(b){
3026         var width = 0;
3027         if(!b){
3028             buttons["ok"].hide();
3029             buttons["cancel"].hide();
3030             buttons["yes"].hide();
3031             buttons["no"].hide();
3032             //dlg.footer.dom.style.display = 'none';
3033             return width;
3034         }
3035         dlg.footerEl.dom.style.display = '';
3036         for(var k in buttons){
3037             if(typeof buttons[k] != "function"){
3038                 if(b[k]){
3039                     buttons[k].show();
3040                     buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.bootstrap.MessageBox.buttonText[k]);
3041                     width += buttons[k].el.getWidth()+15;
3042                 }else{
3043                     buttons[k].hide();
3044                 }
3045             }
3046         }
3047         return width;
3048     };
3049
3050     // private
3051     var handleEsc = function(d, k, e){
3052         if(opt && opt.closable !== false){
3053             dlg.hide();
3054         }
3055         if(e){
3056             e.stopEvent();
3057         }
3058     };
3059
3060     return {
3061         /**
3062          * Returns a reference to the underlying {@link Roo.BasicDialog} element
3063          * @return {Roo.BasicDialog} The BasicDialog element
3064          */
3065         getDialog : function(){
3066            if(!dlg){
3067                 dlg = new Roo.bootstrap.Modal( {
3068                     //draggable: true,
3069                     //resizable:false,
3070                     //constraintoviewport:false,
3071                     //fixedcenter:true,
3072                     //collapsible : false,
3073                     //shim:true,
3074                     //modal: true,
3075                 //    width: 'auto',
3076                   //  height:100,
3077                     //buttonAlign:"center",
3078                     closeClick : function(){
3079                         if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
3080                             handleButton("no");
3081                         }else{
3082                             handleButton("cancel");
3083                         }
3084                     }
3085                 });
3086                 dlg.render();
3087                 dlg.on("hide", handleHide);
3088                 mask = dlg.mask;
3089                 //dlg.addKeyListener(27, handleEsc);
3090                 buttons = {};
3091                 this.buttons = buttons;
3092                 var bt = this.buttonText;
3093                 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
3094                 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
3095                 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
3096                 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
3097                 //Roo.log(buttons);
3098                 bodyEl = dlg.bodyEl.createChild({
3099
3100                     html:'<span class="roo-mb-text"></span><br /><input type="text" class="roo-mb-input" />' +
3101                         '<textarea class="roo-mb-textarea"></textarea>' +
3102                         '<div class="roo-mb-progress-wrap"><div class="roo-mb-progress"><div class="roo-mb-progress-bar">&#160;</div></div></div>'
3103                 });
3104                 msgEl = bodyEl.dom.firstChild;
3105                 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
3106                 textboxEl.enableDisplayMode();
3107                 textboxEl.addKeyListener([10,13], function(){
3108                     if(dlg.isVisible() && opt && opt.buttons){
3109                         if(opt.buttons.ok){
3110                             handleButton("ok");
3111                         }else if(opt.buttons.yes){
3112                             handleButton("yes");
3113                         }
3114                     }
3115                 });
3116                 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
3117                 textareaEl.enableDisplayMode();
3118                 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
3119                 progressEl.enableDisplayMode();
3120                 
3121                 // This is supposed to be the progessElement.. but I think it's controlling the height of everything..
3122                 //var pf = progressEl.dom.firstChild;
3123                 //if (pf) {
3124                     //pp = Roo.get(pf.firstChild);
3125                     //pp.setHeight(pf.offsetHeight);
3126                 //}
3127                 
3128             }
3129             return dlg;
3130         },
3131
3132         /**
3133          * Updates the message box body text
3134          * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
3135          * the XHTML-compliant non-breaking space character '&amp;#160;')
3136          * @return {Roo.MessageBox} This message box
3137          */
3138         updateText : function(text)
3139         {
3140             if(!dlg.isVisible() && !opt.width){
3141                 dlg.dialogEl.setStyle({ 'max-width' : this.maxWidth});
3142                 // dlg.resizeTo(this.maxWidth, 100); // forcing the height breaks long alerts()
3143             }
3144             msgEl.innerHTML = text || '&#160;';
3145       
3146             var cw =  Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
3147             //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
3148             var w = Math.max(
3149                     Math.min(opt.width || cw , this.maxWidth), 
3150                     Math.max(opt.minWidth || this.minWidth, bwidth)
3151             );
3152             if(opt.prompt){
3153                 activeTextEl.setWidth(w);
3154             }
3155             if(dlg.isVisible()){
3156                 dlg.fixedcenter = false;
3157             }
3158             // to big, make it scroll. = But as usual stupid IE does not support
3159             // !important..
3160             
3161             if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
3162                 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
3163                 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
3164             } else {
3165                 bodyEl.dom.style.height = '';
3166                 bodyEl.dom.style.overflowY = '';
3167             }
3168             if (cw > w) {
3169                 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
3170             } else {
3171                 bodyEl.dom.style.overflowX = '';
3172             }
3173             
3174             dlg.setContentSize(w, bodyEl.getHeight());
3175             if(dlg.isVisible()){
3176                 dlg.fixedcenter = true;
3177             }
3178             return this;
3179         },
3180
3181         /**
3182          * Updates a progress-style message box's text and progress bar.  Only relevant on message boxes
3183          * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
3184          * @param {Number} value Any number between 0 and 1 (e.g., .5)
3185          * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
3186          * @return {Roo.MessageBox} This message box
3187          */
3188         updateProgress : function(value, text){
3189             if(text){
3190                 this.updateText(text);
3191             }
3192             if (pp) { // weird bug on my firefox - for some reason this is not defined
3193                 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
3194             }
3195             return this;
3196         },        
3197
3198         /**
3199          * Returns true if the message box is currently displayed
3200          * @return {Boolean} True if the message box is visible, else false
3201          */
3202         isVisible : function(){
3203             return dlg && dlg.isVisible();  
3204         },
3205
3206         /**
3207          * Hides the message box if it is displayed
3208          */
3209         hide : function(){
3210             if(this.isVisible()){
3211                 dlg.hide();
3212             }  
3213         },
3214
3215         /**
3216          * Displays a new message box, or reinitializes an existing message box, based on the config options
3217          * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
3218          * The following config object properties are supported:
3219          * <pre>
3220 Property    Type             Description
3221 ----------  ---------------  ------------------------------------------------------------------------------------
3222 animEl            String/Element   An id or Element from which the message box should animate as it opens and
3223                                    closes (defaults to undefined)
3224 buttons           Object/Boolean   A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
3225                                    cancel:'Bar'}), or false to not show any buttons (defaults to false)
3226 closable          Boolean          False to hide the top-right close button (defaults to true).  Note that
3227                                    progress and wait dialogs will ignore this property and always hide the
3228                                    close button as they can only be closed programmatically.
3229 cls               String           A custom CSS class to apply to the message box element
3230 defaultTextHeight Number           The default height in pixels of the message box's multiline textarea if
3231                                    displayed (defaults to 75)
3232 fn                Function         A callback function to execute after closing the dialog.  The arguments to the
3233                                    function will be btn (the name of the button that was clicked, if applicable,
3234                                    e.g. "ok"), and text (the value of the active text field, if applicable).
3235                                    Progress and wait dialogs will ignore this option since they do not respond to
3236                                    user actions and can only be closed programmatically, so any required function
3237                                    should be called by the same code after it closes the dialog.
3238 icon              String           A CSS class that provides a background image to be used as an icon for
3239                                    the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
3240 maxWidth          Number           The maximum width in pixels of the message box (defaults to 600)
3241 minWidth          Number           The minimum width in pixels of the message box (defaults to 100)
3242 modal             Boolean          False to allow user interaction with the page while the message box is
3243                                    displayed (defaults to true)
3244 msg               String           A string that will replace the existing message box body text (defaults
3245                                    to the XHTML-compliant non-breaking space character '&#160;')
3246 multiline         Boolean          True to prompt the user to enter multi-line text (defaults to false)
3247 progress          Boolean          True to display a progress bar (defaults to false)
3248 progressText      String           The text to display inside the progress bar if progress = true (defaults to '')
3249 prompt            Boolean          True to prompt the user to enter single-line text (defaults to false)
3250 proxyDrag         Boolean          True to display a lightweight proxy while dragging (defaults to false)
3251 title             String           The title text
3252 value             String           The string value to set into the active textbox element if displayed
3253 wait              Boolean          True to display a progress bar (defaults to false)
3254 width             Number           The width of the dialog in pixels
3255 </pre>
3256          *
3257          * Example usage:
3258          * <pre><code>
3259 Roo.Msg.show({
3260    title: 'Address',
3261    msg: 'Please enter your address:',
3262    width: 300,
3263    buttons: Roo.MessageBox.OKCANCEL,
3264    multiline: true,
3265    fn: saveAddress,
3266    animEl: 'addAddressBtn'
3267 });
3268 </code></pre>
3269          * @param {Object} config Configuration options
3270          * @return {Roo.MessageBox} This message box
3271          */
3272         show : function(options)
3273         {
3274             
3275             // this causes nightmares if you show one dialog after another
3276             // especially on callbacks..
3277              
3278             if(this.isVisible()){
3279                 
3280                 this.hide();
3281                 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
3282                 Roo.log("Old Dialog Message:" +  msgEl.innerHTML );
3283                 Roo.log("New Dialog Message:" +  options.msg )
3284                 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
3285                 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
3286                 
3287             }
3288             var d = this.getDialog();
3289             opt = options;
3290             d.setTitle(opt.title || "&#160;");
3291             d.closeEl.setDisplayed(opt.closable !== false);
3292             activeTextEl = textboxEl;
3293             opt.prompt = opt.prompt || (opt.multiline ? true : false);
3294             if(opt.prompt){
3295                 if(opt.multiline){
3296                     textboxEl.hide();
3297                     textareaEl.show();
3298                     textareaEl.setHeight(typeof opt.multiline == "number" ?
3299                         opt.multiline : this.defaultTextHeight);
3300                     activeTextEl = textareaEl;
3301                 }else{
3302                     textboxEl.show();
3303                     textareaEl.hide();
3304                 }
3305             }else{
3306                 textboxEl.hide();
3307                 textareaEl.hide();
3308             }
3309             progressEl.setDisplayed(opt.progress === true);
3310             this.updateProgress(0);
3311             activeTextEl.dom.value = opt.value || "";
3312             if(opt.prompt){
3313                 dlg.setDefaultButton(activeTextEl);
3314             }else{
3315                 var bs = opt.buttons;
3316                 var db = null;
3317                 if(bs && bs.ok){
3318                     db = buttons["ok"];
3319                 }else if(bs && bs.yes){
3320                     db = buttons["yes"];
3321                 }
3322                 dlg.setDefaultButton(db);
3323             }
3324             bwidth = updateButtons(opt.buttons);
3325             this.updateText(opt.msg);
3326             if(opt.cls){
3327                 d.el.addClass(opt.cls);
3328             }
3329             d.proxyDrag = opt.proxyDrag === true;
3330             d.modal = opt.modal !== false;
3331             d.mask = opt.modal !== false ? mask : false;
3332             if(!d.isVisible()){
3333                 // force it to the end of the z-index stack so it gets a cursor in FF
3334                 document.body.appendChild(dlg.el.dom);
3335                 d.animateTarget = null;
3336                 d.show(options.animEl);
3337             }
3338             return this;
3339         },
3340
3341         /**
3342          * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
3343          * the user.  You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
3344          * and closing the message box when the process is complete.
3345          * @param {String} title The title bar text
3346          * @param {String} msg The message box body text
3347          * @return {Roo.MessageBox} This message box
3348          */
3349         progress : function(title, msg){
3350             this.show({
3351                 title : title,
3352                 msg : msg,
3353                 buttons: false,
3354                 progress:true,
3355                 closable:false,
3356                 minWidth: this.minProgressWidth,
3357                 modal : true
3358             });
3359             return this;
3360         },
3361
3362         /**
3363          * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
3364          * If a callback function is passed it will be called after the user clicks the button, and the
3365          * id of the button that was clicked will be passed as the only parameter to the callback
3366          * (could also be the top-right close button).
3367          * @param {String} title The title bar text
3368          * @param {String} msg The message box body text
3369          * @param {Function} fn (optional) The callback function invoked after the message box is closed
3370          * @param {Object} scope (optional) The scope of the callback function
3371          * @return {Roo.MessageBox} This message box
3372          */
3373         alert : function(title, msg, fn, scope)
3374         {
3375             this.show({
3376                 title : title,
3377                 msg : msg,
3378                 buttons: this.OK,
3379                 fn: fn,
3380                 closable : false,
3381                 scope : scope,
3382                 modal : true
3383             });
3384             return this;
3385         },
3386
3387         /**
3388          * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
3389          * interaction while waiting for a long-running process to complete that does not have defined intervals.
3390          * You are responsible for closing the message box when the process is complete.
3391          * @param {String} msg The message box body text
3392          * @param {String} title (optional) The title bar text
3393          * @return {Roo.MessageBox} This message box
3394          */
3395         wait : function(msg, title){
3396             this.show({
3397                 title : title,
3398                 msg : msg,
3399                 buttons: false,
3400                 closable:false,
3401                 progress:true,
3402                 modal:true,
3403                 width:300,
3404                 wait:true
3405             });
3406             waitTimer = Roo.TaskMgr.start({
3407                 run: function(i){
3408                     Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
3409                 },
3410                 interval: 1000
3411             });
3412             return this;
3413         },
3414
3415         /**
3416          * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
3417          * If a callback function is passed it will be called after the user clicks either button, and the id of the
3418          * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
3419          * @param {String} title The title bar text
3420          * @param {String} msg The message box body text
3421          * @param {Function} fn (optional) The callback function invoked after the message box is closed
3422          * @param {Object} scope (optional) The scope of the callback function
3423          * @return {Roo.MessageBox} This message box
3424          */
3425         confirm : function(title, msg, fn, scope){
3426             this.show({
3427                 title : title,
3428                 msg : msg,
3429                 buttons: this.YESNO,
3430                 fn: fn,
3431                 scope : scope,
3432                 modal : true
3433             });
3434             return this;
3435         },
3436
3437         /**
3438          * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
3439          * JavaScript's Window.prompt).  The prompt can be a single-line or multi-line textbox.  If a callback function
3440          * is passed it will be called after the user clicks either button, and the id of the button that was clicked
3441          * (could also be the top-right close button) and the text that was entered will be passed as the two
3442          * parameters to the callback.
3443          * @param {String} title The title bar text
3444          * @param {String} msg The message box body text
3445          * @param {Function} fn (optional) The callback function invoked after the message box is closed
3446          * @param {Object} scope (optional) The scope of the callback function
3447          * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
3448          * property, or the height in pixels to create the textbox (defaults to false / single-line)
3449          * @return {Roo.MessageBox} This message box
3450          */
3451         prompt : function(title, msg, fn, scope, multiline){
3452             this.show({
3453                 title : title,
3454                 msg : msg,
3455                 buttons: this.OKCANCEL,
3456                 fn: fn,
3457                 minWidth:250,
3458                 scope : scope,
3459                 prompt:true,
3460                 multiline: multiline,
3461                 modal : true
3462             });
3463             return this;
3464         },
3465
3466         /**
3467          * Button config that displays a single OK button
3468          * @type Object
3469          */
3470         OK : {ok:true},
3471         /**
3472          * Button config that displays Yes and No buttons
3473          * @type Object
3474          */
3475         YESNO : {yes:true, no:true},
3476         /**
3477          * Button config that displays OK and Cancel buttons
3478          * @type Object
3479          */
3480         OKCANCEL : {ok:true, cancel:true},
3481         /**
3482          * Button config that displays Yes, No and Cancel buttons
3483          * @type Object
3484          */
3485         YESNOCANCEL : {yes:true, no:true, cancel:true},
3486
3487         /**
3488          * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
3489          * @type Number
3490          */
3491         defaultTextHeight : 75,
3492         /**
3493          * The maximum width in pixels of the message box (defaults to 600)
3494          * @type Number
3495          */
3496         maxWidth : 600,
3497         /**
3498          * The minimum width in pixels of the message box (defaults to 100)
3499          * @type Number
3500          */
3501         minWidth : 100,
3502         /**
3503          * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
3504          * for setting a different minimum width than text-only dialogs may need (defaults to 250)
3505          * @type Number
3506          */
3507         minProgressWidth : 250,
3508         /**
3509          * An object containing the default button text strings that can be overriden for localized language support.
3510          * Supported properties are: ok, cancel, yes and no.
3511          * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
3512          * @type Object
3513          */
3514         buttonText : {
3515             ok : "OK",
3516             cancel : "Cancel",
3517             yes : "Yes",
3518             no : "No"
3519         }
3520     };
3521 }();
3522
3523 /**
3524  * Shorthand for {@link Roo.MessageBox}
3525  */
3526 Roo.MessageBox = Roo.MessageBox || Roo.bootstrap.MessageBox;
3527 Roo.Msg = Roo.Msg || Roo.MessageBox;
3528 /*
3529  * - LGPL
3530  *
3531  * navbar
3532  * 
3533  */
3534
3535 /**
3536  * @class Roo.bootstrap.Navbar
3537  * @extends Roo.bootstrap.Component
3538  * Bootstrap Navbar class
3539
3540  * @constructor
3541  * Create a new Navbar
3542  * @param {Object} config The config object
3543  */
3544
3545
3546 Roo.bootstrap.Navbar = function(config){
3547     Roo.bootstrap.Navbar.superclass.constructor.call(this, config);
3548     this.addEvents({
3549         // raw events
3550         /**
3551          * @event beforetoggle
3552          * Fire before toggle the menu
3553          * @param {Roo.EventObject} e
3554          */
3555         "beforetoggle" : true
3556     });
3557 };
3558
3559 Roo.extend(Roo.bootstrap.Navbar, Roo.bootstrap.Component,  {
3560     
3561     
3562    
3563     // private
3564     navItems : false,
3565     loadMask : false,
3566     
3567     
3568     getAutoCreate : function(){
3569         
3570         
3571         throw { message : "nav bar is now a abstract base class - use NavSimplebar / NavHeaderbar / NavSidebar etc..."};
3572         
3573     },
3574     
3575     initEvents :function ()
3576     {
3577         //Roo.log(this.el.select('.navbar-toggle',true));
3578         this.el.select('.navbar-toggle',true).on('click', function() {
3579             if(this.fireEvent('beforetoggle', this) !== false){
3580                this.el.select('.navbar-collapse',true).toggleClass('in');                                 
3581             }
3582             
3583         }, this);
3584         
3585         var mark = {
3586             tag: "div",
3587             cls:"x-dlg-mask"
3588         };
3589         
3590         this.maskEl = Roo.DomHelper.append(this.el, mark, true);
3591         
3592         var size = this.el.getSize();
3593         this.maskEl.setSize(size.width, size.height);
3594         this.maskEl.enableDisplayMode("block");
3595         this.maskEl.hide();
3596         
3597         if(this.loadMask){
3598             this.maskEl.show();
3599         }
3600     },
3601     
3602     
3603     getChildContainer : function()
3604     {
3605         if (this.el.select('.collapse').getCount()) {
3606             return this.el.select('.collapse',true).first();
3607         }
3608         
3609         return this.el;
3610     },
3611     
3612     mask : function()
3613     {
3614         this.maskEl.show();
3615     },
3616     
3617     unmask : function()
3618     {
3619         this.maskEl.hide();
3620     } 
3621     
3622     
3623     
3624     
3625 });
3626
3627
3628
3629  
3630
3631  /*
3632  * - LGPL
3633  *
3634  * navbar
3635  * 
3636  */
3637
3638 /**
3639  * @class Roo.bootstrap.NavSimplebar
3640  * @extends Roo.bootstrap.Navbar
3641  * Bootstrap Sidebar class
3642  *
3643  * @cfg {Boolean} inverse is inverted color
3644  * 
3645  * @cfg {String} type (nav | pills | tabs)
3646  * @cfg {Boolean} arrangement stacked | justified
3647  * @cfg {String} align (left | right) alignment
3648  * 
3649  * @cfg {Boolean} main (true|false) main nav bar? default false
3650  * @cfg {Boolean} loadMask (true|false) loadMask on the bar
3651  * 
3652  * @cfg {String} tag (header|footer|nav|div) default is nav 
3653
3654  * 
3655  * 
3656  * 
3657  * @constructor
3658  * Create a new Sidebar
3659  * @param {Object} config The config object
3660  */
3661
3662
3663 Roo.bootstrap.NavSimplebar = function(config){
3664     Roo.bootstrap.NavSimplebar.superclass.constructor.call(this, config);
3665 };
3666
3667 Roo.extend(Roo.bootstrap.NavSimplebar, Roo.bootstrap.Navbar,  {
3668     
3669     inverse: false,
3670     
3671     type: false,
3672     arrangement: '',
3673     align : false,
3674     
3675     
3676     
3677     main : false,
3678     
3679     
3680     tag : false,
3681     
3682     
3683     getAutoCreate : function(){
3684         
3685         
3686         var cfg = {
3687             tag : this.tag || 'div',
3688             cls : 'navbar'
3689         };
3690           
3691         
3692         cfg.cn = [
3693             {
3694                 cls: 'nav',
3695                 tag : 'ul'
3696             }
3697         ];
3698         
3699          
3700         this.type = this.type || 'nav';
3701         if (['tabs','pills'].indexOf(this.type)!==-1) {
3702             cfg.cn[0].cls += ' nav-' + this.type
3703         
3704         
3705         } else {
3706             if (this.type!=='nav') {
3707                 Roo.log('nav type must be nav/tabs/pills')
3708             }
3709             cfg.cn[0].cls += ' navbar-nav'
3710         }
3711         
3712         
3713         
3714         
3715         if (['stacked','justified'].indexOf(this.arrangement)!==-1) {
3716             cfg.cn[0].cls += ' nav-' + this.arrangement;
3717         }
3718         
3719         
3720         if (this.align === 'right') {
3721             cfg.cn[0].cls += ' navbar-right';
3722         }
3723         
3724         if (this.inverse) {
3725             cfg.cls += ' navbar-inverse';
3726             
3727         }
3728         
3729         
3730         return cfg;
3731     
3732         
3733     }
3734     
3735     
3736     
3737 });
3738
3739
3740
3741  
3742
3743  
3744        /*
3745  * - LGPL
3746  *
3747  * navbar
3748  * 
3749  */
3750
3751 /**
3752  * @class Roo.bootstrap.NavHeaderbar
3753  * @extends Roo.bootstrap.NavSimplebar
3754  * Bootstrap Sidebar class
3755  *
3756  * @cfg {String} brand what is brand
3757  * @cfg {String} position (fixed-top|fixed-bottom|static-top) position
3758  * @cfg {String} brand_href href of the brand
3759  * @cfg {Boolean} srButton generate the (screen reader / mobile) sr-only button   default true
3760  * @cfg {Boolean} autohide a top nav bar header that hides on scroll.
3761  * @cfg {Boolean} desktopCenter should the header be centered on desktop using a container class
3762  * @cfg {Roo.bootstrap.Row} mobilerow - a row to display on mobile only..
3763  * 
3764  * @constructor
3765  * Create a new Sidebar
3766  * @param {Object} config The config object
3767  */
3768
3769
3770 Roo.bootstrap.NavHeaderbar = function(config){
3771     Roo.bootstrap.NavHeaderbar.superclass.constructor.call(this, config);
3772       
3773 };
3774
3775 Roo.extend(Roo.bootstrap.NavHeaderbar, Roo.bootstrap.NavSimplebar,  {
3776     
3777     position: '',
3778     brand: '',
3779     brand_href: false,
3780     srButton : true,
3781     autohide : false,
3782     desktopCenter : false,
3783    
3784     
3785     getAutoCreate : function(){
3786         
3787         var   cfg = {
3788             tag: this.nav || 'nav',
3789             cls: 'navbar',
3790             role: 'navigation',
3791             cn: []
3792         };
3793         
3794         var cn = cfg.cn;
3795         if (this.desktopCenter) {
3796             cn.push({cls : 'container', cn : []});
3797             cn = cn[0].cn;
3798         }
3799         
3800         if(this.srButton){
3801             cn.push({
3802                 tag: 'div',
3803                 cls: 'navbar-header',
3804                 cn: [
3805                     {
3806                         tag: 'button',
3807                         type: 'button',
3808                         cls: 'navbar-toggle',
3809                         'data-toggle': 'collapse',
3810                         cn: [
3811                             {
3812                                 tag: 'span',
3813                                 cls: 'sr-only',
3814                                 html: 'Toggle navigation'
3815                             },
3816                             {
3817                                 tag: 'span',
3818                                 cls: 'icon-bar'
3819                             },
3820                             {
3821                                 tag: 'span',
3822                                 cls: 'icon-bar'
3823                             },
3824                             {
3825                                 tag: 'span',
3826                                 cls: 'icon-bar'
3827                             }
3828                         ]
3829                     }
3830                 ]
3831             });
3832         }
3833         
3834         cn.push({
3835             tag: 'div',
3836             cls: 'collapse navbar-collapse',
3837             cn : []
3838         });
3839         
3840         cfg.cls += this.inverse ? ' navbar-inverse' : ' navbar-default';
3841         
3842         if (['fixed-top','fixed-bottom','static-top'].indexOf(this.position)>-1) {
3843             cfg.cls += ' navbar-' + this.position;
3844             
3845             // tag can override this..
3846             
3847             cfg.tag = this.tag || (this.position  == 'fixed-bottom' ? 'footer' : 'header');
3848         }
3849         
3850         if (this.brand !== '') {
3851             cn[0].cn.push({
3852                 tag: 'a',
3853                 href: this.brand_href ? this.brand_href : '#',
3854                 cls: 'navbar-brand',
3855                 cn: [
3856                 this.brand
3857                 ]
3858             });
3859         }
3860         
3861         if(this.main){
3862             cfg.cls += ' main-nav';
3863         }
3864         
3865         
3866         return cfg;
3867
3868         
3869     },
3870     getHeaderChildContainer : function()
3871     {
3872         if (this.srButton && this.el.select('.navbar-header').getCount()) {
3873             return this.el.select('.navbar-header',true).first();
3874         }
3875         
3876         return this.getChildContainer();
3877     },
3878     
3879     
3880     initEvents : function()
3881     {
3882         Roo.bootstrap.NavHeaderbar.superclass.initEvents.call(this);
3883         
3884         if (this.autohide) {
3885             
3886             var prevScroll = 0;
3887             var ft = this.el;
3888             
3889             Roo.get(document).on('scroll',function(e) {
3890                 var ns = Roo.get(document).getScroll().top;
3891                 var os = prevScroll;
3892                 prevScroll = ns;
3893                 
3894                 if(ns > os){
3895                     ft.removeClass('slideDown');
3896                     ft.addClass('slideUp');
3897                     return;
3898                 }
3899                 ft.removeClass('slideUp');
3900                 ft.addClass('slideDown');
3901                  
3902               
3903           },this);
3904         }
3905     }    
3906     
3907 });
3908
3909
3910
3911  
3912
3913  /*
3914  * - LGPL
3915  *
3916  * navbar
3917  * 
3918  */
3919
3920 /**
3921  * @class Roo.bootstrap.NavSidebar
3922  * @extends Roo.bootstrap.Navbar
3923  * Bootstrap Sidebar class
3924  * 
3925  * @constructor
3926  * Create a new Sidebar
3927  * @param {Object} config The config object
3928  */
3929
3930
3931 Roo.bootstrap.NavSidebar = function(config){
3932     Roo.bootstrap.NavSidebar.superclass.constructor.call(this, config);
3933 };
3934
3935 Roo.extend(Roo.bootstrap.NavSidebar, Roo.bootstrap.Navbar,  {
3936     
3937     sidebar : true, // used by Navbar Item and NavbarGroup at present...
3938     
3939     getAutoCreate : function(){
3940         
3941         
3942         return  {
3943             tag: 'div',
3944             cls: 'sidebar sidebar-nav'
3945         };
3946     
3947         
3948     }
3949     
3950     
3951     
3952 });
3953
3954
3955
3956  
3957
3958  /*
3959  * - LGPL
3960  *
3961  * nav group
3962  * 
3963  */
3964
3965 /**
3966  * @class Roo.bootstrap.NavGroup
3967  * @extends Roo.bootstrap.Component
3968  * Bootstrap NavGroup class
3969  * @cfg {String} align (left|right)
3970  * @cfg {Boolean} inverse
3971  * @cfg {String} type (nav|pills|tab) default nav
3972  * @cfg {String} navId - reference Id for navbar.
3973
3974  * 
3975  * @constructor
3976  * Create a new nav group
3977  * @param {Object} config The config object
3978  */
3979
3980 Roo.bootstrap.NavGroup = function(config){
3981     Roo.bootstrap.NavGroup.superclass.constructor.call(this, config);
3982     this.navItems = [];
3983    
3984     Roo.bootstrap.NavGroup.register(this);
3985      this.addEvents({
3986         /**
3987              * @event changed
3988              * Fires when the active item changes
3989              * @param {Roo.bootstrap.NavGroup} this
3990              * @param {Roo.bootstrap.Navbar.Item} selected The item selected
3991              * @param {Roo.bootstrap.Navbar.Item} prev The previously selected item 
3992          */
3993         'changed': true
3994      });
3995     
3996 };
3997
3998 Roo.extend(Roo.bootstrap.NavGroup, Roo.bootstrap.Component,  {
3999     
4000     align: '',
4001     inverse: false,
4002     form: false,
4003     type: 'nav',
4004     navId : '',
4005     // private
4006     
4007     navItems : false, 
4008     
4009     getAutoCreate : function()
4010     {
4011         var cfg = Roo.apply({}, Roo.bootstrap.NavGroup.superclass.getAutoCreate.call(this));
4012         
4013         cfg = {
4014             tag : 'ul',
4015             cls: 'nav' 
4016         };
4017         
4018         if (['tabs','pills'].indexOf(this.type)!==-1) {
4019             cfg.cls += ' nav-' + this.type
4020         } else {
4021             if (this.type!=='nav') {
4022                 Roo.log('nav type must be nav/tabs/pills')
4023             }
4024             cfg.cls += ' navbar-nav'
4025         }
4026         
4027         if (this.parent() && this.parent().sidebar) {
4028             cfg = {
4029                 tag: 'ul',
4030                 cls: 'dashboard-menu sidebar-menu'
4031             };
4032             
4033             return cfg;
4034         }
4035         
4036         if (this.form === true) {
4037             cfg = {
4038                 tag: 'form',
4039                 cls: 'navbar-form'
4040             };
4041             
4042             if (this.align === 'right') {
4043                 cfg.cls += ' navbar-right';
4044             } else {
4045                 cfg.cls += ' navbar-left';
4046             }
4047         }
4048         
4049         if (this.align === 'right') {
4050             cfg.cls += ' navbar-right';
4051         }
4052         
4053         if (this.inverse) {
4054             cfg.cls += ' navbar-inverse';
4055             
4056         }
4057         
4058         
4059         return cfg;
4060     },
4061     /**
4062     * sets the active Navigation item
4063     * @param {Roo.bootstrap.NavItem} the new current navitem
4064     */
4065     setActiveItem : function(item)
4066     {
4067         var prev = false;
4068         Roo.each(this.navItems, function(v){
4069             if (v == item) {
4070                 return ;
4071             }
4072             if (v.isActive()) {
4073                 v.setActive(false, true);
4074                 prev = v;
4075                 
4076             }
4077             
4078         });
4079
4080         item.setActive(true, true);
4081         this.fireEvent('changed', this, item, prev);
4082         
4083         
4084     },
4085     /**
4086     * gets the active Navigation item
4087     * @return {Roo.bootstrap.NavItem} the current navitem
4088     */
4089     getActive : function()
4090     {
4091         
4092         var prev = false;
4093         Roo.each(this.navItems, function(v){
4094             
4095             if (v.isActive()) {
4096                 prev = v;
4097                 
4098             }
4099             
4100         });
4101         return prev;
4102     },
4103     
4104     indexOfNav : function()
4105     {
4106         
4107         var prev = false;
4108         Roo.each(this.navItems, function(v,i){
4109             
4110             if (v.isActive()) {
4111                 prev = i;
4112                 
4113             }
4114             
4115         });
4116         return prev;
4117     },
4118     /**
4119     * adds a Navigation item
4120     * @param {Roo.bootstrap.NavItem} the navitem to add
4121     */
4122     addItem : function(cfg)
4123     {
4124         var cn = new Roo.bootstrap.NavItem(cfg);
4125         this.register(cn);
4126         cn.parentId = this.id;
4127         cn.onRender(this.el, null);
4128         return cn;
4129     },
4130     /**
4131     * register a Navigation item
4132     * @param {Roo.bootstrap.NavItem} the navitem to add
4133     */
4134     register : function(item)
4135     {
4136         this.navItems.push( item);
4137         item.navId = this.navId;
4138     
4139     },
4140     
4141     /**
4142     * clear all the Navigation item
4143     */
4144    
4145     clearAll : function()
4146     {
4147         this.navItems = [];
4148         this.el.dom.innerHTML = '';
4149     },
4150     
4151     getNavItem: function(tabId)
4152     {
4153         var ret = false;
4154         Roo.each(this.navItems, function(e) {
4155             if (e.tabId == tabId) {
4156                ret =  e;
4157                return false;
4158             }
4159             return true;
4160             
4161         });
4162         return ret;
4163     },
4164     
4165     setActiveNext : function()
4166     {
4167         var i = this.indexOfNav(this.getActive());
4168         if (i > this.navItems.length) {
4169             return;
4170         }
4171         this.setActiveItem(this.navItems[i+1]);
4172     },
4173     setActivePrev : function()
4174     {
4175         var i = this.indexOfNav(this.getActive());
4176         if (i  < 1) {
4177             return;
4178         }
4179         this.setActiveItem(this.navItems[i-1]);
4180     },
4181     clearWasActive : function(except) {
4182         Roo.each(this.navItems, function(e) {
4183             if (e.tabId != except.tabId && e.was_active) {
4184                e.was_active = false;
4185                return false;
4186             }
4187             return true;
4188             
4189         });
4190     },
4191     getWasActive : function ()
4192     {
4193         var r = false;
4194         Roo.each(this.navItems, function(e) {
4195             if (e.was_active) {
4196                r = e;
4197                return false;
4198             }
4199             return true;
4200             
4201         });
4202         return r;
4203     }
4204     
4205     
4206 });
4207
4208  
4209 Roo.apply(Roo.bootstrap.NavGroup, {
4210     
4211     groups: {},
4212      /**
4213     * register a Navigation Group
4214     * @param {Roo.bootstrap.NavGroup} the navgroup to add
4215     */
4216     register : function(navgrp)
4217     {
4218         this.groups[navgrp.navId] = navgrp;
4219         
4220     },
4221     /**
4222     * fetch a Navigation Group based on the navigation ID
4223     * @param {string} the navgroup to add
4224     * @returns {Roo.bootstrap.NavGroup} the navgroup 
4225     */
4226     get: function(navId) {
4227         if (typeof(this.groups[navId]) == 'undefined') {
4228             return false;
4229             //this.register(new Roo.bootstrap.NavGroup({ navId : navId }));
4230         }
4231         return this.groups[navId] ;
4232     }
4233     
4234     
4235     
4236 });
4237
4238  /*
4239  * - LGPL
4240  *
4241  * row
4242  * 
4243  */
4244
4245 /**
4246  * @class Roo.bootstrap.NavItem
4247  * @extends Roo.bootstrap.Component
4248  * Bootstrap Navbar.NavItem class
4249  * @cfg {String} href  link to
4250  * @cfg {String} html content of button
4251  * @cfg {String} badge text inside badge
4252  * @cfg {String} badgecls (bg-green|bg-red|bg-yellow)the extra classes for the badge
4253  * @cfg {String} glyphicon name of glyphicon
4254  * @cfg {String} icon name of font awesome icon
4255  * @cfg {Boolean} active Is item active
4256  * @cfg {Boolean} disabled Is item disabled
4257  
4258  * @cfg {Boolean} preventDefault (true | false) default false
4259  * @cfg {String} tabId the tab that this item activates.
4260  * @cfg {String} tagtype (a|span) render as a href or span?
4261  * @cfg {Boolean} animateRef (true|false) link to element default false  
4262   
4263  * @constructor
4264  * Create a new Navbar Item
4265  * @param {Object} config The config object
4266  */
4267 Roo.bootstrap.NavItem = function(config){
4268     Roo.bootstrap.NavItem.superclass.constructor.call(this, config);
4269     this.addEvents({
4270         // raw events
4271         /**
4272          * @event click
4273          * The raw click event for the entire grid.
4274          * @param {Roo.EventObject} e
4275          */
4276         "click" : true,
4277          /**
4278             * @event changed
4279             * Fires when the active item active state changes
4280             * @param {Roo.bootstrap.NavItem} this
4281             * @param {boolean} state the new state
4282              
4283          */
4284         'changed': true,
4285         /**
4286             * @event scrollto
4287             * Fires when scroll to element
4288             * @param {Roo.bootstrap.NavItem} this
4289             * @param {Object} options
4290             * @param {Roo.EventObject} e
4291              
4292          */
4293         'scrollto': true
4294     });
4295    
4296 };
4297
4298 Roo.extend(Roo.bootstrap.NavItem, Roo.bootstrap.Component,  {
4299     
4300     href: false,
4301     html: '',
4302     badge: '',
4303     icon: false,
4304     glyphicon: false,
4305     active: false,
4306     preventDefault : false,
4307     tabId : false,
4308     tagtype : 'a',
4309     disabled : false,
4310     animateRef : false,
4311     was_active : false,
4312     
4313     getAutoCreate : function(){
4314          
4315         var cfg = {
4316             tag: 'li',
4317             cls: 'nav-item'
4318             
4319         };
4320         
4321         if (this.active) {
4322             cfg.cls = typeof(cfg.cls) == 'undefined' ? 'active' : cfg.cls + ' active';
4323         }
4324         if (this.disabled) {
4325             cfg.cls += ' disabled';
4326         }
4327         
4328         if (this.href || this.html || this.glyphicon || this.icon) {
4329             cfg.cn = [
4330                 {
4331                     tag: this.tagtype,
4332                     href : this.href || "#",
4333                     html: this.html || ''
4334                 }
4335             ];
4336             
4337             if (this.icon) {
4338                 cfg.cn[0].html = '<i class="'+this.icon+'"></i> <span>' + cfg.cn[0].html + '</span>'
4339             }
4340
4341             if(this.glyphicon) {
4342                 cfg.cn[0].html = '<span class="glyphicon glyphicon-' + this.glyphicon + '"></span> '  + cfg.cn[0].html;
4343             }
4344             
4345             if (this.menu) {
4346                 
4347                 cfg.cn[0].html += " <span class='caret'></span>";
4348              
4349             }
4350             
4351             if (this.badge !== '') {
4352                  
4353                 cfg.cn[0].html += ' <span class="badge">' + this.badge + '</span>';
4354             }
4355         }
4356         
4357         
4358         
4359         return cfg;
4360     },
4361     initEvents: function() 
4362     {
4363         if (typeof (this.menu) != 'undefined') {
4364             this.menu.parentType = this.xtype;
4365             this.menu.triggerEl = this.el;
4366             this.menu = this.addxtype(Roo.apply({}, this.menu));
4367         }
4368         
4369         this.el.select('a',true).on('click', this.onClick, this);
4370         
4371         if(this.tagtype == 'span'){
4372             this.el.select('span',true).on('click', this.onClick, this);
4373         }
4374        
4375         // at this point parent should be available..
4376         this.parent().register(this);
4377     },
4378     
4379     onClick : function(e)
4380     {
4381         if (e.getTarget('.dropdown-menu-item')) {
4382             // did you click on a menu itemm.... - then don't trigger onclick..
4383             return;
4384         }
4385         
4386         if(
4387                 this.preventDefault || 
4388                 this.href == '#' 
4389         ){
4390             Roo.log("NavItem - prevent Default?");
4391             e.preventDefault();
4392         }
4393         
4394         if (this.disabled) {
4395             return;
4396         }
4397         
4398         var tg = Roo.bootstrap.TabGroup.get(this.navId);
4399         if (tg && tg.transition) {
4400             Roo.log("waiting for the transitionend");
4401             return;
4402         }
4403         
4404         
4405         
4406         //Roo.log("fire event clicked");
4407         if(this.fireEvent('click', this, e) === false){
4408             return;
4409         };
4410         
4411         if(this.tagtype == 'span'){
4412             return;
4413         }
4414         
4415         //Roo.log(this.href);
4416         var ael = this.el.select('a',true).first();
4417         //Roo.log(ael);
4418         
4419         if(ael && this.animateRef && this.href.indexOf('#') > -1){
4420             //Roo.log(["test:",ael.dom.href.split("#")[0], document.location.toString().split("#")[0]]);
4421             if (ael.dom.href.split("#")[0] != document.location.toString().split("#")[0]) {
4422                 return; // ignore... - it's a 'hash' to another page.
4423             }
4424             Roo.log("NavItem - prevent Default?");
4425             e.preventDefault();
4426             this.scrollToElement(e);
4427         }
4428         
4429         
4430         var p =  this.parent();
4431    
4432         if (['tabs','pills'].indexOf(p.type)!==-1) {
4433             if (typeof(p.setActiveItem) !== 'undefined') {
4434                 p.setActiveItem(this);
4435             }
4436         }
4437         
4438         // if parent is a navbarheader....- and link is probably a '#' page ref.. then remove the expanded menu.
4439         if (p.parentType == 'NavHeaderbar' && !this.menu) {
4440             // remove the collapsed menu expand...
4441             p.parent().el.select('.navbar-collapse',true).removeClass('in');  
4442         }
4443     },
4444     
4445     isActive: function () {
4446         return this.active
4447     },
4448     setActive : function(state, fire, is_was_active)
4449     {
4450         if (this.active && !state && this.navId) {
4451             this.was_active = true;
4452             var nv = Roo.bootstrap.NavGroup.get(this.navId);
4453             if (nv) {
4454                 nv.clearWasActive(this);
4455             }
4456             
4457         }
4458         this.active = state;
4459         
4460         if (!state ) {
4461             this.el.removeClass('active');
4462         } else if (!this.el.hasClass('active')) {
4463             this.el.addClass('active');
4464         }
4465         if (fire) {
4466             this.fireEvent('changed', this, state);
4467         }
4468         
4469         // show a panel if it's registered and related..
4470         
4471         if (!this.navId || !this.tabId || !state || is_was_active) {
4472             return;
4473         }
4474         
4475         var tg = Roo.bootstrap.TabGroup.get(this.navId);
4476         if (!tg) {
4477             return;
4478         }
4479         var pan = tg.getPanelByName(this.tabId);
4480         if (!pan) {
4481             return;
4482         }
4483         // if we can not flip to new panel - go back to old nav highlight..
4484         if (false == tg.showPanel(pan)) {
4485             var nv = Roo.bootstrap.NavGroup.get(this.navId);
4486             if (nv) {
4487                 var onav = nv.getWasActive();
4488                 if (onav) {
4489                     onav.setActive(true, false, true);
4490                 }
4491             }
4492             
4493         }
4494         
4495         
4496         
4497     },
4498      // this should not be here...
4499     setDisabled : function(state)
4500     {
4501         this.disabled = state;
4502         if (!state ) {
4503             this.el.removeClass('disabled');
4504         } else if (!this.el.hasClass('disabled')) {
4505             this.el.addClass('disabled');
4506         }
4507         
4508     },
4509     
4510     /**
4511      * Fetch the element to display the tooltip on.
4512      * @return {Roo.Element} defaults to this.el
4513      */
4514     tooltipEl : function()
4515     {
4516         return this.el.select('' + this.tagtype + '', true).first();
4517     },
4518     
4519     scrollToElement : function(e)
4520     {
4521         var c = document.body;
4522         
4523         /*
4524          * Firefox / IE places the overflow at the html level, unless specifically styled to behave differently.
4525          */
4526         if(Roo.isFirefox || Roo.isIE || Roo.isIE11){
4527             c = document.documentElement;
4528         }
4529         
4530         var target = Roo.get(c).select('a[name=' + this.href.split('#')[1] +']', true).first();
4531         
4532         if(!target){
4533             return;
4534         }
4535
4536         var o = target.calcOffsetsTo(c);
4537         
4538         var options = {
4539             target : target,
4540             value : o[1]
4541         };
4542         
4543         this.fireEvent('scrollto', this, options, e);
4544         
4545         Roo.get(c).scrollTo('top', options.value, true);
4546         
4547         return;
4548     }
4549 });
4550  
4551
4552  /*
4553  * - LGPL
4554  *
4555  * sidebar item
4556  *
4557  *  li
4558  *    <span> icon </span>
4559  *    <span> text </span>
4560  *    <span>badge </span>
4561  */
4562
4563 /**
4564  * @class Roo.bootstrap.NavSidebarItem
4565  * @extends Roo.bootstrap.NavItem
4566  * Bootstrap Navbar.NavSidebarItem class
4567  * {String} badgeWeight (default|primary|success|info|warning|danger)the extra classes for the badge
4568  * {Boolean} open is the menu open
4569  * {Boolean} buttonView use button as the tigger el rather that a (default false)
4570  * {String} buttonWeight (default|primary|success|info|warning|danger)the extra classes for the button
4571  * {String} buttonSize (sm|md|lg)the extra classes for the button
4572  * {Boolean} showArrow show arrow next to the text (default true)
4573  * @constructor
4574  * Create a new Navbar Button
4575  * @param {Object} config The config object
4576  */
4577 Roo.bootstrap.NavSidebarItem = function(config){
4578     Roo.bootstrap.NavSidebarItem.superclass.constructor.call(this, config);
4579     this.addEvents({
4580         // raw events
4581         /**
4582          * @event click
4583          * The raw click event for the entire grid.
4584          * @param {Roo.EventObject} e
4585          */
4586         "click" : true,
4587          /**
4588             * @event changed
4589             * Fires when the active item active state changes
4590             * @param {Roo.bootstrap.NavSidebarItem} this
4591             * @param {boolean} state the new state
4592              
4593          */
4594         'changed': true
4595     });
4596    
4597 };
4598
4599 Roo.extend(Roo.bootstrap.NavSidebarItem, Roo.bootstrap.NavItem,  {
4600     
4601     badgeWeight : 'default',
4602     
4603     open: false,
4604     
4605     buttonView : false,
4606     
4607     buttonWeight : 'default',
4608     
4609     buttonSize : 'md',
4610     
4611     showArrow : true,
4612     
4613     getAutoCreate : function(){
4614         
4615         
4616         var a = {
4617                 tag: 'a',
4618                 href : this.href || '#',
4619                 cls: '',
4620                 html : '',
4621                 cn : []
4622         };
4623         
4624         if(this.buttonView){
4625             a = {
4626                 tag: 'button',
4627                 href : this.href || '#',
4628                 cls: 'btn btn-' + this.buttonWeight + ' btn-' + this.buttonSize + 'roo-button-dropdown-toggle',
4629                 html : this.html,
4630                 cn : []
4631             };
4632         }
4633         
4634         var cfg = {
4635             tag: 'li',
4636             cls: '',
4637             cn: [ a ]
4638         };
4639         
4640         if (this.active) {
4641             cfg.cls += ' active';
4642         }
4643         
4644         if (this.disabled) {
4645             cfg.cls += ' disabled';
4646         }
4647         if (this.open) {
4648             cfg.cls += ' open x-open';
4649         }
4650         // left icon..
4651         if (this.glyphicon || this.icon) {
4652             var c = this.glyphicon  ? ('glyphicon glyphicon-'+this.glyphicon)  : this.icon;
4653             a.cn.push({ tag : 'i', cls : c }) ;
4654         }
4655         
4656         if(!this.buttonView){
4657             var span = {
4658                 tag: 'span',
4659                 html : this.html || ''
4660             };
4661
4662             a.cn.push(span);
4663             
4664         }
4665         
4666         if (this.badge !== '') {
4667             a.cn.push({ tag: 'span',  cls : 'badge pull-right badge-' + this.badgeWeight, html: this.badge }); 
4668         }
4669         
4670         if (this.menu) {
4671             
4672             if(this.showArrow){
4673                 a.cn.push({ tag : 'i', cls : 'glyphicon glyphicon-chevron-down pull-right'});
4674             }
4675             
4676             a.cls += ' dropdown-toggle treeview' ;
4677         }
4678         
4679         return cfg;
4680     },
4681     
4682     initEvents : function()
4683     { 
4684         if (typeof (this.menu) != 'undefined') {
4685             this.menu.parentType = this.xtype;
4686             this.menu.triggerEl = this.el;
4687             this.menu = this.addxtype(Roo.apply({}, this.menu));
4688         }
4689         
4690         this.el.on('click', this.onClick, this);
4691         
4692         if(this.badge !== ''){
4693             this.badgeEl = this.el.select('.badge', true).first().setVisibilityMode(Roo.Element.DISPLAY);
4694         }
4695         
4696     },
4697     
4698     onClick : function(e)
4699     {
4700         if(this.disabled){
4701             e.preventDefault();
4702             return;
4703         }
4704         
4705         if(this.preventDefault){
4706             e.preventDefault();
4707         }
4708         
4709         this.fireEvent('click', this);
4710     },
4711     
4712     disable : function()
4713     {
4714         this.setDisabled(true);
4715     },
4716     
4717     enable : function()
4718     {
4719         this.setDisabled(false);
4720     },
4721     
4722     setDisabled : function(state)
4723     {
4724         if(this.disabled == state){
4725             return;
4726         }
4727         
4728         this.disabled = state;
4729         
4730         if (state) {
4731             this.el.addClass('disabled');
4732             return;
4733         }
4734         
4735         this.el.removeClass('disabled');
4736         
4737         return;
4738     },
4739     
4740     setActive : function(state)
4741     {
4742         if(this.active == state){
4743             return;
4744         }
4745         
4746         this.active = state;
4747         
4748         if (state) {
4749             this.el.addClass('active');
4750             return;
4751         }
4752         
4753         this.el.removeClass('active');
4754         
4755         return;
4756     },
4757     
4758     isActive: function () 
4759     {
4760         return this.active;
4761     },
4762     
4763     setBadge : function(str)
4764     {
4765         if(!this.badgeEl){
4766             return;
4767         }
4768         
4769         this.badgeEl.dom.innerHTML = str;
4770     }
4771     
4772    
4773      
4774  
4775 });
4776  
4777
4778  /*
4779  * - LGPL
4780  *
4781  * row
4782  * 
4783  */
4784
4785 /**
4786  * @class Roo.bootstrap.Row
4787  * @extends Roo.bootstrap.Component
4788  * Bootstrap Row class (contains columns...)
4789  * 
4790  * @constructor
4791  * Create a new Row
4792  * @param {Object} config The config object
4793  */
4794
4795 Roo.bootstrap.Row = function(config){
4796     Roo.bootstrap.Row.superclass.constructor.call(this, config);
4797 };
4798
4799 Roo.extend(Roo.bootstrap.Row, Roo.bootstrap.Component,  {
4800     
4801     getAutoCreate : function(){
4802        return {
4803             cls: 'row clearfix'
4804        };
4805     }
4806     
4807     
4808 });
4809
4810  
4811
4812  /*
4813  * - LGPL
4814  *
4815  * element
4816  * 
4817  */
4818
4819 /**
4820  * @class Roo.bootstrap.Element
4821  * @extends Roo.bootstrap.Component
4822  * Bootstrap Element class
4823  * @cfg {String} html contents of the element
4824  * @cfg {String} tag tag of the element
4825  * @cfg {String} cls class of the element
4826  * @cfg {Boolean} preventDefault (true|false) default false
4827  * @cfg {Boolean} clickable (true|false) default false
4828  * 
4829  * @constructor
4830  * Create a new Element
4831  * @param {Object} config The config object
4832  */
4833
4834 Roo.bootstrap.Element = function(config){
4835     Roo.bootstrap.Element.superclass.constructor.call(this, config);
4836     
4837     this.addEvents({
4838         // raw events
4839         /**
4840          * @event click
4841          * When a element is chick
4842          * @param {Roo.bootstrap.Element} this
4843          * @param {Roo.EventObject} e
4844          */
4845         "click" : true
4846     });
4847 };
4848
4849 Roo.extend(Roo.bootstrap.Element, Roo.bootstrap.Component,  {
4850     
4851     tag: 'div',
4852     cls: '',
4853     html: '',
4854     preventDefault: false, 
4855     clickable: false,
4856     
4857     getAutoCreate : function(){
4858         
4859         var cfg = {
4860             tag: this.tag,
4861             cls: this.cls,
4862             html: this.html
4863         };
4864         
4865         return cfg;
4866     },
4867     
4868     initEvents: function() 
4869     {
4870         Roo.bootstrap.Element.superclass.initEvents.call(this);
4871         
4872         if(this.clickable){
4873             this.el.on('click', this.onClick, this);
4874         }
4875         
4876     },
4877     
4878     onClick : function(e)
4879     {
4880         if(this.preventDefault){
4881             e.preventDefault();
4882         }
4883         
4884         this.fireEvent('click', this, e);
4885     },
4886     
4887     getValue : function()
4888     {
4889         return this.el.dom.innerHTML;
4890     },
4891     
4892     setValue : function(value)
4893     {
4894         this.el.dom.innerHTML = value;
4895     }
4896    
4897 });
4898
4899  
4900
4901  /*
4902  * - LGPL
4903  *
4904  * pagination
4905  * 
4906  */
4907
4908 /**
4909  * @class Roo.bootstrap.Pagination
4910  * @extends Roo.bootstrap.Component
4911  * Bootstrap Pagination class
4912  * @cfg {String} size xs | sm | md | lg
4913  * @cfg {Boolean} inverse false | true
4914  * 
4915  * @constructor
4916  * Create a new Pagination
4917  * @param {Object} config The config object
4918  */
4919
4920 Roo.bootstrap.Pagination = function(config){
4921     Roo.bootstrap.Pagination.superclass.constructor.call(this, config);
4922 };
4923
4924 Roo.extend(Roo.bootstrap.Pagination, Roo.bootstrap.Component,  {
4925     
4926     cls: false,
4927     size: false,
4928     inverse: false,
4929     
4930     getAutoCreate : function(){
4931         var cfg = {
4932             tag: 'ul',
4933                 cls: 'pagination'
4934         };
4935         if (this.inverse) {
4936             cfg.cls += ' inverse';
4937         }
4938         if (this.html) {
4939             cfg.html=this.html;
4940         }
4941         if (this.cls) {
4942             cfg.cls += " " + this.cls;
4943         }
4944         return cfg;
4945     }
4946    
4947 });
4948
4949  
4950
4951  /*
4952  * - LGPL
4953  *
4954  * Pagination item
4955  * 
4956  */
4957
4958
4959 /**
4960  * @class Roo.bootstrap.PaginationItem
4961  * @extends Roo.bootstrap.Component
4962  * Bootstrap PaginationItem class
4963  * @cfg {String} html text
4964  * @cfg {String} href the link
4965  * @cfg {Boolean} preventDefault (true | false) default true
4966  * @cfg {Boolean} active (true | false) default false
4967  * @cfg {Boolean} disabled default false
4968  * 
4969  * 
4970  * @constructor
4971  * Create a new PaginationItem
4972  * @param {Object} config The config object
4973  */
4974
4975
4976 Roo.bootstrap.PaginationItem = function(config){
4977     Roo.bootstrap.PaginationItem.superclass.constructor.call(this, config);
4978     this.addEvents({
4979         // raw events
4980         /**
4981          * @event click
4982          * The raw click event for the entire grid.
4983          * @param {Roo.EventObject} e
4984          */
4985         "click" : true
4986     });
4987 };
4988
4989 Roo.extend(Roo.bootstrap.PaginationItem, Roo.bootstrap.Component,  {
4990     
4991     href : false,
4992     html : false,
4993     preventDefault: true,
4994     active : false,
4995     cls : false,
4996     disabled: false,
4997     
4998     getAutoCreate : function(){
4999         var cfg= {
5000             tag: 'li',
5001             cn: [
5002                 {
5003                     tag : 'a',
5004                     href : this.href ? this.href : '#',
5005                     html : this.html ? this.html : ''
5006                 }
5007             ]
5008         };
5009         
5010         if(this.cls){
5011             cfg.cls = this.cls;
5012         }
5013         
5014         if(this.disabled){
5015             cfg.cls = typeof(cfg.cls) !== 'undefined' ? cfg.cls + ' disabled' : 'disabled';
5016         }
5017         
5018         if(this.active){
5019             cfg.cls = typeof(cfg.cls) !== 'undefined' ? cfg.cls + ' active' : 'active';
5020         }
5021         
5022         return cfg;
5023     },
5024     
5025     initEvents: function() {
5026         
5027         this.el.on('click', this.onClick, this);
5028         
5029     },
5030     onClick : function(e)
5031     {
5032         Roo.log('PaginationItem on click ');
5033         if(this.preventDefault){
5034             e.preventDefault();
5035         }
5036         
5037         if(this.disabled){
5038             return;
5039         }
5040         
5041         this.fireEvent('click', this, e);
5042     }
5043    
5044 });
5045
5046  
5047
5048  /*
5049  * - LGPL
5050  *
5051  * slider
5052  * 
5053  */
5054
5055
5056 /**
5057  * @class Roo.bootstrap.Slider
5058  * @extends Roo.bootstrap.Component
5059  * Bootstrap Slider class
5060  *    
5061  * @constructor
5062  * Create a new Slider
5063  * @param {Object} config The config object
5064  */
5065
5066 Roo.bootstrap.Slider = function(config){
5067     Roo.bootstrap.Slider.superclass.constructor.call(this, config);
5068 };
5069
5070 Roo.extend(Roo.bootstrap.Slider, Roo.bootstrap.Component,  {
5071     
5072     getAutoCreate : function(){
5073         
5074         var cfg = {
5075             tag: 'div',
5076             cls: 'slider slider-sample1 vertical-handler ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all',
5077             cn: [
5078                 {
5079                     tag: 'a',
5080                     cls: 'ui-slider-handle ui-state-default ui-corner-all'
5081                 }
5082             ]
5083         };
5084         
5085         return cfg;
5086     }
5087    
5088 });
5089
5090  /*
5091  * Based on:
5092  * Ext JS Library 1.1.1
5093  * Copyright(c) 2006-2007, Ext JS, LLC.
5094  *
5095  * Originally Released Under LGPL - original licence link has changed is not relivant.
5096  *
5097  * Fork - LGPL
5098  * <script type="text/javascript">
5099  */
5100  
5101
5102 /**
5103  * @class Roo.grid.ColumnModel
5104  * @extends Roo.util.Observable
5105  * This is the default implementation of a ColumnModel used by the Grid. It defines
5106  * the columns in the grid.
5107  * <br>Usage:<br>
5108  <pre><code>
5109  var colModel = new Roo.grid.ColumnModel([
5110         {header: "Ticker", width: 60, sortable: true, locked: true},
5111         {header: "Company Name", width: 150, sortable: true},
5112         {header: "Market Cap.", width: 100, sortable: true},
5113         {header: "$ Sales", width: 100, sortable: true, renderer: money},
5114         {header: "Employees", width: 100, sortable: true, resizable: false}
5115  ]);
5116  </code></pre>
5117  * <p>
5118  
5119  * The config options listed for this class are options which may appear in each
5120  * individual column definition.
5121  * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
5122  * @constructor
5123  * @param {Object} config An Array of column config objects. See this class's
5124  * config objects for details.
5125 */
5126 Roo.grid.ColumnModel = function(config){
5127         /**
5128      * The config passed into the constructor
5129      */
5130     this.config = config;
5131     this.lookup = {};
5132
5133     // if no id, create one
5134     // if the column does not have a dataIndex mapping,
5135     // map it to the order it is in the config
5136     for(var i = 0, len = config.length; i < len; i++){
5137         var c = config[i];
5138         if(typeof c.dataIndex == "undefined"){
5139             c.dataIndex = i;
5140         }
5141         if(typeof c.renderer == "string"){
5142             c.renderer = Roo.util.Format[c.renderer];
5143         }
5144         if(typeof c.id == "undefined"){
5145             c.id = Roo.id();
5146         }
5147         if(c.editor && c.editor.xtype){
5148             c.editor  = Roo.factory(c.editor, Roo.grid);
5149         }
5150         if(c.editor && c.editor.isFormField){
5151             c.editor = new Roo.grid.GridEditor(c.editor);
5152         }
5153         this.lookup[c.id] = c;
5154     }
5155
5156     /**
5157      * The width of columns which have no width specified (defaults to 100)
5158      * @type Number
5159      */
5160     this.defaultWidth = 100;
5161
5162     /**
5163      * Default sortable of columns which have no sortable specified (defaults to false)
5164      * @type Boolean
5165      */
5166     this.defaultSortable = false;
5167
5168     this.addEvents({
5169         /**
5170              * @event widthchange
5171              * Fires when the width of a column changes.
5172              * @param {ColumnModel} this
5173              * @param {Number} columnIndex The column index
5174              * @param {Number} newWidth The new width
5175              */
5176             "widthchange": true,
5177         /**
5178              * @event headerchange
5179              * Fires when the text of a header changes.
5180              * @param {ColumnModel} this
5181              * @param {Number} columnIndex The column index
5182              * @param {Number} newText The new header text
5183              */
5184             "headerchange": true,
5185         /**
5186              * @event hiddenchange
5187              * Fires when a column is hidden or "unhidden".
5188              * @param {ColumnModel} this
5189              * @param {Number} columnIndex The column index
5190              * @param {Boolean} hidden true if hidden, false otherwise
5191              */
5192             "hiddenchange": true,
5193             /**
5194          * @event columnmoved
5195          * Fires when a column is moved.
5196          * @param {ColumnModel} this
5197          * @param {Number} oldIndex
5198          * @param {Number} newIndex
5199          */
5200         "columnmoved" : true,
5201         /**
5202          * @event columlockchange
5203          * Fires when a column's locked state is changed
5204          * @param {ColumnModel} this
5205          * @param {Number} colIndex
5206          * @param {Boolean} locked true if locked
5207          */
5208         "columnlockchange" : true
5209     });
5210     Roo.grid.ColumnModel.superclass.constructor.call(this);
5211 };
5212 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
5213     /**
5214      * @cfg {String} header The header text to display in the Grid view.
5215      */
5216     /**
5217      * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
5218      * {@link Roo.data.Record} definition from which to draw the column's value. If not
5219      * specified, the column's index is used as an index into the Record's data Array.
5220      */
5221     /**
5222      * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
5223      * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
5224      */
5225     /**
5226      * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
5227      * Defaults to the value of the {@link #defaultSortable} property.
5228      * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
5229      */
5230     /**
5231      * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid.  Defaults to false.
5232      */
5233     /**
5234      * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed.  Defaults to false.
5235      */
5236     /**
5237      * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
5238      */
5239     /**
5240      * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
5241      */
5242     /**
5243      * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
5244      * given the cell's data value. See {@link #setRenderer}. If not specified, the
5245      * default renderer returns the escaped data value. If an object is returned (bootstrap only)
5246      * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
5247      */
5248        /**
5249      * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor 
5250      */
5251     /**
5252      * @cfg {String} align (Optional) Set the CSS text-align property of the column.  Defaults to undefined.
5253      */
5254     /**
5255      * @cfg {String} cursor (Optional)
5256      */
5257     /**
5258      * @cfg {String} tooltip (Optional)
5259      */
5260     /**
5261      * @cfg {Number} xs (Optional)
5262      */
5263     /**
5264      * @cfg {Number} sm (Optional)
5265      */
5266     /**
5267      * @cfg {Number} md (Optional)
5268      */
5269     /**
5270      * @cfg {Number} lg (Optional)
5271      */
5272     /**
5273      * Returns the id of the column at the specified index.
5274      * @param {Number} index The column index
5275      * @return {String} the id
5276      */
5277     getColumnId : function(index){
5278         return this.config[index].id;
5279     },
5280
5281     /**
5282      * Returns the column for a specified id.
5283      * @param {String} id The column id
5284      * @return {Object} the column
5285      */
5286     getColumnById : function(id){
5287         return this.lookup[id];
5288     },
5289
5290     
5291     /**
5292      * Returns the column for a specified dataIndex.
5293      * @param {String} dataIndex The column dataIndex
5294      * @return {Object|Boolean} the column or false if not found
5295      */
5296     getColumnByDataIndex: function(dataIndex){
5297         var index = this.findColumnIndex(dataIndex);
5298         return index > -1 ? this.config[index] : false;
5299     },
5300     
5301     /**
5302      * Returns the index for a specified column id.
5303      * @param {String} id The column id
5304      * @return {Number} the index, or -1 if not found
5305      */
5306     getIndexById : function(id){
5307         for(var i = 0, len = this.config.length; i < len; i++){
5308             if(this.config[i].id == id){
5309                 return i;
5310             }
5311         }
5312         return -1;
5313     },
5314     
5315     /**
5316      * Returns the index for a specified column dataIndex.
5317      * @param {String} dataIndex The column dataIndex
5318      * @return {Number} the index, or -1 if not found
5319      */
5320     
5321     findColumnIndex : function(dataIndex){
5322         for(var i = 0, len = this.config.length; i < len; i++){
5323             if(this.config[i].dataIndex == dataIndex){
5324                 return i;
5325             }
5326         }
5327         return -1;
5328     },
5329     
5330     
5331     moveColumn : function(oldIndex, newIndex){
5332         var c = this.config[oldIndex];
5333         this.config.splice(oldIndex, 1);
5334         this.config.splice(newIndex, 0, c);
5335         this.dataMap = null;
5336         this.fireEvent("columnmoved", this, oldIndex, newIndex);
5337     },
5338
5339     isLocked : function(colIndex){
5340         return this.config[colIndex].locked === true;
5341     },
5342
5343     setLocked : function(colIndex, value, suppressEvent){
5344         if(this.isLocked(colIndex) == value){
5345             return;
5346         }
5347         this.config[colIndex].locked = value;
5348         if(!suppressEvent){
5349             this.fireEvent("columnlockchange", this, colIndex, value);
5350         }
5351     },
5352
5353     getTotalLockedWidth : function(){
5354         var totalWidth = 0;
5355         for(var i = 0; i < this.config.length; i++){
5356             if(this.isLocked(i) && !this.isHidden(i)){
5357                 this.totalWidth += this.getColumnWidth(i);
5358             }
5359         }
5360         return totalWidth;
5361     },
5362
5363     getLockedCount : function(){
5364         for(var i = 0, len = this.config.length; i < len; i++){
5365             if(!this.isLocked(i)){
5366                 return i;
5367             }
5368         }
5369         
5370         return this.config.length;
5371     },
5372
5373     /**
5374      * Returns the number of columns.
5375      * @return {Number}
5376      */
5377     getColumnCount : function(visibleOnly){
5378         if(visibleOnly === true){
5379             var c = 0;
5380             for(var i = 0, len = this.config.length; i < len; i++){
5381                 if(!this.isHidden(i)){
5382                     c++;
5383                 }
5384             }
5385             return c;
5386         }
5387         return this.config.length;
5388     },
5389
5390     /**
5391      * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
5392      * @param {Function} fn
5393      * @param {Object} scope (optional)
5394      * @return {Array} result
5395      */
5396     getColumnsBy : function(fn, scope){
5397         var r = [];
5398         for(var i = 0, len = this.config.length; i < len; i++){
5399             var c = this.config[i];
5400             if(fn.call(scope||this, c, i) === true){
5401                 r[r.length] = c;
5402             }
5403         }
5404         return r;
5405     },
5406
5407     /**
5408      * Returns true if the specified column is sortable.
5409      * @param {Number} col The column index
5410      * @return {Boolean}
5411      */
5412     isSortable : function(col){
5413         if(typeof this.config[col].sortable == "undefined"){
5414             return this.defaultSortable;
5415         }
5416         return this.config[col].sortable;
5417     },
5418
5419     /**
5420      * Returns the rendering (formatting) function defined for the column.
5421      * @param {Number} col The column index.
5422      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
5423      */
5424     getRenderer : function(col){
5425         if(!this.config[col].renderer){
5426             return Roo.grid.ColumnModel.defaultRenderer;
5427         }
5428         return this.config[col].renderer;
5429     },
5430
5431     /**
5432      * Sets the rendering (formatting) function for a column.
5433      * @param {Number} col The column index
5434      * @param {Function} fn The function to use to process the cell's raw data
5435      * to return HTML markup for the grid view. The render function is called with
5436      * the following parameters:<ul>
5437      * <li>Data value.</li>
5438      * <li>Cell metadata. An object in which you may set the following attributes:<ul>
5439      * <li>css A CSS style string to apply to the table cell.</li>
5440      * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
5441      * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
5442      * <li>Row index</li>
5443      * <li>Column index</li>
5444      * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
5445      */
5446     setRenderer : function(col, fn){
5447         this.config[col].renderer = fn;
5448     },
5449
5450     /**
5451      * Returns the width for the specified column.
5452      * @param {Number} col The column index
5453      * @return {Number}
5454      */
5455     getColumnWidth : function(col){
5456         return this.config[col].width * 1 || this.defaultWidth;
5457     },
5458
5459     /**
5460      * Sets the width for a column.
5461      * @param {Number} col The column index
5462      * @param {Number} width The new width
5463      */
5464     setColumnWidth : function(col, width, suppressEvent){
5465         this.config[col].width = width;
5466         this.totalWidth = null;
5467         if(!suppressEvent){
5468              this.fireEvent("widthchange", this, col, width);
5469         }
5470     },
5471
5472     /**
5473      * Returns the total width of all columns.
5474      * @param {Boolean} includeHidden True to include hidden column widths
5475      * @return {Number}
5476      */
5477     getTotalWidth : function(includeHidden){
5478         if(!this.totalWidth){
5479             this.totalWidth = 0;
5480             for(var i = 0, len = this.config.length; i < len; i++){
5481                 if(includeHidden || !this.isHidden(i)){
5482                     this.totalWidth += this.getColumnWidth(i);
5483                 }
5484             }
5485         }
5486         return this.totalWidth;
5487     },
5488
5489     /**
5490      * Returns the header for the specified column.
5491      * @param {Number} col The column index
5492      * @return {String}
5493      */
5494     getColumnHeader : function(col){
5495         return this.config[col].header;
5496     },
5497
5498     /**
5499      * Sets the header for a column.
5500      * @param {Number} col The column index
5501      * @param {String} header The new header
5502      */
5503     setColumnHeader : function(col, header){
5504         this.config[col].header = header;
5505         this.fireEvent("headerchange", this, col, header);
5506     },
5507
5508     /**
5509      * Returns the tooltip for the specified column.
5510      * @param {Number} col The column index
5511      * @return {String}
5512      */
5513     getColumnTooltip : function(col){
5514             return this.config[col].tooltip;
5515     },
5516     /**
5517      * Sets the tooltip for a column.
5518      * @param {Number} col The column index
5519      * @param {String} tooltip The new tooltip
5520      */
5521     setColumnTooltip : function(col, tooltip){
5522             this.config[col].tooltip = tooltip;
5523     },
5524
5525     /**
5526      * Returns the dataIndex for the specified column.
5527      * @param {Number} col The column index
5528      * @return {Number}
5529      */
5530     getDataIndex : function(col){
5531         return this.config[col].dataIndex;
5532     },
5533
5534     /**
5535      * Sets the dataIndex for a column.
5536      * @param {Number} col The column index
5537      * @param {Number} dataIndex The new dataIndex
5538      */
5539     setDataIndex : function(col, dataIndex){
5540         this.config[col].dataIndex = dataIndex;
5541     },
5542
5543     
5544     
5545     /**
5546      * Returns true if the cell is editable.
5547      * @param {Number} colIndex The column index
5548      * @param {Number} rowIndex The row index - this is nto actually used..?
5549      * @return {Boolean}
5550      */
5551     isCellEditable : function(colIndex, rowIndex){
5552         return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
5553     },
5554
5555     /**
5556      * Returns the editor defined for the cell/column.
5557      * return false or null to disable editing.
5558      * @param {Number} colIndex The column index
5559      * @param {Number} rowIndex The row index
5560      * @return {Object}
5561      */
5562     getCellEditor : function(colIndex, rowIndex){
5563         return this.config[colIndex].editor;
5564     },
5565
5566     /**
5567      * Sets if a column is editable.
5568      * @param {Number} col The column index
5569      * @param {Boolean} editable True if the column is editable
5570      */
5571     setEditable : function(col, editable){
5572         this.config[col].editable = editable;
5573     },
5574
5575
5576     /**
5577      * Returns true if the column is hidden.
5578      * @param {Number} colIndex The column index
5579      * @return {Boolean}
5580      */
5581     isHidden : function(colIndex){
5582         return this.config[colIndex].hidden;
5583     },
5584
5585
5586     /**
5587      * Returns true if the column width cannot be changed
5588      */
5589     isFixed : function(colIndex){
5590         return this.config[colIndex].fixed;
5591     },
5592
5593     /**
5594      * Returns true if the column can be resized
5595      * @return {Boolean}
5596      */
5597     isResizable : function(colIndex){
5598         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
5599     },
5600     /**
5601      * Sets if a column is hidden.
5602      * @param {Number} colIndex The column index
5603      * @param {Boolean} hidden True if the column is hidden
5604      */
5605     setHidden : function(colIndex, hidden){
5606         this.config[colIndex].hidden = hidden;
5607         this.totalWidth = null;
5608         this.fireEvent("hiddenchange", this, colIndex, hidden);
5609     },
5610
5611     /**
5612      * Sets the editor for a column.
5613      * @param {Number} col The column index
5614      * @param {Object} editor The editor object
5615      */
5616     setEditor : function(col, editor){
5617         this.config[col].editor = editor;
5618     }
5619 });
5620
5621 Roo.grid.ColumnModel.defaultRenderer = function(value)
5622 {
5623     if(typeof value == "object") {
5624         return value;
5625     }
5626         if(typeof value == "string" && value.length < 1){
5627             return "&#160;";
5628         }
5629     
5630         return String.format("{0}", value);
5631 };
5632
5633 // Alias for backwards compatibility
5634 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
5635 /*
5636  * Based on:
5637  * Ext JS Library 1.1.1
5638  * Copyright(c) 2006-2007, Ext JS, LLC.
5639  *
5640  * Originally Released Under LGPL - original licence link has changed is not relivant.
5641  *
5642  * Fork - LGPL
5643  * <script type="text/javascript">
5644  */
5645  
5646 /**
5647  * @class Roo.LoadMask
5648  * A simple utility class for generically masking elements while loading data.  If the element being masked has
5649  * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
5650  * process and the mask element will be cached for reuse.  For all other elements, this mask will replace the
5651  * element's UpdateManager load indicator and will be destroyed after the initial load.
5652  * @constructor
5653  * Create a new LoadMask
5654  * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
5655  * @param {Object} config The config object
5656  */
5657 Roo.LoadMask = function(el, config){
5658     this.el = Roo.get(el);
5659     Roo.apply(this, config);
5660     if(this.store){
5661         this.store.on('beforeload', this.onBeforeLoad, this);
5662         this.store.on('load', this.onLoad, this);
5663         this.store.on('loadexception', this.onLoadException, this);
5664         this.removeMask = false;
5665     }else{
5666         var um = this.el.getUpdateManager();
5667         um.showLoadIndicator = false; // disable the default indicator
5668         um.on('beforeupdate', this.onBeforeLoad, this);
5669         um.on('update', this.onLoad, this);
5670         um.on('failure', this.onLoad, this);
5671         this.removeMask = true;
5672     }
5673 };
5674
5675 Roo.LoadMask.prototype = {
5676     /**
5677      * @cfg {Boolean} removeMask
5678      * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
5679      * False to persist the mask element reference for multiple uses (e.g., for paged data widgets).  Defaults to false.
5680      */
5681     /**
5682      * @cfg {String} msg
5683      * The text to display in a centered loading message box (defaults to 'Loading...')
5684      */
5685     msg : 'Loading...',
5686     /**
5687      * @cfg {String} msgCls
5688      * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
5689      */
5690     msgCls : 'x-mask-loading',
5691
5692     /**
5693      * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
5694      * @type Boolean
5695      */
5696     disabled: false,
5697
5698     /**
5699      * Disables the mask to prevent it from being displayed
5700      */
5701     disable : function(){
5702        this.disabled = true;
5703     },
5704
5705     /**
5706      * Enables the mask so that it can be displayed
5707      */
5708     enable : function(){
5709         this.disabled = false;
5710     },
5711     
5712     onLoadException : function()
5713     {
5714         Roo.log(arguments);
5715         
5716         if (typeof(arguments[3]) != 'undefined') {
5717             Roo.MessageBox.alert("Error loading",arguments[3]);
5718         } 
5719         /*
5720         try {
5721             if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
5722                 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
5723             }   
5724         } catch(e) {
5725             
5726         }
5727         */
5728     
5729         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
5730     },
5731     // private
5732     onLoad : function()
5733     {
5734         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
5735     },
5736
5737     // private
5738     onBeforeLoad : function(){
5739         if(!this.disabled){
5740             (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
5741         }
5742     },
5743
5744     // private
5745     destroy : function(){
5746         if(this.store){
5747             this.store.un('beforeload', this.onBeforeLoad, this);
5748             this.store.un('load', this.onLoad, this);
5749             this.store.un('loadexception', this.onLoadException, this);
5750         }else{
5751             var um = this.el.getUpdateManager();
5752             um.un('beforeupdate', this.onBeforeLoad, this);
5753             um.un('update', this.onLoad, this);
5754             um.un('failure', this.onLoad, this);
5755         }
5756     }
5757 };/*
5758  * - LGPL
5759  *
5760  * table
5761  * 
5762  */
5763
5764 /**
5765  * @class Roo.bootstrap.Table
5766  * @extends Roo.bootstrap.Component
5767  * Bootstrap Table class
5768  * @cfg {String} cls table class
5769  * @cfg {String} align (left|center|right) Specifies the alignment of a table according to surrounding text
5770  * @cfg {String} bgcolor Specifies the background color for a table
5771  * @cfg {Number} border Specifies whether the table cells should have borders or not
5772  * @cfg {Number} cellpadding Specifies the space between the cell wall and the cell content
5773  * @cfg {Number} cellspacing Specifies the space between cells
5774  * @cfg {String} frame Specifies which parts of the outside borders that should be visible
5775  * @cfg {String} rules Specifies which parts of the inside borders that should be visible
5776  * @cfg {String} sortable Specifies that the table should be sortable
5777  * @cfg {String} summary Specifies a summary of the content of a table
5778  * @cfg {Number} width Specifies the width of a table
5779  * @cfg {String} layout table layout (auto | fixed | initial | inherit)
5780  * 
5781  * @cfg {boolean} striped Should the rows be alternative striped
5782  * @cfg {boolean} bordered Add borders to the table
5783  * @cfg {boolean} hover Add hover highlighting
5784  * @cfg {boolean} condensed Format condensed
5785  * @cfg {boolean} responsive Format condensed
5786  * @cfg {Boolean} loadMask (true|false) default false
5787  * @cfg {Boolean} footerShow (true|false) generate tfoot, default true
5788  * @cfg {Boolean} headerShow (true|false) generate thead, default true
5789  * @cfg {Boolean} rowSelection (true|false) default false
5790  * @cfg {Boolean} cellSelection (true|false) default false
5791  * @cfg {Boolean} scrollBody (true|false) default false - body scrolled / fixed header
5792  * @cfg {Roo.bootstrap.PagingToolbar} footer  a paging toolbar
5793  * @cfg {Boolean} lazyLoad  auto load data while scrolling to the end (default false)
5794  
5795  * 
5796  * @constructor
5797  * Create a new Table
5798  * @param {Object} config The config object
5799  */
5800
5801 Roo.bootstrap.Table = function(config){
5802     Roo.bootstrap.Table.superclass.constructor.call(this, config);
5803     
5804   
5805     
5806     // BC...
5807     this.rowSelection = (typeof(config.rowSelection) != 'undefined') ? config.rowSelection : this.rowSelection;
5808     this.cellSelection = (typeof(config.cellSelection) != 'undefined') ? config.cellSelection : this.cellSelection;
5809     this.headerShow = (typeof(config.thead) != 'undefined') ? config.thead : this.headerShow;
5810     this.footerShow = (typeof(config.tfoot) != 'undefined') ? config.tfoot : this.footerShow;
5811     
5812     this.sm = this.sm || {xtype: 'RowSelectionModel'};
5813     if (this.sm) {
5814         this.sm.grid = this;
5815         this.selModel = Roo.factory(this.sm, Roo.bootstrap.Table);
5816         this.sm = this.selModel;
5817         this.sm.xmodule = this.xmodule || false;
5818     }
5819     
5820     if (this.cm && typeof(this.cm.config) == 'undefined') {
5821         this.colModel = new Roo.grid.ColumnModel(this.cm);
5822         this.cm = this.colModel;
5823         this.cm.xmodule = this.xmodule || false;
5824     }
5825     if (this.store) {
5826         this.store= Roo.factory(this.store, Roo.data);
5827         this.ds = this.store;
5828         this.ds.xmodule = this.xmodule || false;
5829          
5830     }
5831     if (this.footer && this.store) {
5832         this.footer.dataSource = this.ds;
5833         this.footer = Roo.factory(this.footer);
5834     }
5835     
5836     /** @private */
5837     this.addEvents({
5838         /**
5839          * @event cellclick
5840          * Fires when a cell is clicked
5841          * @param {Roo.bootstrap.Table} this
5842          * @param {Roo.Element} el
5843          * @param {Number} rowIndex
5844          * @param {Number} columnIndex
5845          * @param {Roo.EventObject} e
5846          */
5847         "cellclick" : true,
5848         /**
5849          * @event celldblclick
5850          * Fires when a cell is double clicked
5851          * @param {Roo.bootstrap.Table} this
5852          * @param {Roo.Element} el
5853          * @param {Number} rowIndex
5854          * @param {Number} columnIndex
5855          * @param {Roo.EventObject} e
5856          */
5857         "celldblclick" : true,
5858         /**
5859          * @event rowclick
5860          * Fires when a row is clicked
5861          * @param {Roo.bootstrap.Table} this
5862          * @param {Roo.Element} el
5863          * @param {Number} rowIndex
5864          * @param {Roo.EventObject} e
5865          */
5866         "rowclick" : true,
5867         /**
5868          * @event rowdblclick
5869          * Fires when a row is double clicked
5870          * @param {Roo.bootstrap.Table} this
5871          * @param {Roo.Element} el
5872          * @param {Number} rowIndex
5873          * @param {Roo.EventObject} e
5874          */
5875         "rowdblclick" : true,
5876         /**
5877          * @event mouseover
5878          * Fires when a mouseover occur
5879          * @param {Roo.bootstrap.Table} this
5880          * @param {Roo.Element} el
5881          * @param {Number} rowIndex
5882          * @param {Number} columnIndex
5883          * @param {Roo.EventObject} e
5884          */
5885         "mouseover" : true,
5886         /**
5887          * @event mouseout
5888          * Fires when a mouseout occur
5889          * @param {Roo.bootstrap.Table} this
5890          * @param {Roo.Element} el
5891          * @param {Number} rowIndex
5892          * @param {Number} columnIndex
5893          * @param {Roo.EventObject} e
5894          */
5895         "mouseout" : true,
5896         /**
5897          * @event rowclass
5898          * Fires when a row is rendered, so you can change add a style to it.
5899          * @param {Roo.bootstrap.Table} this
5900          * @param {Object} rowcfg   contains record  rowIndex colIndex and rowClass - set rowClass to add a style.
5901          */
5902         'rowclass' : true,
5903           /**
5904          * @event rowsrendered
5905          * Fires when all the  rows have been rendered
5906          * @param {Roo.bootstrap.Table} this
5907          */
5908         'rowsrendered' : true,
5909         /**
5910          * @event contextmenu
5911          * The raw contextmenu event for the entire grid.
5912          * @param {Roo.EventObject} e
5913          */
5914         "contextmenu" : true,
5915         /**
5916          * @event rowcontextmenu
5917          * Fires when a row is right clicked
5918          * @param {Roo.bootstrap.Table} this
5919          * @param {Number} rowIndex
5920          * @param {Roo.EventObject} e
5921          */
5922         "rowcontextmenu" : true,
5923         /**
5924          * @event cellcontextmenu
5925          * Fires when a cell is right clicked
5926          * @param {Roo.bootstrap.Table} this
5927          * @param {Number} rowIndex
5928          * @param {Number} cellIndex
5929          * @param {Roo.EventObject} e
5930          */
5931          "cellcontextmenu" : true,
5932          /**
5933          * @event headercontextmenu
5934          * Fires when a header is right clicked
5935          * @param {Roo.bootstrap.Table} this
5936          * @param {Number} columnIndex
5937          * @param {Roo.EventObject} e
5938          */
5939         "headercontextmenu" : true
5940     });
5941 };
5942
5943 Roo.extend(Roo.bootstrap.Table, Roo.bootstrap.Component,  {
5944     
5945     cls: false,
5946     align: false,
5947     bgcolor: false,
5948     border: false,
5949     cellpadding: false,
5950     cellspacing: false,
5951     frame: false,
5952     rules: false,
5953     sortable: false,
5954     summary: false,
5955     width: false,
5956     striped : false,
5957     scrollBody : false,
5958     bordered: false,
5959     hover:  false,
5960     condensed : false,
5961     responsive : false,
5962     sm : false,
5963     cm : false,
5964     store : false,
5965     loadMask : false,
5966     footerShow : true,
5967     headerShow : true,
5968   
5969     rowSelection : false,
5970     cellSelection : false,
5971     layout : false,
5972     
5973     // Roo.Element - the tbody
5974     mainBody: false,
5975     // Roo.Element - thead element
5976     mainHead: false,
5977     
5978     container: false, // used by gridpanel...
5979     
5980     lazyLoad : false,
5981     
5982     getAutoCreate : function()
5983     {
5984         var cfg = Roo.apply({}, Roo.bootstrap.Table.superclass.getAutoCreate.call(this));
5985         
5986         cfg = {
5987             tag: 'table',
5988             cls : 'table',
5989             cn : []
5990         };
5991         if (this.scrollBody) {
5992             cfg.cls += ' table-body-fixed';
5993         }    
5994         if (this.striped) {
5995             cfg.cls += ' table-striped';
5996         }
5997         
5998         if (this.hover) {
5999             cfg.cls += ' table-hover';
6000         }
6001         if (this.bordered) {
6002             cfg.cls += ' table-bordered';
6003         }
6004         if (this.condensed) {
6005             cfg.cls += ' table-condensed';
6006         }
6007         if (this.responsive) {
6008             cfg.cls += ' table-responsive';
6009         }
6010         
6011         if (this.cls) {
6012             cfg.cls+=  ' ' +this.cls;
6013         }
6014         
6015         // this lot should be simplifed...
6016         
6017         if (this.align) {
6018             cfg.align=this.align;
6019         }
6020         if (this.bgcolor) {
6021             cfg.bgcolor=this.bgcolor;
6022         }
6023         if (this.border) {
6024             cfg.border=this.border;
6025         }
6026         if (this.cellpadding) {
6027             cfg.cellpadding=this.cellpadding;
6028         }
6029         if (this.cellspacing) {
6030             cfg.cellspacing=this.cellspacing;
6031         }
6032         if (this.frame) {
6033             cfg.frame=this.frame;
6034         }
6035         if (this.rules) {
6036             cfg.rules=this.rules;
6037         }
6038         if (this.sortable) {
6039             cfg.sortable=this.sortable;
6040         }
6041         if (this.summary) {
6042             cfg.summary=this.summary;
6043         }
6044         if (this.width) {
6045             cfg.width=this.width;
6046         }
6047         if (this.layout) {
6048             cfg.style = (typeof(cfg.style) == 'undefined') ? ('table-layout:' + this.layout + ';') : (cfg.style + ('table-layout:' + this.layout + ';'));
6049         }
6050         
6051         if(this.store || this.cm){
6052             if(this.headerShow){
6053                 cfg.cn.push(this.renderHeader());
6054             }
6055             
6056             cfg.cn.push(this.renderBody());
6057             
6058             if(this.footerShow){
6059                 cfg.cn.push(this.renderFooter());
6060             }
6061             // where does this come from?
6062             //cfg.cls+=  ' TableGrid';
6063         }
6064         
6065         return { cn : [ cfg ] };
6066     },
6067     
6068     initEvents : function()
6069     {   
6070         if(!this.store || !this.cm){
6071             return;
6072         }
6073         if (this.selModel) {
6074             this.selModel.initEvents();
6075         }
6076         
6077         
6078         //Roo.log('initEvents with ds!!!!');
6079         
6080         this.mainBody = this.el.select('tbody', true).first();
6081         this.mainHead = this.el.select('thead', true).first();
6082         
6083         
6084         
6085         
6086         var _this = this;
6087         
6088         Roo.each(this.el.select('thead th.sortable', true).elements, function(e){
6089             e.on('click', _this.sort, _this);
6090         });
6091         
6092         this.mainBody.on("click", this.onClick, this);
6093         this.mainBody.on("dblclick", this.onDblClick, this);
6094         
6095         // why is this done????? = it breaks dialogs??
6096         //this.parent().el.setStyle('position', 'relative');
6097         
6098         
6099         if (this.footer) {
6100             this.footer.parentId = this.id;
6101             this.footer.onRender(this.el.select('tfoot tr td').first(), null);
6102             
6103             if(this.lazyLoad){
6104                 this.el.select('tfoot tr td').first().addClass('hide');
6105             }
6106         } 
6107         
6108         this.maskEl = new Roo.LoadMask(this.el, { store : this.ds, msgCls: 'roo-el-mask-msg' });
6109         
6110         this.store.on('load', this.onLoad, this);
6111         this.store.on('beforeload', this.onBeforeLoad, this);
6112         this.store.on('update', this.onUpdate, this);
6113         this.store.on('add', this.onAdd, this);
6114         this.store.on("clear", this.clear, this);
6115         
6116         this.el.on("contextmenu", this.onContextMenu, this);
6117         
6118         this.mainBody.on('scroll', this.onBodyScroll, this);
6119         
6120         
6121     },
6122     
6123     onContextMenu : function(e, t)
6124     {
6125         this.processEvent("contextmenu", e);
6126     },
6127     
6128     processEvent : function(name, e)
6129     {
6130         if (name != 'touchstart' ) {
6131             this.fireEvent(name, e);    
6132         }
6133         
6134         var t = e.getTarget();
6135         
6136         var cell = Roo.get(t);
6137         
6138         if(!cell){
6139             return;
6140         }
6141         
6142         if(cell.findParent('tfoot', false, true)){
6143             return;
6144         }
6145         
6146         if(cell.findParent('thead', false, true)){
6147             
6148             if(e.getTarget().nodeName.toLowerCase() != 'th'){
6149                 cell = Roo.get(t).findParent('th', false, true);
6150                 if (!cell) {
6151                     Roo.log("failed to find th in thead?");
6152                     Roo.log(e.getTarget());
6153                     return;
6154                 }
6155             }
6156             
6157             var cellIndex = cell.dom.cellIndex;
6158             
6159             var ename = name == 'touchstart' ? 'click' : name;
6160             this.fireEvent("header" + ename, this, cellIndex, e);
6161             
6162             return;
6163         }
6164         
6165         if(e.getTarget().nodeName.toLowerCase() != 'td'){
6166             cell = Roo.get(t).findParent('td', false, true);
6167             if (!cell) {
6168                 Roo.log("failed to find th in tbody?");
6169                 Roo.log(e.getTarget());
6170                 return;
6171             }
6172         }
6173         
6174         var row = cell.findParent('tr', false, true);
6175         var cellIndex = cell.dom.cellIndex;
6176         var rowIndex = row.dom.rowIndex - 1;
6177         
6178         if(row !== false){
6179             
6180             this.fireEvent("row" + name, this, rowIndex, e);
6181             
6182             if(cell !== false){
6183             
6184                 this.fireEvent("cell" + name, this, rowIndex, cellIndex, e);
6185             }
6186         }
6187         
6188     },
6189     
6190     onMouseover : function(e, el)
6191     {
6192         var cell = Roo.get(el);
6193         
6194         if(!cell){
6195             return;
6196         }
6197         
6198         if(e.getTarget().nodeName.toLowerCase() != 'td'){
6199             cell = cell.findParent('td', false, true);
6200         }
6201         
6202         var row = cell.findParent('tr', false, true);
6203         var cellIndex = cell.dom.cellIndex;
6204         var rowIndex = row.dom.rowIndex - 1; // start from 0
6205         
6206         this.fireEvent('mouseover', this, cell, rowIndex, cellIndex, e);
6207         
6208     },
6209     
6210     onMouseout : function(e, el)
6211     {
6212         var cell = Roo.get(el);
6213         
6214         if(!cell){
6215             return;
6216         }
6217         
6218         if(e.getTarget().nodeName.toLowerCase() != 'td'){
6219             cell = cell.findParent('td', false, true);
6220         }
6221         
6222         var row = cell.findParent('tr', false, true);
6223         var cellIndex = cell.dom.cellIndex;
6224         var rowIndex = row.dom.rowIndex - 1; // start from 0
6225         
6226         this.fireEvent('mouseout', this, cell, rowIndex, cellIndex, e);
6227         
6228     },
6229     
6230     onClick : function(e, el)
6231     {
6232         var cell = Roo.get(el);
6233         
6234         if(!cell || (!this.cellSelection && !this.rowSelection)){
6235             return;
6236         }
6237         
6238         if(e.getTarget().nodeName.toLowerCase() != 'td'){
6239             cell = cell.findParent('td', false, true);
6240         }
6241         
6242         if(!cell || typeof(cell) == 'undefined'){
6243             return;
6244         }
6245         
6246         var row = cell.findParent('tr', false, true);
6247         
6248         if(!row || typeof(row) == 'undefined'){
6249             return;
6250         }
6251         
6252         var cellIndex = cell.dom.cellIndex;
6253         var rowIndex = this.getRowIndex(row);
6254         
6255         // why??? - should these not be based on SelectionModel?
6256         if(this.cellSelection){
6257             this.fireEvent('cellclick', this, cell, rowIndex, cellIndex, e);
6258         }
6259         
6260         if(this.rowSelection){
6261             this.fireEvent('rowclick', this, row, rowIndex, e);
6262         }
6263         
6264         
6265     },
6266         
6267     onDblClick : function(e,el)
6268     {
6269         var cell = Roo.get(el);
6270         
6271         if(!cell || (!this.cellSelection && !this.rowSelection)){
6272             return;
6273         }
6274         
6275         if(e.getTarget().nodeName.toLowerCase() != 'td'){
6276             cell = cell.findParent('td', false, true);
6277         }
6278         
6279         if(!cell || typeof(cell) == 'undefined'){
6280             return;
6281         }
6282         
6283         var row = cell.findParent('tr', false, true);
6284         
6285         if(!row || typeof(row) == 'undefined'){
6286             return;
6287         }
6288         
6289         var cellIndex = cell.dom.cellIndex;
6290         var rowIndex = this.getRowIndex(row);
6291         
6292         if(this.cellSelection){
6293             this.fireEvent('celldblclick', this, cell, rowIndex, cellIndex, e);
6294         }
6295         
6296         if(this.rowSelection){
6297             this.fireEvent('rowdblclick', this, row, rowIndex, e);
6298         }
6299     },
6300     
6301     sort : function(e,el)
6302     {
6303         var col = Roo.get(el);
6304         
6305         if(!col.hasClass('sortable')){
6306             return;
6307         }
6308         
6309         var sort = col.attr('sort');
6310         var dir = 'ASC';
6311         
6312         if(col.select('i', true).first().hasClass('glyphicon-arrow-up')){
6313             dir = 'DESC';
6314         }
6315         
6316         this.store.sortInfo = {field : sort, direction : dir};
6317         
6318         if (this.footer) {
6319             Roo.log("calling footer first");
6320             this.footer.onClick('first');
6321         } else {
6322         
6323             this.store.load({ params : { start : 0 } });
6324         }
6325     },
6326     
6327     renderHeader : function()
6328     {
6329         var header = {
6330             tag: 'thead',
6331             cn : []
6332         };
6333         
6334         var cm = this.cm;
6335         this.totalWidth = 0;
6336         
6337         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
6338             
6339             var config = cm.config[i];
6340             
6341             var c = {
6342                 tag: 'th',
6343                 style : '',
6344                 html: cm.getColumnHeader(i)
6345             };
6346             
6347             var hh = '';
6348             
6349             if(typeof(config.sortable) != 'undefined' && config.sortable){
6350                 c.cls = 'sortable';
6351                 c.html = '<i class="glyphicon"></i>' + c.html;
6352             }
6353             
6354             if(typeof(config.lgHeader) != 'undefined'){
6355                 hh += '<span class="hidden-xs hidden-sm hidden-md">' + config.lgHeader + '</span>';
6356             }
6357             
6358             if(typeof(config.mdHeader) != 'undefined'){
6359                 hh += '<span class="hidden-xs hidden-sm hidden-lg">' + config.mdHeader + '</span>';
6360             }
6361             
6362             if(typeof(config.smHeader) != 'undefined'){
6363                 hh += '<span class="hidden-xs hidden-md hidden-lg">' + config.smHeader + '</span>';
6364             }
6365             
6366             if(typeof(config.xsHeader) != 'undefined'){
6367                 hh += '<span class="hidden-sm hidden-md hidden-lg">' + config.xsHeader + '</span>';
6368             }
6369             
6370             if(hh.length){
6371                 c.html = hh;
6372             }
6373             
6374             if(typeof(config.tooltip) != 'undefined'){
6375                 c.tooltip = config.tooltip;
6376             }
6377             
6378             if(typeof(config.colspan) != 'undefined'){
6379                 c.colspan = config.colspan;
6380             }
6381             
6382             if(typeof(config.hidden) != 'undefined' && config.hidden){
6383                 c.style += ' display:none;';
6384             }
6385             
6386             if(typeof(config.dataIndex) != 'undefined'){
6387                 c.sort = config.dataIndex;
6388             }
6389             
6390            
6391             
6392             if(typeof(config.align) != 'undefined' && config.align.length){
6393                 c.style += ' text-align:' + config.align + ';';
6394             }
6395             
6396             if(typeof(config.width) != 'undefined'){
6397                 c.style += ' width:' + config.width + 'px;';
6398                 this.totalWidth += config.width;
6399             } else {
6400                 this.totalWidth += 100; // assume minimum of 100 per column?
6401             }
6402             
6403             if(typeof(config.cls) != 'undefined'){
6404                 c.cls = (typeof(c.cls) == 'undefined') ? config.cls : (c.cls + ' ' + config.cls);
6405             }
6406             
6407             ['xs','sm','md','lg'].map(function(size){
6408                 
6409                 if(typeof(config[size]) == 'undefined'){
6410                     return;
6411                 }
6412                 
6413                 if (!config[size]) { // 0 = hidden
6414                     c.cls += ' hidden-' + size;
6415                     return;
6416                 }
6417                 
6418                 c.cls += ' col-' + size + '-' + config[size];
6419
6420             });
6421             
6422             header.cn.push(c)
6423         }
6424         
6425         return header;
6426     },
6427     
6428     renderBody : function()
6429     {
6430         var body = {
6431             tag: 'tbody',
6432             cn : [
6433                 {
6434                     tag: 'tr',
6435                     cn : [
6436                         {
6437                             tag : 'td',
6438                             colspan :  this.cm.getColumnCount()
6439                         }
6440                     ]
6441                 }
6442             ]
6443         };
6444         
6445         return body;
6446     },
6447     
6448     renderFooter : function()
6449     {
6450         var footer = {
6451             tag: 'tfoot',
6452             cn : [
6453                 {
6454                     tag: 'tr',
6455                     cn : [
6456                         {
6457                             tag : 'td',
6458                             colspan :  this.cm.getColumnCount()
6459                         }
6460                     ]
6461                 }
6462             ]
6463         };
6464         
6465         return footer;
6466     },
6467     
6468     
6469     
6470     onLoad : function()
6471     {
6472 //        Roo.log('ds onload');
6473         this.clear();
6474         
6475         var _this = this;
6476         var cm = this.cm;
6477         var ds = this.store;
6478         
6479         Roo.each(this.el.select('thead th.sortable', true).elements, function(e){
6480             e.select('i', true).removeClass(['glyphicon-arrow-up', 'glyphicon-arrow-down']);
6481             if (_this.store.sortInfo) {
6482                     
6483                 if(e.hasClass('sortable') && e.attr('sort') == _this.store.sortInfo.field && _this.store.sortInfo.direction.toUpperCase() == 'ASC'){
6484                     e.select('i', true).addClass(['glyphicon-arrow-up']);
6485                 }
6486                 
6487                 if(e.hasClass('sortable') && e.attr('sort') == _this.store.sortInfo.field && _this.store.sortInfo.direction.toUpperCase() == 'DESC'){
6488                     e.select('i', true).addClass(['glyphicon-arrow-down']);
6489                 }
6490             }
6491         });
6492         
6493         var tbody =  this.mainBody;
6494               
6495         if(ds.getCount() > 0){
6496             ds.data.each(function(d,rowIndex){
6497                 var row =  this.renderRow(cm, ds, rowIndex);
6498                 
6499                 tbody.createChild(row);
6500                 
6501                 var _this = this;
6502                 
6503                 if(row.cellObjects.length){
6504                     Roo.each(row.cellObjects, function(r){
6505                         _this.renderCellObject(r);
6506                     })
6507                 }
6508                 
6509             }, this);
6510         }
6511         
6512         Roo.each(this.el.select('tbody td', true).elements, function(e){
6513             e.on('mouseover', _this.onMouseover, _this);
6514         });
6515         
6516         Roo.each(this.el.select('tbody td', true).elements, function(e){
6517             e.on('mouseout', _this.onMouseout, _this);
6518         });
6519         this.fireEvent('rowsrendered', this);
6520         //if(this.loadMask){
6521         //    this.maskEl.hide();
6522         //}
6523         
6524         this.autoSize();
6525     },
6526     
6527     
6528     onUpdate : function(ds,record)
6529     {
6530         this.refreshRow(record);
6531         this.autoSize();
6532     },
6533     
6534     onRemove : function(ds, record, index, isUpdate){
6535         if(isUpdate !== true){
6536             this.fireEvent("beforerowremoved", this, index, record);
6537         }
6538         var bt = this.mainBody.dom;
6539         
6540         var rows = this.el.select('tbody > tr', true).elements;
6541         
6542         if(typeof(rows[index]) != 'undefined'){
6543             bt.removeChild(rows[index].dom);
6544         }
6545         
6546 //        if(bt.rows[index]){
6547 //            bt.removeChild(bt.rows[index]);
6548 //        }
6549         
6550         if(isUpdate !== true){
6551             //this.stripeRows(index);
6552             //this.syncRowHeights(index, index);
6553             //this.layout();
6554             this.fireEvent("rowremoved", this, index, record);
6555         }
6556     },
6557     
6558     onAdd : function(ds, records, rowIndex)
6559     {
6560         //Roo.log('on Add called');
6561         // - note this does not handle multiple adding very well..
6562         var bt = this.mainBody.dom;
6563         for (var i =0 ; i < records.length;i++) {
6564             //Roo.log('call insert row Add called on ' + rowIndex + ':' + i);
6565             //Roo.log(records[i]);
6566             //Roo.log(this.store.getAt(rowIndex+i));
6567             this.insertRow(this.store, rowIndex + i, false);
6568             return;
6569         }
6570         
6571     },
6572     
6573     
6574     refreshRow : function(record){
6575         var ds = this.store, index;
6576         if(typeof record == 'number'){
6577             index = record;
6578             record = ds.getAt(index);
6579         }else{
6580             index = ds.indexOf(record);
6581         }
6582         this.insertRow(ds, index, true);
6583         this.autoSize();
6584         this.onRemove(ds, record, index+1, true);
6585         this.autoSize();
6586         //this.syncRowHeights(index, index);
6587         //this.layout();
6588         this.fireEvent("rowupdated", this, index, record);
6589     },
6590     
6591     insertRow : function(dm, rowIndex, isUpdate){
6592         
6593         if(!isUpdate){
6594             this.fireEvent("beforerowsinserted", this, rowIndex);
6595         }
6596             //var s = this.getScrollState();
6597         var row = this.renderRow(this.cm, this.store, rowIndex);
6598         // insert before rowIndex..
6599         var e = this.mainBody.createChild(row,this.getRowDom(rowIndex));
6600         
6601         var _this = this;
6602                 
6603         if(row.cellObjects.length){
6604             Roo.each(row.cellObjects, function(r){
6605                 _this.renderCellObject(r);
6606             })
6607         }
6608             
6609         if(!isUpdate){
6610             this.fireEvent("rowsinserted", this, rowIndex);
6611             //this.syncRowHeights(firstRow, lastRow);
6612             //this.stripeRows(firstRow);
6613             //this.layout();
6614         }
6615         
6616     },
6617     
6618     
6619     getRowDom : function(rowIndex)
6620     {
6621         var rows = this.el.select('tbody > tr', true).elements;
6622         
6623         return (typeof(rows[rowIndex]) == 'undefined') ? false : rows[rowIndex];
6624         
6625     },
6626     // returns the object tree for a tr..
6627   
6628     
6629     renderRow : function(cm, ds, rowIndex) 
6630     {
6631         
6632         var d = ds.getAt(rowIndex);
6633         
6634         var row = {
6635             tag : 'tr',
6636             cn : []
6637         };
6638             
6639         var cellObjects = [];
6640         
6641         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
6642             var config = cm.config[i];
6643             
6644             var renderer = cm.getRenderer(i);
6645             var value = '';
6646             var id = false;
6647             
6648             if(typeof(renderer) !== 'undefined'){
6649                 value = renderer(d.data[cm.getDataIndex(i)], false, d);
6650             }
6651             // if object are returned, then they are expected to be Roo.bootstrap.Component instances
6652             // and are rendered into the cells after the row is rendered - using the id for the element.
6653             
6654             if(typeof(value) === 'object'){
6655                 id = Roo.id();
6656                 cellObjects.push({
6657                     container : id,
6658                     cfg : value 
6659                 })
6660             }
6661             
6662             var rowcfg = {
6663                 record: d,
6664                 rowIndex : rowIndex,
6665                 colIndex : i,
6666                 rowClass : ''
6667             };
6668
6669             this.fireEvent('rowclass', this, rowcfg);
6670             
6671             var td = {
6672                 tag: 'td',
6673                 cls : rowcfg.rowClass,
6674                 style: '',
6675                 html: (typeof(value) === 'object') ? '' : value
6676             };
6677             
6678             if (id) {
6679                 td.id = id;
6680             }
6681             
6682             if(typeof(config.colspan) != 'undefined'){
6683                 td.colspan = config.colspan;
6684             }
6685             
6686             if(typeof(config.hidden) != 'undefined' && config.hidden){
6687                 td.style += ' display:none;';
6688             }
6689             
6690             if(typeof(config.align) != 'undefined' && config.align.length){
6691                 td.style += ' text-align:' + config.align + ';';
6692             }
6693             
6694             if(typeof(config.width) != 'undefined'){
6695                 td.style += ' width:' +  config.width + 'px;';
6696             }
6697             
6698             if(typeof(config.cursor) != 'undefined'){
6699                 td.style += ' cursor:' +  config.cursor + ';';
6700             }
6701             
6702             if(typeof(config.cls) != 'undefined'){
6703                 td.cls = (typeof(td.cls) == 'undefined') ? config.cls : (td.cls + ' ' + config.cls);
6704             }
6705             
6706             ['xs','sm','md','lg'].map(function(size){
6707                 
6708                 if(typeof(config[size]) == 'undefined'){
6709                     return;
6710                 }
6711                 
6712                 if (!config[size]) { // 0 = hidden
6713                     td.cls += ' hidden-' + size;
6714                     return;
6715                 }
6716                 
6717                 td.cls += ' col-' + size + '-' + config[size];
6718
6719             });
6720              
6721             row.cn.push(td);
6722            
6723         }
6724         
6725         row.cellObjects = cellObjects;
6726         
6727         return row;
6728           
6729     },
6730     
6731     
6732     
6733     onBeforeLoad : function()
6734     {
6735         //Roo.log('ds onBeforeLoad');
6736         
6737         //this.clear();
6738         
6739         //if(this.loadMask){
6740         //    this.maskEl.show();
6741         //}
6742     },
6743      /**
6744      * Remove all rows
6745      */
6746     clear : function()
6747     {
6748         this.el.select('tbody', true).first().dom.innerHTML = '';
6749     },
6750     /**
6751      * Show or hide a row.
6752      * @param {Number} rowIndex to show or hide
6753      * @param {Boolean} state hide
6754      */
6755     setRowVisibility : function(rowIndex, state)
6756     {
6757         var bt = this.mainBody.dom;
6758         
6759         var rows = this.el.select('tbody > tr', true).elements;
6760         
6761         if(typeof(rows[rowIndex]) == 'undefined'){
6762             return;
6763         }
6764         rows[rowIndex].dom.style.display = state ? '' : 'none';
6765     },
6766     
6767     
6768     getSelectionModel : function(){
6769         if(!this.selModel){
6770             this.selModel = new Roo.bootstrap.Table.RowSelectionModel({grid: this});
6771         }
6772         return this.selModel;
6773     },
6774     /*
6775      * Render the Roo.bootstrap object from renderder
6776      */
6777     renderCellObject : function(r)
6778     {
6779         var _this = this;
6780         
6781         r.cfg.parentId = (typeof(r.container) == 'string') ? r.container : r.container.id;
6782         
6783         var t = r.cfg.render(r.container);
6784         
6785         if(r.cfg.cn){
6786             Roo.each(r.cfg.cn, function(c){
6787                 var child = {
6788                     container: t.getChildContainer(),
6789                     cfg: c
6790                 };
6791                 _this.renderCellObject(child);
6792             })
6793         }
6794     },
6795     
6796     getRowIndex : function(row)
6797     {
6798         var rowIndex = -1;
6799         
6800         Roo.each(this.el.select('tbody > tr', true).elements, function(el, index){
6801             if(el != row){
6802                 return;
6803             }
6804             
6805             rowIndex = index;
6806         });
6807         
6808         return rowIndex;
6809     },
6810      /**
6811      * Returns the grid's underlying element = used by panel.Grid
6812      * @return {Element} The element
6813      */
6814     getGridEl : function(){
6815         return this.el;
6816     },
6817      /**
6818      * Forces a resize - used by panel.Grid
6819      * @return {Element} The element
6820      */
6821     autoSize : function()
6822     {
6823         //var ctr = Roo.get(this.container.dom.parentElement);
6824         var ctr = Roo.get(this.el.dom);
6825         
6826         var thd = this.getGridEl().select('thead',true).first();
6827         var tbd = this.getGridEl().select('tbody', true).first();
6828         var tfd = this.getGridEl().select('tfoot', true).first();
6829         
6830         var cw = ctr.getWidth();
6831         
6832         if (tbd) {
6833             
6834             tbd.setSize(ctr.getWidth(),
6835                         ctr.getHeight() - (thd.getHeight() + (tfd ? tfd.getHeight() : 0))
6836             );
6837             var barsize = (tbd.dom.offsetWidth - tbd.dom.clientWidth);
6838             cw -= barsize;
6839         }
6840         cw = Math.max(cw, this.totalWidth);
6841         this.getGridEl().select('tr',true).setWidth(cw);
6842         // resize 'expandable coloumn?
6843         
6844         return; // we doe not have a view in this design..
6845         
6846     },
6847     onBodyScroll: function()
6848     {
6849         //Roo.log("body scrolled');" + this.mainBody.dom.scrollLeft);
6850         this.mainHead.setStyle({
6851             'position' : 'relative',
6852             'left': (-1* this.mainBody.dom.scrollLeft) + 'px'
6853         });
6854         
6855         if(this.lazyLoad){
6856             
6857             var scrollHeight = this.mainBody.dom.scrollHeight;
6858             
6859             var scrollTop = Math.ceil(this.mainBody.getScroll().top);
6860             
6861             var height = this.mainBody.getHeight();
6862             
6863             if(scrollHeight - height == scrollTop) {
6864                 
6865                 var total = this.ds.getTotalCount();
6866                 
6867                 if(this.footer.cursor + this.footer.pageSize < total){
6868                     
6869                     this.footer.ds.load({
6870                         params : {
6871                             start : this.footer.cursor + this.footer.pageSize,
6872                             limit : this.footer.pageSize
6873                         },
6874                         add : true
6875                     });
6876                 }
6877             }
6878             
6879         }
6880     }
6881 });
6882
6883  
6884
6885  /*
6886  * - LGPL
6887  *
6888  * table cell
6889  * 
6890  */
6891
6892 /**
6893  * @class Roo.bootstrap.TableCell
6894  * @extends Roo.bootstrap.Component
6895  * Bootstrap TableCell class
6896  * @cfg {String} html cell contain text
6897  * @cfg {String} cls cell class
6898  * @cfg {String} tag cell tag (td|th) default td
6899  * @cfg {String} abbr Specifies an abbreviated version of the content in a cell
6900  * @cfg {String} align Aligns the content in a cell
6901  * @cfg {String} axis Categorizes cells
6902  * @cfg {String} bgcolor Specifies the background color of a cell
6903  * @cfg {Number} charoff Sets the number of characters the content will be aligned from the character specified by the char attribute
6904  * @cfg {Number} colspan Specifies the number of columns a cell should span
6905  * @cfg {String} headers Specifies one or more header cells a cell is related to
6906  * @cfg {Number} height Sets the height of a cell
6907  * @cfg {String} nowrap Specifies that the content inside a cell should not wrap
6908  * @cfg {Number} rowspan Sets the number of rows a cell should span
6909  * @cfg {String} scope Defines a way to associate header cells and data cells in a table
6910  * @cfg {String} valign Vertical aligns the content in a cell
6911  * @cfg {Number} width Specifies the width of a cell
6912  * 
6913  * @constructor
6914  * Create a new TableCell
6915  * @param {Object} config The config object
6916  */
6917
6918 Roo.bootstrap.TableCell = function(config){
6919     Roo.bootstrap.TableCell.superclass.constructor.call(this, config);
6920 };
6921
6922 Roo.extend(Roo.bootstrap.TableCell, Roo.bootstrap.Component,  {
6923     
6924     html: false,
6925     cls: false,
6926     tag: false,
6927     abbr: false,
6928     align: false,
6929     axis: false,
6930     bgcolor: false,
6931     charoff: false,
6932     colspan: false,
6933     headers: false,
6934     height: false,
6935     nowrap: false,
6936     rowspan: false,
6937     scope: false,
6938     valign: false,
6939     width: false,
6940     
6941     
6942     getAutoCreate : function(){
6943         var cfg = Roo.apply({}, Roo.bootstrap.TableCell.superclass.getAutoCreate.call(this));
6944         
6945         cfg = {
6946             tag: 'td'
6947         };
6948         
6949         if(this.tag){
6950             cfg.tag = this.tag;
6951         }
6952         
6953         if (this.html) {
6954             cfg.html=this.html
6955         }
6956         if (this.cls) {
6957             cfg.cls=this.cls
6958         }
6959         if (this.abbr) {
6960             cfg.abbr=this.abbr
6961         }
6962         if (this.align) {
6963             cfg.align=this.align
6964         }
6965         if (this.axis) {
6966             cfg.axis=this.axis
6967         }
6968         if (this.bgcolor) {
6969             cfg.bgcolor=this.bgcolor
6970         }
6971         if (this.charoff) {
6972             cfg.charoff=this.charoff
6973         }
6974         if (this.colspan) {
6975             cfg.colspan=this.colspan
6976         }
6977         if (this.headers) {
6978             cfg.headers=this.headers
6979         }
6980         if (this.height) {
6981             cfg.height=this.height
6982         }
6983         if (this.nowrap) {
6984             cfg.nowrap=this.nowrap
6985         }
6986         if (this.rowspan) {
6987             cfg.rowspan=this.rowspan
6988         }
6989         if (this.scope) {
6990             cfg.scope=this.scope
6991         }
6992         if (this.valign) {
6993             cfg.valign=this.valign
6994         }
6995         if (this.width) {
6996             cfg.width=this.width
6997         }
6998         
6999         
7000         return cfg;
7001     }
7002    
7003 });
7004
7005  
7006
7007  /*
7008  * - LGPL
7009  *
7010  * table row
7011  * 
7012  */
7013
7014 /**
7015  * @class Roo.bootstrap.TableRow
7016  * @extends Roo.bootstrap.Component
7017  * Bootstrap TableRow class
7018  * @cfg {String} cls row class
7019  * @cfg {String} align Aligns the content in a table row
7020  * @cfg {String} bgcolor Specifies a background color for a table row
7021  * @cfg {Number} charoff Sets the number of characters the content will be aligned from the character specified by the char attribute
7022  * @cfg {String} valign Vertical aligns the content in a table row
7023  * 
7024  * @constructor
7025  * Create a new TableRow
7026  * @param {Object} config The config object
7027  */
7028
7029 Roo.bootstrap.TableRow = function(config){
7030     Roo.bootstrap.TableRow.superclass.constructor.call(this, config);
7031 };
7032
7033 Roo.extend(Roo.bootstrap.TableRow, Roo.bootstrap.Component,  {
7034     
7035     cls: false,
7036     align: false,
7037     bgcolor: false,
7038     charoff: false,
7039     valign: false,
7040     
7041     getAutoCreate : function(){
7042         var cfg = Roo.apply({}, Roo.bootstrap.TableRow.superclass.getAutoCreate.call(this));
7043         
7044         cfg = {
7045             tag: 'tr'
7046         };
7047             
7048         if(this.cls){
7049             cfg.cls = this.cls;
7050         }
7051         if(this.align){
7052             cfg.align = this.align;
7053         }
7054         if(this.bgcolor){
7055             cfg.bgcolor = this.bgcolor;
7056         }
7057         if(this.charoff){
7058             cfg.charoff = this.charoff;
7059         }
7060         if(this.valign){
7061             cfg.valign = this.valign;
7062         }
7063         
7064         return cfg;
7065     }
7066    
7067 });
7068
7069  
7070
7071  /*
7072  * - LGPL
7073  *
7074  * table body
7075  * 
7076  */
7077
7078 /**
7079  * @class Roo.bootstrap.TableBody
7080  * @extends Roo.bootstrap.Component
7081  * Bootstrap TableBody class
7082  * @cfg {String} cls element class
7083  * @cfg {String} tag element tag (thead|tbody|tfoot) default tbody
7084  * @cfg {String} align Aligns the content inside the element
7085  * @cfg {Number} charoff Sets the number of characters the content inside the element will be aligned from the character specified by the char attribute
7086  * @cfg {String} valign Vertical aligns the content inside the <tbody> element
7087  * 
7088  * @constructor
7089  * Create a new TableBody
7090  * @param {Object} config The config object
7091  */
7092
7093 Roo.bootstrap.TableBody = function(config){
7094     Roo.bootstrap.TableBody.superclass.constructor.call(this, config);
7095 };
7096
7097 Roo.extend(Roo.bootstrap.TableBody, Roo.bootstrap.Component,  {
7098     
7099     cls: false,
7100     tag: false,
7101     align: false,
7102     charoff: false,
7103     valign: false,
7104     
7105     getAutoCreate : function(){
7106         var cfg = Roo.apply({}, Roo.bootstrap.TableBody.superclass.getAutoCreate.call(this));
7107         
7108         cfg = {
7109             tag: 'tbody'
7110         };
7111             
7112         if (this.cls) {
7113             cfg.cls=this.cls
7114         }
7115         if(this.tag){
7116             cfg.tag = this.tag;
7117         }
7118         
7119         if(this.align){
7120             cfg.align = this.align;
7121         }
7122         if(this.charoff){
7123             cfg.charoff = this.charoff;
7124         }
7125         if(this.valign){
7126             cfg.valign = this.valign;
7127         }
7128         
7129         return cfg;
7130     }
7131     
7132     
7133 //    initEvents : function()
7134 //    {
7135 //        
7136 //        if(!this.store){
7137 //            return;
7138 //        }
7139 //        
7140 //        this.store = Roo.factory(this.store, Roo.data);
7141 //        this.store.on('load', this.onLoad, this);
7142 //        
7143 //        this.store.load();
7144 //        
7145 //    },
7146 //    
7147 //    onLoad: function () 
7148 //    {   
7149 //        this.fireEvent('load', this);
7150 //    }
7151 //    
7152 //   
7153 });
7154
7155  
7156
7157  /*
7158  * Based on:
7159  * Ext JS Library 1.1.1
7160  * Copyright(c) 2006-2007, Ext JS, LLC.
7161  *
7162  * Originally Released Under LGPL - original licence link has changed is not relivant.
7163  *
7164  * Fork - LGPL
7165  * <script type="text/javascript">
7166  */
7167
7168 // as we use this in bootstrap.
7169 Roo.namespace('Roo.form');
7170  /**
7171  * @class Roo.form.Action
7172  * Internal Class used to handle form actions
7173  * @constructor
7174  * @param {Roo.form.BasicForm} el The form element or its id
7175  * @param {Object} config Configuration options
7176  */
7177
7178  
7179  
7180 // define the action interface
7181 Roo.form.Action = function(form, options){
7182     this.form = form;
7183     this.options = options || {};
7184 };
7185 /**
7186  * Client Validation Failed
7187  * @const 
7188  */
7189 Roo.form.Action.CLIENT_INVALID = 'client';
7190 /**
7191  * Server Validation Failed
7192  * @const 
7193  */
7194 Roo.form.Action.SERVER_INVALID = 'server';
7195  /**
7196  * Connect to Server Failed
7197  * @const 
7198  */
7199 Roo.form.Action.CONNECT_FAILURE = 'connect';
7200 /**
7201  * Reading Data from Server Failed
7202  * @const 
7203  */
7204 Roo.form.Action.LOAD_FAILURE = 'load';
7205
7206 Roo.form.Action.prototype = {
7207     type : 'default',
7208     failureType : undefined,
7209     response : undefined,
7210     result : undefined,
7211
7212     // interface method
7213     run : function(options){
7214
7215     },
7216
7217     // interface method
7218     success : function(response){
7219
7220     },
7221
7222     // interface method
7223     handleResponse : function(response){
7224
7225     },
7226
7227     // default connection failure
7228     failure : function(response){
7229         
7230         this.response = response;
7231         this.failureType = Roo.form.Action.CONNECT_FAILURE;
7232         this.form.afterAction(this, false);
7233     },
7234
7235     processResponse : function(response){
7236         this.response = response;
7237         if(!response.responseText){
7238             return true;
7239         }
7240         this.result = this.handleResponse(response);
7241         return this.result;
7242     },
7243
7244     // utility functions used internally
7245     getUrl : function(appendParams){
7246         var url = this.options.url || this.form.url || this.form.el.dom.action;
7247         if(appendParams){
7248             var p = this.getParams();
7249             if(p){
7250                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
7251             }
7252         }
7253         return url;
7254     },
7255
7256     getMethod : function(){
7257         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
7258     },
7259
7260     getParams : function(){
7261         var bp = this.form.baseParams;
7262         var p = this.options.params;
7263         if(p){
7264             if(typeof p == "object"){
7265                 p = Roo.urlEncode(Roo.applyIf(p, bp));
7266             }else if(typeof p == 'string' && bp){
7267                 p += '&' + Roo.urlEncode(bp);
7268             }
7269         }else if(bp){
7270             p = Roo.urlEncode(bp);
7271         }
7272         return p;
7273     },
7274
7275     createCallback : function(){
7276         return {
7277             success: this.success,
7278             failure: this.failure,
7279             scope: this,
7280             timeout: (this.form.timeout*1000),
7281             upload: this.form.fileUpload ? this.success : undefined
7282         };
7283     }
7284 };
7285
7286 Roo.form.Action.Submit = function(form, options){
7287     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
7288 };
7289
7290 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
7291     type : 'submit',
7292
7293     haveProgress : false,
7294     uploadComplete : false,
7295     
7296     // uploadProgress indicator.
7297     uploadProgress : function()
7298     {
7299         if (!this.form.progressUrl) {
7300             return;
7301         }
7302         
7303         if (!this.haveProgress) {
7304             Roo.MessageBox.progress("Uploading", "Uploading");
7305         }
7306         if (this.uploadComplete) {
7307            Roo.MessageBox.hide();
7308            return;
7309         }
7310         
7311         this.haveProgress = true;
7312    
7313         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
7314         
7315         var c = new Roo.data.Connection();
7316         c.request({
7317             url : this.form.progressUrl,
7318             params: {
7319                 id : uid
7320             },
7321             method: 'GET',
7322             success : function(req){
7323                //console.log(data);
7324                 var rdata = false;
7325                 var edata;
7326                 try  {
7327                    rdata = Roo.decode(req.responseText)
7328                 } catch (e) {
7329                     Roo.log("Invalid data from server..");
7330                     Roo.log(edata);
7331                     return;
7332                 }
7333                 if (!rdata || !rdata.success) {
7334                     Roo.log(rdata);
7335                     Roo.MessageBox.alert(Roo.encode(rdata));
7336                     return;
7337                 }
7338                 var data = rdata.data;
7339                 
7340                 if (this.uploadComplete) {
7341                    Roo.MessageBox.hide();
7342                    return;
7343                 }
7344                    
7345                 if (data){
7346                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
7347                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
7348                     );
7349                 }
7350                 this.uploadProgress.defer(2000,this);
7351             },
7352        
7353             failure: function(data) {
7354                 Roo.log('progress url failed ');
7355                 Roo.log(data);
7356             },
7357             scope : this
7358         });
7359            
7360     },
7361     
7362     
7363     run : function()
7364     {
7365         // run get Values on the form, so it syncs any secondary forms.
7366         this.form.getValues();
7367         
7368         var o = this.options;
7369         var method = this.getMethod();
7370         var isPost = method == 'POST';
7371         if(o.clientValidation === false || this.form.isValid()){
7372             
7373             if (this.form.progressUrl) {
7374                 this.form.findField('UPLOAD_IDENTIFIER').setValue(
7375                     (new Date() * 1) + '' + Math.random());
7376                     
7377             } 
7378             
7379             
7380             Roo.Ajax.request(Roo.apply(this.createCallback(), {
7381                 form:this.form.el.dom,
7382                 url:this.getUrl(!isPost),
7383                 method: method,
7384                 params:isPost ? this.getParams() : null,
7385                 isUpload: this.form.fileUpload
7386             }));
7387             
7388             this.uploadProgress();
7389
7390         }else if (o.clientValidation !== false){ // client validation failed
7391             this.failureType = Roo.form.Action.CLIENT_INVALID;
7392             this.form.afterAction(this, false);
7393         }
7394     },
7395
7396     success : function(response)
7397     {
7398         this.uploadComplete= true;
7399         if (this.haveProgress) {
7400             Roo.MessageBox.hide();
7401         }
7402         
7403         
7404         var result = this.processResponse(response);
7405         if(result === true || result.success){
7406             this.form.afterAction(this, true);
7407             return;
7408         }
7409         if(result.errors){
7410             this.form.markInvalid(result.errors);
7411             this.failureType = Roo.form.Action.SERVER_INVALID;
7412         }
7413         this.form.afterAction(this, false);
7414     },
7415     failure : function(response)
7416     {
7417         this.uploadComplete= true;
7418         if (this.haveProgress) {
7419             Roo.MessageBox.hide();
7420         }
7421         
7422         this.response = response;
7423         this.failureType = Roo.form.Action.CONNECT_FAILURE;
7424         this.form.afterAction(this, false);
7425     },
7426     
7427     handleResponse : function(response){
7428         if(this.form.errorReader){
7429             var rs = this.form.errorReader.read(response);
7430             var errors = [];
7431             if(rs.records){
7432                 for(var i = 0, len = rs.records.length; i < len; i++) {
7433                     var r = rs.records[i];
7434                     errors[i] = r.data;
7435                 }
7436             }
7437             if(errors.length < 1){
7438                 errors = null;
7439             }
7440             return {
7441                 success : rs.success,
7442                 errors : errors
7443             };
7444         }
7445         var ret = false;
7446         try {
7447             ret = Roo.decode(response.responseText);
7448         } catch (e) {
7449             ret = {
7450                 success: false,
7451                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
7452                 errors : []
7453             };
7454         }
7455         return ret;
7456         
7457     }
7458 });
7459
7460
7461 Roo.form.Action.Load = function(form, options){
7462     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
7463     this.reader = this.form.reader;
7464 };
7465
7466 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
7467     type : 'load',
7468
7469     run : function(){
7470         
7471         Roo.Ajax.request(Roo.apply(
7472                 this.createCallback(), {
7473                     method:this.getMethod(),
7474                     url:this.getUrl(false),
7475                     params:this.getParams()
7476         }));
7477     },
7478
7479     success : function(response){
7480         
7481         var result = this.processResponse(response);
7482         if(result === true || !result.success || !result.data){
7483             this.failureType = Roo.form.Action.LOAD_FAILURE;
7484             this.form.afterAction(this, false);
7485             return;
7486         }
7487         this.form.clearInvalid();
7488         this.form.setValues(result.data);
7489         this.form.afterAction(this, true);
7490     },
7491
7492     handleResponse : function(response){
7493         if(this.form.reader){
7494             var rs = this.form.reader.read(response);
7495             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
7496             return {
7497                 success : rs.success,
7498                 data : data
7499             };
7500         }
7501         return Roo.decode(response.responseText);
7502     }
7503 });
7504
7505 Roo.form.Action.ACTION_TYPES = {
7506     'load' : Roo.form.Action.Load,
7507     'submit' : Roo.form.Action.Submit
7508 };/*
7509  * - LGPL
7510  *
7511  * form
7512  *
7513  */
7514
7515 /**
7516  * @class Roo.bootstrap.Form
7517  * @extends Roo.bootstrap.Component
7518  * Bootstrap Form class
7519  * @cfg {String} method  GET | POST (default POST)
7520  * @cfg {String} labelAlign top | left (default top)
7521  * @cfg {String} align left  | right - for navbars
7522  * @cfg {Boolean} loadMask load mask when submit (default true)
7523
7524  *
7525  * @constructor
7526  * Create a new Form
7527  * @param {Object} config The config object
7528  */
7529
7530
7531 Roo.bootstrap.Form = function(config){
7532     Roo.bootstrap.Form.superclass.constructor.call(this, config);
7533     
7534     Roo.bootstrap.Form.popover.apply();
7535     
7536     this.addEvents({
7537         /**
7538          * @event clientvalidation
7539          * If the monitorValid config option is true, this event fires repetitively to notify of valid state
7540          * @param {Form} this
7541          * @param {Boolean} valid true if the form has passed client-side validation
7542          */
7543         clientvalidation: true,
7544         /**
7545          * @event beforeaction
7546          * Fires before any action is performed. Return false to cancel the action.
7547          * @param {Form} this
7548          * @param {Action} action The action to be performed
7549          */
7550         beforeaction: true,
7551         /**
7552          * @event actionfailed
7553          * Fires when an action fails.
7554          * @param {Form} this
7555          * @param {Action} action The action that failed
7556          */
7557         actionfailed : true,
7558         /**
7559          * @event actioncomplete
7560          * Fires when an action is completed.
7561          * @param {Form} this
7562          * @param {Action} action The action that completed
7563          */
7564         actioncomplete : true
7565     });
7566
7567 };
7568
7569 Roo.extend(Roo.bootstrap.Form, Roo.bootstrap.Component,  {
7570
7571      /**
7572      * @cfg {String} method
7573      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
7574      */
7575     method : 'POST',
7576     /**
7577      * @cfg {String} url
7578      * The URL to use for form actions if one isn't supplied in the action options.
7579      */
7580     /**
7581      * @cfg {Boolean} fileUpload
7582      * Set to true if this form is a file upload.
7583      */
7584
7585     /**
7586      * @cfg {Object} baseParams
7587      * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
7588      */
7589
7590     /**
7591      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
7592      */
7593     timeout: 30,
7594     /**
7595      * @cfg {Sting} align (left|right) for navbar forms
7596      */
7597     align : 'left',
7598
7599     // private
7600     activeAction : null,
7601
7602     /**
7603      * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
7604      * element by passing it or its id or mask the form itself by passing in true.
7605      * @type Mixed
7606      */
7607     waitMsgTarget : false,
7608
7609     loadMask : true,
7610     
7611     /**
7612      * @cfg {Boolean} errorMask (true|false) default false
7613      */
7614     errorMask : false,
7615     
7616     /**
7617      * @cfg {Number} maskOffset Default 100
7618      */
7619     maskOffset : 100,
7620
7621     getAutoCreate : function(){
7622
7623         var cfg = {
7624             tag: 'form',
7625             method : this.method || 'POST',
7626             id : this.id || Roo.id(),
7627             cls : ''
7628         };
7629         if (this.parent().xtype.match(/^Nav/)) {
7630             cfg.cls = 'navbar-form navbar-' + this.align;
7631
7632         }
7633
7634         if (this.labelAlign == 'left' ) {
7635             cfg.cls += ' form-horizontal';
7636         }
7637
7638
7639         return cfg;
7640     },
7641     initEvents : function()
7642     {
7643         this.el.on('submit', this.onSubmit, this);
7644         // this was added as random key presses on the form where triggering form submit.
7645         this.el.on('keypress', function(e) {
7646             if (e.getCharCode() != 13) {
7647                 return true;
7648             }
7649             // we might need to allow it for textareas.. and some other items.
7650             // check e.getTarget().
7651
7652             if(e.getTarget().nodeName.toLowerCase() === 'textarea'){
7653                 return true;
7654             }
7655
7656             Roo.log("keypress blocked");
7657
7658             e.preventDefault();
7659             return false;
7660         });
7661         
7662     },
7663     // private
7664     onSubmit : function(e){
7665         e.stopEvent();
7666     },
7667
7668      /**
7669      * Returns true if client-side validation on the form is successful.
7670      * @return Boolean
7671      */
7672     isValid : function(){
7673         var items = this.getItems();
7674         var valid = true;
7675         var target = false;
7676         
7677         items.each(function(f){
7678             
7679             if(f.validate()){
7680                 return;
7681             }
7682             valid = false;
7683
7684             if(!target && f.el.isVisible(true)){
7685                 target = f;
7686             }
7687            
7688         });
7689         
7690         if(this.errorMask && !valid){
7691             Roo.bootstrap.Form.popover.mask(this, target);
7692         }
7693         
7694         return valid;
7695     },
7696     
7697     /**
7698      * Returns true if any fields in this form have changed since their original load.
7699      * @return Boolean
7700      */
7701     isDirty : function(){
7702         var dirty = false;
7703         var items = this.getItems();
7704         items.each(function(f){
7705            if(f.isDirty()){
7706                dirty = true;
7707                return false;
7708            }
7709            return true;
7710         });
7711         return dirty;
7712     },
7713      /**
7714      * Performs a predefined action (submit or load) or custom actions you define on this form.
7715      * @param {String} actionName The name of the action type
7716      * @param {Object} options (optional) The options to pass to the action.  All of the config options listed
7717      * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
7718      * accept other config options):
7719      * <pre>
7720 Property          Type             Description
7721 ----------------  ---------------  ----------------------------------------------------------------------------------
7722 url               String           The url for the action (defaults to the form's url)
7723 method            String           The form method to use (defaults to the form's method, or POST if not defined)
7724 params            String/Object    The params to pass (defaults to the form's baseParams, or none if not defined)
7725 clientValidation  Boolean          Applies to submit only.  Pass true to call form.isValid() prior to posting to
7726                                    validate the form on the client (defaults to false)
7727      * </pre>
7728      * @return {BasicForm} this
7729      */
7730     doAction : function(action, options){
7731         if(typeof action == 'string'){
7732             action = new Roo.form.Action.ACTION_TYPES[action](this, options);
7733         }
7734         if(this.fireEvent('beforeaction', this, action) !== false){
7735             this.beforeAction(action);
7736             action.run.defer(100, action);
7737         }
7738         return this;
7739     },
7740
7741     // private
7742     beforeAction : function(action){
7743         var o = action.options;
7744
7745         if(this.loadMask){
7746             this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
7747         }
7748         // not really supported yet.. ??
7749
7750         //if(this.waitMsgTarget === true){
7751         //  this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
7752         //}else if(this.waitMsgTarget){
7753         //    this.waitMsgTarget = Roo.get(this.waitMsgTarget);
7754         //    this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
7755         //}else {
7756         //    Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
7757        // }
7758
7759     },
7760
7761     // private
7762     afterAction : function(action, success){
7763         this.activeAction = null;
7764         var o = action.options;
7765
7766         //if(this.waitMsgTarget === true){
7767             this.el.unmask();
7768         //}else if(this.waitMsgTarget){
7769         //    this.waitMsgTarget.unmask();
7770         //}else{
7771         //    Roo.MessageBox.updateProgress(1);
7772         //    Roo.MessageBox.hide();
7773        // }
7774         //
7775         if(success){
7776             if(o.reset){
7777                 this.reset();
7778             }
7779             Roo.callback(o.success, o.scope, [this, action]);
7780             this.fireEvent('actioncomplete', this, action);
7781
7782         }else{
7783
7784             // failure condition..
7785             // we have a scenario where updates need confirming.
7786             // eg. if a locking scenario exists..
7787             // we look for { errors : { needs_confirm : true }} in the response.
7788             if (
7789                 (typeof(action.result) != 'undefined')  &&
7790                 (typeof(action.result.errors) != 'undefined')  &&
7791                 (typeof(action.result.errors.needs_confirm) != 'undefined')
7792            ){
7793                 var _t = this;
7794                 Roo.log("not supported yet");
7795                  /*
7796
7797                 Roo.MessageBox.confirm(
7798                     "Change requires confirmation",
7799                     action.result.errorMsg,
7800                     function(r) {
7801                         if (r != 'yes') {
7802                             return;
7803                         }
7804                         _t.doAction('submit', { params :  { _submit_confirmed : 1 } }  );
7805                     }
7806
7807                 );
7808                 */
7809
7810
7811                 return;
7812             }
7813
7814             Roo.callback(o.failure, o.scope, [this, action]);
7815             // show an error message if no failed handler is set..
7816             if (!this.hasListener('actionfailed')) {
7817                 Roo.log("need to add dialog support");
7818                 /*
7819                 Roo.MessageBox.alert("Error",
7820                     (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
7821                         action.result.errorMsg :
7822                         "Saving Failed, please check your entries or try again"
7823                 );
7824                 */
7825             }
7826
7827             this.fireEvent('actionfailed', this, action);
7828         }
7829
7830     },
7831     /**
7832      * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
7833      * @param {String} id The value to search for
7834      * @return Field
7835      */
7836     findField : function(id){
7837         var items = this.getItems();
7838         var field = items.get(id);
7839         if(!field){
7840              items.each(function(f){
7841                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
7842                     field = f;
7843                     return false;
7844                 }
7845                 return true;
7846             });
7847         }
7848         return field || null;
7849     },
7850      /**
7851      * Mark fields in this form invalid in bulk.
7852      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
7853      * @return {BasicForm} this
7854      */
7855     markInvalid : function(errors){
7856         if(errors instanceof Array){
7857             for(var i = 0, len = errors.length; i < len; i++){
7858                 var fieldError = errors[i];
7859                 var f = this.findField(fieldError.id);
7860                 if(f){
7861                     f.markInvalid(fieldError.msg);
7862                 }
7863             }
7864         }else{
7865             var field, id;
7866             for(id in errors){
7867                 if(typeof errors[id] != 'function' && (field = this.findField(id))){
7868                     field.markInvalid(errors[id]);
7869                 }
7870             }
7871         }
7872         //Roo.each(this.childForms || [], function (f) {
7873         //    f.markInvalid(errors);
7874         //});
7875
7876         return this;
7877     },
7878
7879     /**
7880      * Set values for fields in this form in bulk.
7881      * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
7882      * @return {BasicForm} this
7883      */
7884     setValues : function(values){
7885         if(values instanceof Array){ // array of objects
7886             for(var i = 0, len = values.length; i < len; i++){
7887                 var v = values[i];
7888                 var f = this.findField(v.id);
7889                 if(f){
7890                     f.setValue(v.value);
7891                     if(this.trackResetOnLoad){
7892                         f.originalValue = f.getValue();
7893                     }
7894                 }
7895             }
7896         }else{ // object hash
7897             var field, id;
7898             for(id in values){
7899                 if(typeof values[id] != 'function' && (field = this.findField(id))){
7900
7901                     if (field.setFromData &&
7902                         field.valueField &&
7903                         field.displayField &&
7904                         // combos' with local stores can
7905                         // be queried via setValue()
7906                         // to set their value..
7907                         (field.store && !field.store.isLocal)
7908                         ) {
7909                         // it's a combo
7910                         var sd = { };
7911                         sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
7912                         sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
7913                         field.setFromData(sd);
7914
7915                     } else {
7916                         field.setValue(values[id]);
7917                     }
7918
7919
7920                     if(this.trackResetOnLoad){
7921                         field.originalValue = field.getValue();
7922                     }
7923                 }
7924             }
7925         }
7926
7927         //Roo.each(this.childForms || [], function (f) {
7928         //    f.setValues(values);
7929         //});
7930
7931         return this;
7932     },
7933
7934     /**
7935      * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
7936      * they are returned as an array.
7937      * @param {Boolean} asString
7938      * @return {Object}
7939      */
7940     getValues : function(asString){
7941         //if (this.childForms) {
7942             // copy values from the child forms
7943         //    Roo.each(this.childForms, function (f) {
7944         //        this.setValues(f.getValues());
7945         //    }, this);
7946         //}
7947
7948
7949
7950         var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
7951         if(asString === true){
7952             return fs;
7953         }
7954         return Roo.urlDecode(fs);
7955     },
7956
7957     /**
7958      * Returns the fields in this form as an object with key/value pairs.
7959      * This differs from getValues as it calls getValue on each child item, rather than using dom data.
7960      * @return {Object}
7961      */
7962     getFieldValues : function(with_hidden)
7963     {
7964         var items = this.getItems();
7965         var ret = {};
7966         items.each(function(f){
7967             if (!f.getName()) {
7968                 return;
7969             }
7970             var v = f.getValue();
7971             if (f.inputType =='radio') {
7972                 if (typeof(ret[f.getName()]) == 'undefined') {
7973                     ret[f.getName()] = ''; // empty..
7974                 }
7975
7976                 if (!f.el.dom.checked) {
7977                     return;
7978
7979                 }
7980                 v = f.el.dom.value;
7981
7982             }
7983
7984             // not sure if this supported any more..
7985             if ((typeof(v) == 'object') && f.getRawValue) {
7986                 v = f.getRawValue() ; // dates..
7987             }
7988             // combo boxes where name != hiddenName...
7989             if (f.name !== false && f.name != '' && f.name != f.getName()) {
7990                 ret[f.name] = f.getRawValue();
7991             }
7992             ret[f.getName()] = v;
7993         });
7994
7995         return ret;
7996     },
7997
7998     /**
7999      * Clears all invalid messages in this form.
8000      * @return {BasicForm} this
8001      */
8002     clearInvalid : function(){
8003         var items = this.getItems();
8004
8005         items.each(function(f){
8006            f.clearInvalid();
8007         });
8008
8009
8010
8011         return this;
8012     },
8013
8014     /**
8015      * Resets this form.
8016      * @return {BasicForm} this
8017      */
8018     reset : function(){
8019         var items = this.getItems();
8020         items.each(function(f){
8021             f.reset();
8022         });
8023
8024         Roo.each(this.childForms || [], function (f) {
8025             f.reset();
8026         });
8027
8028
8029         return this;
8030     },
8031     getItems : function()
8032     {
8033         var r=new Roo.util.MixedCollection(false, function(o){
8034             return o.id || (o.id = Roo.id());
8035         });
8036         var iter = function(el) {
8037             if (el.inputEl) {
8038                 r.add(el);
8039             }
8040             if (!el.items) {
8041                 return;
8042             }
8043             Roo.each(el.items,function(e) {
8044                 iter(e);
8045             });
8046
8047
8048         };
8049
8050         iter(this);
8051         return r;
8052
8053
8054
8055
8056     }
8057
8058 });
8059
8060 Roo.apply(Roo.bootstrap.Form, {
8061     
8062     popover : {
8063         
8064         padding : 5,
8065         
8066         isApplied : false,
8067         
8068         isMasked : false,
8069         
8070         form : false,
8071         
8072         target : false,
8073         
8074         toolTip : false,
8075         
8076         intervalID : false,
8077         
8078         maskEl : false,
8079         
8080         apply : function()
8081         {
8082             if(this.isApplied){
8083                 return;
8084             }
8085             
8086             this.maskEl = {
8087                 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
8088                 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
8089                 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
8090                 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
8091             };
8092             
8093             this.maskEl.top.enableDisplayMode("block");
8094             this.maskEl.left.enableDisplayMode("block");
8095             this.maskEl.bottom.enableDisplayMode("block");
8096             this.maskEl.right.enableDisplayMode("block");
8097             
8098             this.toolTip = new Roo.bootstrap.Tooltip({
8099                 cls : 'roo-form-error-popover',
8100                 alignment : {
8101                     'left' : ['r-l', [-2,0], 'right'],
8102                     'right' : ['l-r', [2,0], 'left'],
8103                     'bottom' : ['tl-bl', [0,2], 'top'],
8104                     'top' : [ 'bl-tl', [0,-2], 'bottom']
8105                 }
8106             });
8107             
8108             this.toolTip.render(Roo.get(document.body));
8109
8110             this.toolTip.el.enableDisplayMode("block");
8111             
8112             Roo.get(document.body).on('click', function(){
8113                 this.unmask();
8114             }, this);
8115             
8116             Roo.get(document.body).on('touchstart', function(){
8117                 this.unmask();
8118             }, this);
8119             
8120             this.isApplied = true
8121         },
8122         
8123         mask : function(form, target)
8124         {
8125             this.form = form;
8126             
8127             this.target = target;
8128             
8129             if(!this.form.errorMask || !target.el){
8130                 return;
8131             }
8132             
8133             var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.modal', 100, true) || Roo.get(document.body);
8134             
8135             var ot = this.target.el.calcOffsetsTo(scrollable);
8136             
8137             var scrollTo = ot[1] - this.form.maskOffset;
8138             
8139             scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
8140             
8141             scrollable.scrollTo('top', scrollTo);
8142             
8143             var box = this.target.el.getBox();
8144             Roo.log(box);
8145             var zIndex = Roo.bootstrap.Modal.zIndex++;
8146
8147             
8148             this.maskEl.top.setStyle('position', 'absolute');
8149             this.maskEl.top.setStyle('z-index', zIndex);
8150             this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
8151             this.maskEl.top.setLeft(0);
8152             this.maskEl.top.setTop(0);
8153             this.maskEl.top.show();
8154             
8155             this.maskEl.left.setStyle('position', 'absolute');
8156             this.maskEl.left.setStyle('z-index', zIndex);
8157             this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
8158             this.maskEl.left.setLeft(0);
8159             this.maskEl.left.setTop(box.y - this.padding);
8160             this.maskEl.left.show();
8161
8162             this.maskEl.bottom.setStyle('position', 'absolute');
8163             this.maskEl.bottom.setStyle('z-index', zIndex);
8164             this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
8165             this.maskEl.bottom.setLeft(0);
8166             this.maskEl.bottom.setTop(box.bottom + this.padding);
8167             this.maskEl.bottom.show();
8168
8169             this.maskEl.right.setStyle('position', 'absolute');
8170             this.maskEl.right.setStyle('z-index', zIndex);
8171             this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
8172             this.maskEl.right.setLeft(box.right + this.padding);
8173             this.maskEl.right.setTop(box.y - this.padding);
8174             this.maskEl.right.show();
8175
8176             this.toolTip.bindEl = this.target.el;
8177
8178             this.toolTip.el.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
8179
8180             var tip = this.target.blankText;
8181
8182             if(this.target.getValue() !== '' ) {
8183                 
8184                 if (this.target.invalidText.length) {
8185                     tip = this.target.invalidText;
8186                 } else if (this.target.regexText.length){
8187                     tip = this.target.regexText;
8188                 }
8189             }
8190
8191             this.toolTip.show(tip);
8192
8193             this.intervalID = window.setInterval(function() {
8194                 Roo.bootstrap.Form.popover.unmask();
8195             }, 10000);
8196
8197             window.onwheel = function(){ return false;};
8198             
8199             (function(){ this.isMasked = true; }).defer(500, this);
8200             
8201         },
8202         
8203         unmask : function()
8204         {
8205             if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
8206                 return;
8207             }
8208             
8209             this.maskEl.top.setStyle('position', 'absolute');
8210             this.maskEl.top.setSize(0, 0).setXY([0, 0]);
8211             this.maskEl.top.hide();
8212
8213             this.maskEl.left.setStyle('position', 'absolute');
8214             this.maskEl.left.setSize(0, 0).setXY([0, 0]);
8215             this.maskEl.left.hide();
8216
8217             this.maskEl.bottom.setStyle('position', 'absolute');
8218             this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
8219             this.maskEl.bottom.hide();
8220
8221             this.maskEl.right.setStyle('position', 'absolute');
8222             this.maskEl.right.setSize(0, 0).setXY([0, 0]);
8223             this.maskEl.right.hide();
8224             
8225             this.toolTip.hide();
8226             
8227             this.toolTip.el.hide();
8228             
8229             window.onwheel = function(){ return true;};
8230             
8231             if(this.intervalID){
8232                 window.clearInterval(this.intervalID);
8233                 this.intervalID = false;
8234             }
8235             
8236             this.isMasked = false;
8237             
8238         }
8239         
8240     }
8241     
8242 });
8243
8244 /*
8245  * Based on:
8246  * Ext JS Library 1.1.1
8247  * Copyright(c) 2006-2007, Ext JS, LLC.
8248  *
8249  * Originally Released Under LGPL - original licence link has changed is not relivant.
8250  *
8251  * Fork - LGPL
8252  * <script type="text/javascript">
8253  */
8254 /**
8255  * @class Roo.form.VTypes
8256  * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
8257  * @singleton
8258  */
8259 Roo.form.VTypes = function(){
8260     // closure these in so they are only created once.
8261     var alpha = /^[a-zA-Z_]+$/;
8262     var alphanum = /^[a-zA-Z0-9_]+$/;
8263     var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
8264     var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
8265
8266     // All these messages and functions are configurable
8267     return {
8268         /**
8269          * The function used to validate email addresses
8270          * @param {String} value The email address
8271          */
8272         'email' : function(v){
8273             return email.test(v);
8274         },
8275         /**
8276          * The error text to display when the email validation function returns false
8277          * @type String
8278          */
8279         'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
8280         /**
8281          * The keystroke filter mask to be applied on email input
8282          * @type RegExp
8283          */
8284         'emailMask' : /[a-z0-9_\.\-@]/i,
8285
8286         /**
8287          * The function used to validate URLs
8288          * @param {String} value The URL
8289          */
8290         'url' : function(v){
8291             return url.test(v);
8292         },
8293         /**
8294          * The error text to display when the url validation function returns false
8295          * @type String
8296          */
8297         'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
8298         
8299         /**
8300          * The function used to validate alpha values
8301          * @param {String} value The value
8302          */
8303         'alpha' : function(v){
8304             return alpha.test(v);
8305         },
8306         /**
8307          * The error text to display when the alpha validation function returns false
8308          * @type String
8309          */
8310         'alphaText' : 'This field should only contain letters and _',
8311         /**
8312          * The keystroke filter mask to be applied on alpha input
8313          * @type RegExp
8314          */
8315         'alphaMask' : /[a-z_]/i,
8316
8317         /**
8318          * The function used to validate alphanumeric values
8319          * @param {String} value The value
8320          */
8321         'alphanum' : function(v){
8322             return alphanum.test(v);
8323         },
8324         /**
8325          * The error text to display when the alphanumeric validation function returns false
8326          * @type String
8327          */
8328         'alphanumText' : 'This field should only contain letters, numbers and _',
8329         /**
8330          * The keystroke filter mask to be applied on alphanumeric input
8331          * @type RegExp
8332          */
8333         'alphanumMask' : /[a-z0-9_]/i
8334     };
8335 }();/*
8336  * - LGPL
8337  *
8338  * Input
8339  * 
8340  */
8341
8342 /**
8343  * @class Roo.bootstrap.Input
8344  * @extends Roo.bootstrap.Component
8345  * Bootstrap Input class
8346  * @cfg {Boolean} disabled is it disabled
8347  * @cfg {String} inputType button | checkbox | email | file | hidden | image | number | password | radio | range | reset | search | submit | text
8348  * @cfg {String} name name of the input
8349  * @cfg {string} fieldLabel - the label associated
8350  * @cfg {string} placeholder - placeholder to put in text.
8351  * @cfg {string}  before - input group add on before
8352  * @cfg {string} after - input group add on after
8353  * @cfg {string} size - (lg|sm) or leave empty..
8354  * @cfg {Number} xs colspan out of 12 for mobile-sized screens
8355  * @cfg {Number} sm colspan out of 12 for tablet-sized screens
8356  * @cfg {Number} md colspan out of 12 for computer-sized screens
8357  * @cfg {Number} lg colspan out of 12 for large computer-sized screens
8358  * @cfg {string} value default value of the input
8359  * @cfg {Number} labelWidth set the width of label 
8360  * @cfg {Number} labellg set the width of label (1-12)
8361  * @cfg {Number} labelmd set the width of label (1-12)
8362  * @cfg {Number} labelsm set the width of label (1-12)
8363  * @cfg {Number} labelxs set the width of label (1-12)
8364  * @cfg {String} labelAlign (top|left)
8365  * @cfg {Boolean} readOnly Specifies that the field should be read-only
8366  * @cfg {String} autocomplete - default is new-password see: https://developers.google.com/web/fundamentals/input/form/label-and-name-inputs?hl=en
8367  * @cfg {String} indicatorpos (left|right) default left
8368
8369  * @cfg {String} align (left|center|right) Default left
8370  * @cfg {Boolean} forceFeedback (true|false) Default false
8371  * 
8372  * 
8373  * 
8374  * 
8375  * @constructor
8376  * Create a new Input
8377  * @param {Object} config The config object
8378  */
8379
8380 Roo.bootstrap.Input = function(config){
8381     
8382     Roo.bootstrap.Input.superclass.constructor.call(this, config);
8383     
8384     this.addEvents({
8385         /**
8386          * @event focus
8387          * Fires when this field receives input focus.
8388          * @param {Roo.form.Field} this
8389          */
8390         focus : true,
8391         /**
8392          * @event blur
8393          * Fires when this field loses input focus.
8394          * @param {Roo.form.Field} this
8395          */
8396         blur : true,
8397         /**
8398          * @event specialkey
8399          * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
8400          * {@link Roo.EventObject#getKey} to determine which key was pressed.
8401          * @param {Roo.form.Field} this
8402          * @param {Roo.EventObject} e The event object
8403          */
8404         specialkey : true,
8405         /**
8406          * @event change
8407          * Fires just before the field blurs if the field value has changed.
8408          * @param {Roo.form.Field} this
8409          * @param {Mixed} newValue The new value
8410          * @param {Mixed} oldValue The original value
8411          */
8412         change : true,
8413         /**
8414          * @event invalid
8415          * Fires after the field has been marked as invalid.
8416          * @param {Roo.form.Field} this
8417          * @param {String} msg The validation message
8418          */
8419         invalid : true,
8420         /**
8421          * @event valid
8422          * Fires after the field has been validated with no errors.
8423          * @param {Roo.form.Field} this
8424          */
8425         valid : true,
8426          /**
8427          * @event keyup
8428          * Fires after the key up
8429          * @param {Roo.form.Field} this
8430          * @param {Roo.EventObject}  e The event Object
8431          */
8432         keyup : true
8433     });
8434 };
8435
8436 Roo.extend(Roo.bootstrap.Input, Roo.bootstrap.Component,  {
8437      /**
8438      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
8439       automatic validation (defaults to "keyup").
8440      */
8441     validationEvent : "keyup",
8442      /**
8443      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
8444      */
8445     validateOnBlur : true,
8446     /**
8447      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
8448      */
8449     validationDelay : 250,
8450      /**
8451      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
8452      */
8453     focusClass : "x-form-focus",  // not needed???
8454     
8455        
8456     /**
8457      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
8458      */
8459     invalidClass : "has-warning",
8460     
8461     /**
8462      * @cfg {String} validClass The CSS class to use when marking a field valid (defaults to "x-form-invalid")
8463      */
8464     validClass : "has-success",
8465     
8466     /**
8467      * @cfg {Boolean} hasFeedback (true|false) default true
8468      */
8469     hasFeedback : true,
8470     
8471     /**
8472      * @cfg {String} invalidFeedbackIcon The CSS class to use when create feedback icon (defaults to "x-form-invalid")
8473      */
8474     invalidFeedbackClass : "glyphicon-warning-sign",
8475     
8476     /**
8477      * @cfg {String} validFeedbackIcon The CSS class to use when create feedback icon (defaults to "x-form-invalid")
8478      */
8479     validFeedbackClass : "glyphicon-ok",
8480     
8481     /**
8482      * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
8483      */
8484     selectOnFocus : false,
8485     
8486      /**
8487      * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
8488      */
8489     maskRe : null,
8490        /**
8491      * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
8492      */
8493     vtype : null,
8494     
8495       /**
8496      * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
8497      */
8498     disableKeyFilter : false,
8499     
8500        /**
8501      * @cfg {Boolean} disabled True to disable the field (defaults to false).
8502      */
8503     disabled : false,
8504      /**
8505      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
8506      */
8507     allowBlank : true,
8508     /**
8509      * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
8510      */
8511     blankText : "Please complete this mandatory field",
8512     
8513      /**
8514      * @cfg {Number} minLength Minimum input field length required (defaults to 0)
8515      */
8516     minLength : 0,
8517     /**
8518      * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
8519      */
8520     maxLength : Number.MAX_VALUE,
8521     /**
8522      * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
8523      */
8524     minLengthText : "The minimum length for this field is {0}",
8525     /**
8526      * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
8527      */
8528     maxLengthText : "The maximum length for this field is {0}",
8529   
8530     
8531     /**
8532      * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
8533      * If available, this function will be called only after the basic validators all return true, and will be passed the
8534      * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
8535      */
8536     validator : null,
8537     /**
8538      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
8539      * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
8540      * current field value.  If the test fails, the field will be marked invalid using {@link #regexText}.
8541      */
8542     regex : null,
8543     /**
8544      * @cfg {String} regexText -- Depricated - use Invalid Text
8545      */
8546     regexText : "",
8547     
8548     /**
8549      * @cfg {String} invalidText The error text to display if {@link #validator} test fails during validation (defaults to "")
8550      */
8551     invalidText : "",
8552     
8553     
8554     
8555     autocomplete: false,
8556     
8557     
8558     fieldLabel : '',
8559     inputType : 'text',
8560     
8561     name : false,
8562     placeholder: false,
8563     before : false,
8564     after : false,
8565     size : false,
8566     hasFocus : false,
8567     preventMark: false,
8568     isFormField : true,
8569     value : '',
8570     labelWidth : 2,
8571     labelAlign : false,
8572     readOnly : false,
8573     align : false,
8574     formatedValue : false,
8575     forceFeedback : false,
8576     
8577     indicatorpos : 'left',
8578     
8579     labellg : 0,
8580     labelmd : 0,
8581     labelsm : 0,
8582     labelxs : 0,
8583     
8584     parentLabelAlign : function()
8585     {
8586         var parent = this;
8587         while (parent.parent()) {
8588             parent = parent.parent();
8589             if (typeof(parent.labelAlign) !='undefined') {
8590                 return parent.labelAlign;
8591             }
8592         }
8593         return 'left';
8594         
8595     },
8596     
8597     getAutoCreate : function()
8598     {
8599         var align = (!this.labelAlign) ? this.parentLabelAlign() : this.labelAlign;
8600         
8601         var id = Roo.id();
8602         
8603         var cfg = {};
8604         
8605         if(this.inputType != 'hidden'){
8606             cfg.cls = 'form-group' //input-group
8607         }
8608         
8609         var input =  {
8610             tag: 'input',
8611             id : id,
8612             type : this.inputType,
8613             value : this.value,
8614             cls : 'form-control',
8615             placeholder : this.placeholder || '',
8616             autocomplete : this.autocomplete || 'new-password'
8617         };
8618         
8619         if(this.align){
8620             input.style = (typeof(input.style) == 'undefined') ? ('text-align:' + this.align) : (input.style + 'text-align:' + this.align);
8621         }
8622         
8623         if(this.maxLength && this.maxLength != Number.MAX_VALUE){
8624             input.maxLength = this.maxLength;
8625         }
8626         
8627         if (this.disabled) {
8628             input.disabled=true;
8629         }
8630         
8631         if (this.readOnly) {
8632             input.readonly=true;
8633         }
8634         
8635         if (this.name) {
8636             input.name = this.name;
8637         }
8638         
8639         if (this.size) {
8640             input.cls += ' input-' + this.size;
8641         }
8642         
8643         var settings=this;
8644         ['xs','sm','md','lg'].map(function(size){
8645             if (settings[size]) {
8646                 cfg.cls += ' col-' + size + '-' + settings[size];
8647             }
8648         });
8649         
8650         var inputblock = input;
8651         
8652         var feedback = {
8653             tag: 'span',
8654             cls: 'glyphicon form-control-feedback'
8655         };
8656             
8657         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
8658             
8659             inputblock = {
8660                 cls : 'has-feedback',
8661                 cn :  [
8662                     input,
8663                     feedback
8664                 ] 
8665             };  
8666         }
8667         
8668         if (this.before || this.after) {
8669             
8670             inputblock = {
8671                 cls : 'input-group',
8672                 cn :  [] 
8673             };
8674             
8675             if (this.before && typeof(this.before) == 'string') {
8676                 
8677                 inputblock.cn.push({
8678                     tag :'span',
8679                     cls : 'roo-input-before input-group-addon',
8680                     html : this.before
8681                 });
8682             }
8683             if (this.before && typeof(this.before) == 'object') {
8684                 this.before = Roo.factory(this.before);
8685                 
8686                 inputblock.cn.push({
8687                     tag :'span',
8688                     cls : 'roo-input-before input-group-' +
8689                         (this.before.xtype == 'Button' ? 'btn' : 'addon')  //?? what about checkboxes - that looks like a bit of a hack thought? 
8690                 });
8691             }
8692             
8693             inputblock.cn.push(input);
8694             
8695             if (this.after && typeof(this.after) == 'string') {
8696                 inputblock.cn.push({
8697                     tag :'span',
8698                     cls : 'roo-input-after input-group-addon',
8699                     html : this.after
8700                 });
8701             }
8702             if (this.after && typeof(this.after) == 'object') {
8703                 this.after = Roo.factory(this.after);
8704                 
8705                 inputblock.cn.push({
8706                     tag :'span',
8707                     cls : 'roo-input-after input-group-' +
8708                         (this.after.xtype == 'Button' ? 'btn' : 'addon')  //?? what about checkboxes - that looks like a bit of a hack thought? 
8709                 });
8710             }
8711             
8712             if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
8713                 inputblock.cls += ' has-feedback';
8714                 inputblock.cn.push(feedback);
8715             }
8716         };
8717         
8718         if (align ==='left' && this.fieldLabel.length) {
8719             
8720             cfg.cls += ' roo-form-group-label-left';
8721             
8722             cfg.cn = [
8723                 {
8724                     tag : 'i',
8725                     cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
8726                     tooltip : 'This field is required'
8727                 },
8728                 {
8729                     tag: 'label',
8730                     'for' :  id,
8731                     cls : 'control-label',
8732                     html : this.fieldLabel
8733
8734                 },
8735                 {
8736                     cls : "", 
8737                     cn: [
8738                         inputblock
8739                     ]
8740                 }
8741             ];
8742             
8743             var labelCfg = cfg.cn[1];
8744             var contentCfg = cfg.cn[2];
8745             
8746             if(this.indicatorpos == 'right'){
8747                 cfg.cn = [
8748                     {
8749                         tag: 'label',
8750                         'for' :  id,
8751                         cls : 'control-label',
8752                         html : this.fieldLabel
8753
8754                     },
8755                     {
8756                         tag : 'i',
8757                         cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
8758                         tooltip : 'This field is required'
8759                     },
8760                     {
8761                         cls : "",
8762                         cn: [
8763                             inputblock
8764                         ]
8765                     }
8766
8767                 ];
8768                 
8769                 labelCfg = cfg.cn[0];
8770                 contentCfg = cfg.cn[2];
8771             
8772             }
8773             
8774             if(this.labelWidth > 12){
8775                 labelCfg.style = "width: " + this.labelWidth + 'px';
8776             }
8777             
8778             if(this.labelWidth < 13 && this.labelmd == 0){
8779                 this.labelmd = this.labelWidth;
8780             }
8781             
8782             if(this.labellg > 0){
8783                 labelCfg.cls += ' col-lg-' + this.labellg;
8784                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
8785             }
8786             
8787             if(this.labelmd > 0){
8788                 labelCfg.cls += ' col-md-' + this.labelmd;
8789                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
8790             }
8791             
8792             if(this.labelsm > 0){
8793                 labelCfg.cls += ' col-sm-' + this.labelsm;
8794                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
8795             }
8796             
8797             if(this.labelxs > 0){
8798                 labelCfg.cls += ' col-xs-' + this.labelxs;
8799                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
8800             }
8801             
8802             
8803         } else if ( this.fieldLabel.length) {
8804                 
8805             cfg.cn = [
8806                 {
8807                     tag : 'i',
8808                     cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
8809                     tooltip : 'This field is required'
8810                 },
8811                 {
8812                     tag: 'label',
8813                    //cls : 'input-group-addon',
8814                     html : this.fieldLabel
8815
8816                 },
8817
8818                inputblock
8819
8820            ];
8821            
8822            if(this.indicatorpos == 'right'){
8823                 
8824                 cfg.cn = [
8825                     {
8826                         tag: 'label',
8827                        //cls : 'input-group-addon',
8828                         html : this.fieldLabel
8829
8830                     },
8831                     {
8832                         tag : 'i',
8833                         cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
8834                         tooltip : 'This field is required'
8835                     },
8836
8837                    inputblock
8838
8839                ];
8840
8841             }
8842
8843         } else {
8844             
8845             cfg.cn = [
8846
8847                     inputblock
8848
8849             ];
8850                 
8851                 
8852         };
8853         
8854         if (this.parentType === 'Navbar' &&  this.parent().bar) {
8855            cfg.cls += ' navbar-form';
8856         }
8857         
8858         if (this.parentType === 'NavGroup') {
8859            cfg.cls += ' navbar-form';
8860            cfg.tag = 'li';
8861         }
8862         
8863         return cfg;
8864         
8865     },
8866     /**
8867      * return the real input element.
8868      */
8869     inputEl: function ()
8870     {
8871         return this.el.select('input.form-control',true).first();
8872     },
8873     
8874     tooltipEl : function()
8875     {
8876         return this.inputEl();
8877     },
8878     
8879     indicatorEl : function()
8880     {
8881         var indicator = this.el.select('i.roo-required-indicator',true).first();
8882         
8883         if(!indicator){
8884             return false;
8885         }
8886         
8887         return indicator;
8888         
8889     },
8890     
8891     setDisabled : function(v)
8892     {
8893         var i  = this.inputEl().dom;
8894         if (!v) {
8895             i.removeAttribute('disabled');
8896             return;
8897             
8898         }
8899         i.setAttribute('disabled','true');
8900     },
8901     initEvents : function()
8902     {
8903           
8904         this.inputEl().on("keydown" , this.fireKey,  this);
8905         this.inputEl().on("focus", this.onFocus,  this);
8906         this.inputEl().on("blur", this.onBlur,  this);
8907         
8908         this.inputEl().relayEvent('keyup', this);
8909         
8910         this.indicator = this.indicatorEl();
8911         
8912         if(this.indicator){
8913             this.indicator.setVisibilityMode(Roo.Element.DISPLAY);
8914             this.indicator.hide();
8915         }
8916  
8917         // reference to original value for reset
8918         this.originalValue = this.getValue();
8919         //Roo.form.TextField.superclass.initEvents.call(this);
8920         if(this.validationEvent == 'keyup'){
8921             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
8922             this.inputEl().on('keyup', this.filterValidation, this);
8923         }
8924         else if(this.validationEvent !== false){
8925             this.inputEl().on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
8926         }
8927         
8928         if(this.selectOnFocus){
8929             this.on("focus", this.preFocus, this);
8930             
8931         }
8932         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
8933             this.inputEl().on("keypress", this.filterKeys, this);
8934         } else {
8935             this.inputEl().relayEvent('keypress', this);
8936         }
8937        /* if(this.grow){
8938             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
8939             this.el.on("click", this.autoSize,  this);
8940         }
8941         */
8942         if(this.inputEl().is('input[type=password]') && Roo.isSafari){
8943             this.inputEl().on('keydown', this.SafariOnKeyDown, this);
8944         }
8945         
8946         if (typeof(this.before) == 'object') {
8947             this.before.render(this.el.select('.roo-input-before',true).first());
8948         }
8949         if (typeof(this.after) == 'object') {
8950             this.after.render(this.el.select('.roo-input-after',true).first());
8951         }
8952         
8953         
8954     },
8955     filterValidation : function(e){
8956         if(!e.isNavKeyPress()){
8957             this.validationTask.delay(this.validationDelay);
8958         }
8959     },
8960      /**
8961      * Validates the field value
8962      * @return {Boolean} True if the value is valid, else false
8963      */
8964     validate : function(){
8965         //if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
8966         if(this.disabled || this.validateValue(this.getRawValue())){
8967             this.markValid();
8968             return true;
8969         }
8970         
8971         this.markInvalid();
8972         return false;
8973     },
8974     
8975     
8976     /**
8977      * Validates a value according to the field's validation rules and marks the field as invalid
8978      * if the validation fails
8979      * @param {Mixed} value The value to validate
8980      * @return {Boolean} True if the value is valid, else false
8981      */
8982     validateValue : function(value){
8983         if(value.length < 1)  { // if it's blank
8984             if(this.allowBlank){
8985                 return true;
8986             }            
8987             return this.inputEl().hasClass('hide') ? true : false;
8988         }
8989         
8990         if(value.length < this.minLength){
8991             return false;
8992         }
8993         if(value.length > this.maxLength){
8994             return false;
8995         }
8996         if(this.vtype){
8997             var vt = Roo.form.VTypes;
8998             if(!vt[this.vtype](value, this)){
8999                 return false;
9000             }
9001         }
9002         if(typeof this.validator == "function"){
9003             var msg = this.validator(value);
9004             if(msg !== true){
9005                 return false;
9006             }
9007             if (typeof(msg) == 'string') {
9008                 this.invalidText = msg;
9009             }
9010         }
9011         
9012         if(this.regex && !this.regex.test(value)){
9013             return false;
9014         }
9015         
9016         return true;
9017     },
9018
9019     
9020     
9021      // private
9022     fireKey : function(e){
9023         //Roo.log('field ' + e.getKey());
9024         if(e.isNavKeyPress()){
9025             this.fireEvent("specialkey", this, e);
9026         }
9027     },
9028     focus : function (selectText){
9029         if(this.rendered){
9030             this.inputEl().focus();
9031             if(selectText === true){
9032                 this.inputEl().dom.select();
9033             }
9034         }
9035         return this;
9036     } ,
9037     
9038     onFocus : function(){
9039         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
9040            // this.el.addClass(this.focusClass);
9041         }
9042         if(!this.hasFocus){
9043             this.hasFocus = true;
9044             this.startValue = this.getValue();
9045             this.fireEvent("focus", this);
9046         }
9047     },
9048     
9049     beforeBlur : Roo.emptyFn,
9050
9051     
9052     // private
9053     onBlur : function(){
9054         this.beforeBlur();
9055         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
9056             //this.el.removeClass(this.focusClass);
9057         }
9058         this.hasFocus = false;
9059         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
9060             this.validate();
9061         }
9062         var v = this.getValue();
9063         if(String(v) !== String(this.startValue)){
9064             this.fireEvent('change', this, v, this.startValue);
9065         }
9066         this.fireEvent("blur", this);
9067     },
9068     
9069     /**
9070      * Resets the current field value to the originally loaded value and clears any validation messages
9071      */
9072     reset : function(){
9073         this.setValue(this.originalValue);
9074         this.validate();
9075     },
9076      /**
9077      * Returns the name of the field
9078      * @return {Mixed} name The name field
9079      */
9080     getName: function(){
9081         return this.name;
9082     },
9083      /**
9084      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
9085      * @return {Mixed} value The field value
9086      */
9087     getValue : function(){
9088         
9089         var v = this.inputEl().getValue();
9090         
9091         return v;
9092     },
9093     /**
9094      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
9095      * @return {Mixed} value The field value
9096      */
9097     getRawValue : function(){
9098         var v = this.inputEl().getValue();
9099         
9100         return v;
9101     },
9102     
9103     /**
9104      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
9105      * @param {Mixed} value The value to set
9106      */
9107     setRawValue : function(v){
9108         return this.inputEl().dom.value = (v === null || v === undefined ? '' : v);
9109     },
9110     
9111     selectText : function(start, end){
9112         var v = this.getRawValue();
9113         if(v.length > 0){
9114             start = start === undefined ? 0 : start;
9115             end = end === undefined ? v.length : end;
9116             var d = this.inputEl().dom;
9117             if(d.setSelectionRange){
9118                 d.setSelectionRange(start, end);
9119             }else if(d.createTextRange){
9120                 var range = d.createTextRange();
9121                 range.moveStart("character", start);
9122                 range.moveEnd("character", v.length-end);
9123                 range.select();
9124             }
9125         }
9126     },
9127     
9128     /**
9129      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
9130      * @param {Mixed} value The value to set
9131      */
9132     setValue : function(v){
9133         this.value = v;
9134         if(this.rendered){
9135             this.inputEl().dom.value = (v === null || v === undefined ? '' : v);
9136             this.validate();
9137         }
9138     },
9139     
9140     /*
9141     processValue : function(value){
9142         if(this.stripCharsRe){
9143             var newValue = value.replace(this.stripCharsRe, '');
9144             if(newValue !== value){
9145                 this.setRawValue(newValue);
9146                 return newValue;
9147             }
9148         }
9149         return value;
9150     },
9151   */
9152     preFocus : function(){
9153         
9154         if(this.selectOnFocus){
9155             this.inputEl().dom.select();
9156         }
9157     },
9158     filterKeys : function(e){
9159         var k = e.getKey();
9160         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
9161             return;
9162         }
9163         var c = e.getCharCode(), cc = String.fromCharCode(c);
9164         if(Roo.isIE && (e.isSpecialKey() || !cc)){
9165             return;
9166         }
9167         if(!this.maskRe.test(cc)){
9168             e.stopEvent();
9169         }
9170     },
9171      /**
9172      * Clear any invalid styles/messages for this field
9173      */
9174     clearInvalid : function(){
9175         
9176         if(!this.el || this.preventMark){ // not rendered
9177             return;
9178         }
9179         
9180      
9181         this.el.removeClass(this.invalidClass);
9182         
9183         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
9184             
9185             var feedback = this.el.select('.form-control-feedback', true).first();
9186             
9187             if(feedback){
9188                 this.el.select('.form-control-feedback', true).first().removeClass(this.invalidFeedbackClass);
9189             }
9190             
9191         }
9192         
9193         this.fireEvent('valid', this);
9194     },
9195     
9196      /**
9197      * Mark this field as valid
9198      */
9199     markValid : function()
9200     {
9201         if(!this.el  || this.preventMark){ // not rendered...
9202             return;
9203         }
9204         
9205         this.el.removeClass([this.invalidClass, this.validClass]);
9206         
9207         var feedback = this.el.select('.form-control-feedback', true).first();
9208             
9209         if(feedback){
9210             this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
9211         }
9212
9213         if(this.disabled){
9214             return;
9215         }
9216         
9217         if(this.allowBlank && !this.getRawValue().length){
9218             return;
9219         }
9220         
9221         if(this.indicator){
9222             this.indicator.hide();
9223         }
9224         
9225         this.el.addClass(this.validClass);
9226         
9227         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank && (this.getValue().length || this.forceFeedback)){
9228             
9229             var feedback = this.el.select('.form-control-feedback', true).first();
9230             
9231             if(feedback){
9232                 this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
9233                 this.el.select('.form-control-feedback', true).first().addClass([this.validFeedbackClass]);
9234             }
9235             
9236         }
9237         
9238         this.fireEvent('valid', this);
9239     },
9240     
9241      /**
9242      * Mark this field as invalid
9243      * @param {String} msg The validation message
9244      */
9245     markInvalid : function(msg)
9246     {
9247         if(!this.el  || this.preventMark){ // not rendered
9248             return;
9249         }
9250         
9251         this.el.removeClass([this.invalidClass, this.validClass]);
9252         
9253         var feedback = this.el.select('.form-control-feedback', true).first();
9254             
9255         if(feedback){
9256             this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
9257         }
9258
9259         if(this.disabled){
9260             return;
9261         }
9262         
9263         if(this.allowBlank && !this.getRawValue().length){
9264             return;
9265         }
9266         
9267         if(this.indicator){
9268             this.indicator.show();
9269         }
9270         
9271         this.el.addClass(this.invalidClass);
9272         
9273         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
9274             
9275             var feedback = this.el.select('.form-control-feedback', true).first();
9276             
9277             if(feedback){
9278                 this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
9279                 
9280                 if(this.getValue().length || this.forceFeedback){
9281                     this.el.select('.form-control-feedback', true).first().addClass([this.invalidFeedbackClass]);
9282                 }
9283                 
9284             }
9285             
9286         }
9287         
9288         this.fireEvent('invalid', this, msg);
9289     },
9290     // private
9291     SafariOnKeyDown : function(event)
9292     {
9293         // this is a workaround for a password hang bug on chrome/ webkit.
9294         if (this.inputEl().dom.type != 'password') {
9295             return;
9296         }
9297         
9298         var isSelectAll = false;
9299         
9300         if(this.inputEl().dom.selectionEnd > 0){
9301             isSelectAll = (this.inputEl().dom.selectionEnd - this.inputEl().dom.selectionStart - this.getValue().length == 0) ? true : false;
9302         }
9303         if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
9304             event.preventDefault();
9305             this.setValue('');
9306             return;
9307         }
9308         
9309         if(isSelectAll  && event.getCharCode() > 31 && !event.ctrlKey) { // not backspace and delete key (or ctrl-v)
9310             
9311             event.preventDefault();
9312             // this is very hacky as keydown always get's upper case.
9313             //
9314             var cc = String.fromCharCode(event.getCharCode());
9315             this.setValue( event.shiftKey ?  cc : cc.toLowerCase());
9316             
9317         }
9318     },
9319     adjustWidth : function(tag, w){
9320         tag = tag.toLowerCase();
9321         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
9322             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
9323                 if(tag == 'input'){
9324                     return w + 2;
9325                 }
9326                 if(tag == 'textarea'){
9327                     return w-2;
9328                 }
9329             }else if(Roo.isOpera){
9330                 if(tag == 'input'){
9331                     return w + 2;
9332                 }
9333                 if(tag == 'textarea'){
9334                     return w-2;
9335                 }
9336             }
9337         }
9338         return w;
9339     }
9340     
9341 });
9342
9343  
9344 /*
9345  * - LGPL
9346  *
9347  * Input
9348  * 
9349  */
9350
9351 /**
9352  * @class Roo.bootstrap.TextArea
9353  * @extends Roo.bootstrap.Input
9354  * Bootstrap TextArea class
9355  * @cfg {Number} cols Specifies the visible width of a text area
9356  * @cfg {Number} rows Specifies the visible number of lines in a text area
9357  * @cfg {string} wrap (soft|hard)Specifies how the text in a text area is to be wrapped when submitted in a form
9358  * @cfg {string} resize (none|both|horizontal|vertical|inherit|initial)
9359  * @cfg {string} html text
9360  * 
9361  * @constructor
9362  * Create a new TextArea
9363  * @param {Object} config The config object
9364  */
9365
9366 Roo.bootstrap.TextArea = function(config){
9367     Roo.bootstrap.TextArea.superclass.constructor.call(this, config);
9368    
9369 };
9370
9371 Roo.extend(Roo.bootstrap.TextArea, Roo.bootstrap.Input,  {
9372      
9373     cols : false,
9374     rows : 5,
9375     readOnly : false,
9376     warp : 'soft',
9377     resize : false,
9378     value: false,
9379     html: false,
9380     
9381     getAutoCreate : function(){
9382         
9383         var align = (!this.labelAlign) ? this.parentLabelAlign() : this.labelAlign;
9384         
9385         var id = Roo.id();
9386         
9387         var cfg = {};
9388         
9389         var input =  {
9390             tag: 'textarea',
9391             id : id,
9392             warp : this.warp,
9393             rows : this.rows,
9394             value : this.value || '',
9395             html: this.html || '',
9396             cls : 'form-control',
9397             placeholder : this.placeholder || '' 
9398             
9399         };
9400         
9401         if(this.maxLength && this.maxLength != Number.MAX_VALUE){
9402             input.maxLength = this.maxLength;
9403         }
9404         
9405         if(this.resize){
9406             input.style = (typeof(input.style) == 'undefined') ? 'resize:' + this.resize : input.style + 'resize:' + this.resize;
9407         }
9408         
9409         if(this.cols){
9410             input.cols = this.cols;
9411         }
9412         
9413         if (this.readOnly) {
9414             input.readonly = true;
9415         }
9416         
9417         if (this.name) {
9418             input.name = this.name;
9419         }
9420         
9421         if (this.size) {
9422             input.cls = (typeof(input.cls) == 'undefined') ? 'input-' + this.size : input.cls + ' input-' + this.size;
9423         }
9424         
9425         var settings=this;
9426         ['xs','sm','md','lg'].map(function(size){
9427             if (settings[size]) {
9428                 cfg.cls += ' col-' + size + '-' + settings[size];
9429             }
9430         });
9431         
9432         var inputblock = input;
9433         
9434         if(this.hasFeedback && !this.allowBlank){
9435             
9436             var feedback = {
9437                 tag: 'span',
9438                 cls: 'glyphicon form-control-feedback'
9439             };
9440
9441             inputblock = {
9442                 cls : 'has-feedback',
9443                 cn :  [
9444                     input,
9445                     feedback
9446                 ] 
9447             };  
9448         }
9449         
9450         
9451         if (this.before || this.after) {
9452             
9453             inputblock = {
9454                 cls : 'input-group',
9455                 cn :  [] 
9456             };
9457             if (this.before) {
9458                 inputblock.cn.push({
9459                     tag :'span',
9460                     cls : 'input-group-addon',
9461                     html : this.before
9462                 });
9463             }
9464             
9465             inputblock.cn.push(input);
9466             
9467             if(this.hasFeedback && !this.allowBlank){
9468                 inputblock.cls += ' has-feedback';
9469                 inputblock.cn.push(feedback);
9470             }
9471             
9472             if (this.after) {
9473                 inputblock.cn.push({
9474                     tag :'span',
9475                     cls : 'input-group-addon',
9476                     html : this.after
9477                 });
9478             }
9479             
9480         }
9481         
9482         if (align ==='left' && this.fieldLabel.length) {
9483             cfg.cn = [
9484                 {
9485                     tag: 'label',
9486                     'for' :  id,
9487                     cls : 'control-label',
9488                     html : this.fieldLabel
9489                 },
9490                 {
9491                     cls : "",
9492                     cn: [
9493                         inputblock
9494                     ]
9495                 }
9496
9497             ];
9498             
9499             if(this.labelWidth > 12){
9500                 cfg.cn[0].style = "width: " + this.labelWidth + 'px';
9501             }
9502
9503             if(this.labelWidth < 13 && this.labelmd == 0){
9504                 this.labelmd = this.labelWidth;
9505             }
9506
9507             if(this.labellg > 0){
9508                 cfg.cn[0].cls += ' col-lg-' + this.labellg;
9509                 cfg.cn[1].cls += ' col-lg-' + (12 - this.labellg);
9510             }
9511
9512             if(this.labelmd > 0){
9513                 cfg.cn[0].cls += ' col-md-' + this.labelmd;
9514                 cfg.cn[1].cls += ' col-md-' + (12 - this.labelmd);
9515             }
9516
9517             if(this.labelsm > 0){
9518                 cfg.cn[0].cls += ' col-sm-' + this.labelsm;
9519                 cfg.cn[1].cls += ' col-sm-' + (12 - this.labelsm);
9520             }
9521
9522             if(this.labelxs > 0){
9523                 cfg.cn[0].cls += ' col-xs-' + this.labelxs;
9524                 cfg.cn[1].cls += ' col-xs-' + (12 - this.labelxs);
9525             }
9526             
9527         } else if ( this.fieldLabel.length) {
9528             cfg.cn = [
9529
9530                {
9531                    tag: 'label',
9532                    //cls : 'input-group-addon',
9533                    html : this.fieldLabel
9534
9535                },
9536
9537                inputblock
9538
9539            ];
9540
9541         } else {
9542
9543             cfg.cn = [
9544
9545                 inputblock
9546
9547             ];
9548                 
9549         }
9550         
9551         if (this.disabled) {
9552             input.disabled=true;
9553         }
9554         
9555         return cfg;
9556         
9557     },
9558     /**
9559      * return the real textarea element.
9560      */
9561     inputEl: function ()
9562     {
9563         return this.el.select('textarea.form-control',true).first();
9564     },
9565     
9566     /**
9567      * Clear any invalid styles/messages for this field
9568      */
9569     clearInvalid : function()
9570     {
9571         
9572         if(!this.el || this.preventMark){ // not rendered
9573             return;
9574         }
9575         
9576         var label = this.el.select('label', true).first();
9577         var icon = this.el.select('i.fa-star', true).first();
9578         
9579         if(label && icon){
9580             icon.remove();
9581         }
9582         
9583         this.el.removeClass(this.invalidClass);
9584         
9585         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
9586             
9587             var feedback = this.el.select('.form-control-feedback', true).first();
9588             
9589             if(feedback){
9590                 this.el.select('.form-control-feedback', true).first().removeClass(this.invalidFeedbackClass);
9591             }
9592             
9593         }
9594         
9595         this.fireEvent('valid', this);
9596     },
9597     
9598      /**
9599      * Mark this field as valid
9600      */
9601     markValid : function()
9602     {
9603         if(!this.el  || this.preventMark){ // not rendered
9604             return;
9605         }
9606         
9607         this.el.removeClass([this.invalidClass, this.validClass]);
9608         
9609         var feedback = this.el.select('.form-control-feedback', true).first();
9610             
9611         if(feedback){
9612             this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
9613         }
9614
9615         if(this.disabled || this.allowBlank){
9616             return;
9617         }
9618         
9619         var label = this.el.select('label', true).first();
9620         var icon = this.el.select('i.fa-star', true).first();
9621         
9622         if(label && icon){
9623             icon.remove();
9624         }
9625         
9626         this.el.addClass(this.validClass);
9627         
9628         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank && (this.getValue().length || this.forceFeedback)){
9629             
9630             var feedback = this.el.select('.form-control-feedback', true).first();
9631             
9632             if(feedback){
9633                 this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
9634                 this.el.select('.form-control-feedback', true).first().addClass([this.validFeedbackClass]);
9635             }
9636             
9637         }
9638         
9639         this.fireEvent('valid', this);
9640     },
9641     
9642      /**
9643      * Mark this field as invalid
9644      * @param {String} msg The validation message
9645      */
9646     markInvalid : function(msg)
9647     {
9648         if(!this.el  || this.preventMark){ // not rendered
9649             return;
9650         }
9651         
9652         this.el.removeClass([this.invalidClass, this.validClass]);
9653         
9654         var feedback = this.el.select('.form-control-feedback', true).first();
9655             
9656         if(feedback){
9657             this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
9658         }
9659
9660         if(this.disabled || this.allowBlank){
9661             return;
9662         }
9663         
9664         var label = this.el.select('label', true).first();
9665         var icon = this.el.select('i.fa-star', true).first();
9666         
9667         if(!this.getValue().length && label && !icon){
9668             this.el.createChild({
9669                 tag : 'i',
9670                 cls : 'text-danger fa fa-lg fa-star',
9671                 tooltip : 'This field is required',
9672                 style : 'margin-right:5px;'
9673             }, label, true);
9674         }
9675
9676         this.el.addClass(this.invalidClass);
9677         
9678         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
9679             
9680             var feedback = this.el.select('.form-control-feedback', true).first();
9681             
9682             if(feedback){
9683                 this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
9684                 
9685                 if(this.getValue().length || this.forceFeedback){
9686                     this.el.select('.form-control-feedback', true).first().addClass([this.invalidFeedbackClass]);
9687                 }
9688                 
9689             }
9690             
9691         }
9692         
9693         this.fireEvent('invalid', this, msg);
9694     }
9695 });
9696
9697  
9698 /*
9699  * - LGPL
9700  *
9701  * trigger field - base class for combo..
9702  * 
9703  */
9704  
9705 /**
9706  * @class Roo.bootstrap.TriggerField
9707  * @extends Roo.bootstrap.Input
9708  * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
9709  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
9710  * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
9711  * for which you can provide a custom implementation.  For example:
9712  * <pre><code>
9713 var trigger = new Roo.bootstrap.TriggerField();
9714 trigger.onTriggerClick = myTriggerFn;
9715 trigger.applyTo('my-field');
9716 </code></pre>
9717  *
9718  * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
9719  * {@link Roo.bootstrap.DateField} and {@link Roo.bootstrap.ComboBox} are perfect examples of this.
9720  * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
9721  * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
9722  * @cfg {String} caret (search|calendar) a fontawesome for the trigger icon see http://fortawesome.github.io/Font-Awesome/icons/
9723
9724  * @constructor
9725  * Create a new TriggerField.
9726  * @param {Object} config Configuration options (valid {@Roo.bootstrap.Input} config options will also be applied
9727  * to the base TextField)
9728  */
9729 Roo.bootstrap.TriggerField = function(config){
9730     this.mimicing = false;
9731     Roo.bootstrap.TriggerField.superclass.constructor.call(this, config);
9732 };
9733
9734 Roo.extend(Roo.bootstrap.TriggerField, Roo.bootstrap.Input,  {
9735     /**
9736      * @cfg {String} triggerClass A CSS class to apply to the trigger
9737      */
9738      /**
9739      * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
9740      */
9741     hideTrigger:false,
9742
9743     /**
9744      * @cfg {Boolean} removable (true|false) special filter default false
9745      */
9746     removable : false,
9747     
9748     /** @cfg {Boolean} grow @hide */
9749     /** @cfg {Number} growMin @hide */
9750     /** @cfg {Number} growMax @hide */
9751
9752     /**
9753      * @hide 
9754      * @method
9755      */
9756     autoSize: Roo.emptyFn,
9757     // private
9758     monitorTab : true,
9759     // private
9760     deferHeight : true,
9761
9762     
9763     actionMode : 'wrap',
9764     
9765     caret : false,
9766     
9767     
9768     getAutoCreate : function(){
9769        
9770         var align = this.labelAlign || this.parentLabelAlign();
9771         
9772         var id = Roo.id();
9773         
9774         var cfg = {
9775             cls: 'form-group' //input-group
9776         };
9777         
9778         
9779         var input =  {
9780             tag: 'input',
9781             id : id,
9782             type : this.inputType,
9783             cls : 'form-control',
9784             autocomplete: 'new-password',
9785             placeholder : this.placeholder || '' 
9786             
9787         };
9788         if (this.name) {
9789             input.name = this.name;
9790         }
9791         if (this.size) {
9792             input.cls += ' input-' + this.size;
9793         }
9794         
9795         if (this.disabled) {
9796             input.disabled=true;
9797         }
9798         
9799         var inputblock = input;
9800         
9801         if(this.hasFeedback && !this.allowBlank){
9802             
9803             var feedback = {
9804                 tag: 'span',
9805                 cls: 'glyphicon form-control-feedback'
9806             };
9807             
9808             if(this.removable && !this.editable && !this.tickable){
9809                 inputblock = {
9810                     cls : 'has-feedback',
9811                     cn :  [
9812                         inputblock,
9813                         {
9814                             tag: 'button',
9815                             html : 'x',
9816                             cls : 'roo-combo-removable-btn close'
9817                         },
9818                         feedback
9819                     ] 
9820                 };
9821             } else {
9822                 inputblock = {
9823                     cls : 'has-feedback',
9824                     cn :  [
9825                         inputblock,
9826                         feedback
9827                     ] 
9828                 };
9829             }
9830
9831         } else {
9832             if(this.removable && !this.editable && !this.tickable){
9833                 inputblock = {
9834                     cls : 'roo-removable',
9835                     cn :  [
9836                         inputblock,
9837                         {
9838                             tag: 'button',
9839                             html : 'x',
9840                             cls : 'roo-combo-removable-btn close'
9841                         }
9842                     ] 
9843                 };
9844             }
9845         }
9846         
9847         if (this.before || this.after) {
9848             
9849             inputblock = {
9850                 cls : 'input-group',
9851                 cn :  [] 
9852             };
9853             if (this.before) {
9854                 inputblock.cn.push({
9855                     tag :'span',
9856                     cls : 'input-group-addon',
9857                     html : this.before
9858                 });
9859             }
9860             
9861             inputblock.cn.push(input);
9862             
9863             if(this.hasFeedback && !this.allowBlank){
9864                 inputblock.cls += ' has-feedback';
9865                 inputblock.cn.push(feedback);
9866             }
9867             
9868             if (this.after) {
9869                 inputblock.cn.push({
9870                     tag :'span',
9871                     cls : 'input-group-addon',
9872                     html : this.after
9873                 });
9874             }
9875             
9876         };
9877         
9878         var box = {
9879             tag: 'div',
9880             cn: [
9881                 {
9882                     tag: 'input',
9883                     type : 'hidden',
9884                     cls: 'form-hidden-field'
9885                 },
9886                 inputblock
9887             ]
9888             
9889         };
9890         
9891         if(this.multiple){
9892             box = {
9893                 tag: 'div',
9894                 cn: [
9895                     {
9896                         tag: 'input',
9897                         type : 'hidden',
9898                         cls: 'form-hidden-field'
9899                     },
9900                     {
9901                         tag: 'ul',
9902                         cls: 'roo-select2-choices',
9903                         cn:[
9904                             {
9905                                 tag: 'li',
9906                                 cls: 'roo-select2-search-field',
9907                                 cn: [
9908
9909                                     inputblock
9910                                 ]
9911                             }
9912                         ]
9913                     }
9914                 ]
9915             }
9916         };
9917         
9918         var combobox = {
9919             cls: 'roo-select2-container input-group',
9920             cn: [
9921                 box
9922 //                {
9923 //                    tag: 'ul',
9924 //                    cls: 'typeahead typeahead-long dropdown-menu',
9925 //                    style: 'display:none'
9926 //                }
9927             ]
9928         };
9929         
9930         if(!this.multiple && this.showToggleBtn){
9931             
9932             var caret = {
9933                         tag: 'span',
9934                         cls: 'caret'
9935              };
9936             if (this.caret != false) {
9937                 caret = {
9938                      tag: 'i',
9939                      cls: 'fa fa-' + this.caret
9940                 };
9941                 
9942             }
9943             
9944             combobox.cn.push({
9945                 tag :'span',
9946                 cls : 'input-group-addon btn dropdown-toggle',
9947                 cn : [
9948                     caret,
9949                     {
9950                         tag: 'span',
9951                         cls: 'combobox-clear',
9952                         cn  : [
9953                             {
9954                                 tag : 'i',
9955                                 cls: 'icon-remove'
9956                             }
9957                         ]
9958                     }
9959                 ]
9960
9961             })
9962         }
9963         
9964         if(this.multiple){
9965             combobox.cls += ' roo-select2-container-multi';
9966         }
9967         
9968         if (align ==='left' && this.fieldLabel.length) {
9969             
9970             cfg.cls += ' roo-form-group-label-left';
9971
9972             cfg.cn = [
9973                 {
9974                     tag : 'i',
9975                     cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
9976                     tooltip : 'This field is required'
9977                 },
9978                 {
9979                     tag: 'label',
9980                     'for' :  id,
9981                     cls : 'control-label',
9982                     html : this.fieldLabel
9983
9984                 },
9985                 {
9986                     cls : "", 
9987                     cn: [
9988                         combobox
9989                     ]
9990                 }
9991
9992             ];
9993             
9994             var labelCfg = cfg.cn[1];
9995             var contentCfg = cfg.cn[2];
9996             
9997             if(this.indicatorpos == 'right'){
9998                 cfg.cn = [
9999                     {
10000                         tag: 'label',
10001                         'for' :  id,
10002                         cls : 'control-label',
10003                         cn : [
10004                             {
10005                                 tag : 'span',
10006                                 html : this.fieldLabel
10007                             },
10008                             {
10009                                 tag : 'i',
10010                                 cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
10011                                 tooltip : 'This field is required'
10012                             }
10013                         ]
10014                     },
10015                     {
10016                         cls : "", 
10017                         cn: [
10018                             combobox
10019                         ]
10020                     }
10021
10022                 ];
10023                 
10024                 labelCfg = cfg.cn[0];
10025                 contentCfg = cfg.cn[1];
10026             }
10027             
10028             if(this.labelWidth > 12){
10029                 labelCfg.style = "width: " + this.labelWidth + 'px';
10030             }
10031             
10032             if(this.labelWidth < 13 && this.labelmd == 0){
10033                 this.labelmd = this.labelWidth;
10034             }
10035             
10036             if(this.labellg > 0){
10037                 labelCfg.cls += ' col-lg-' + this.labellg;
10038                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
10039             }
10040             
10041             if(this.labelmd > 0){
10042                 labelCfg.cls += ' col-md-' + this.labelmd;
10043                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
10044             }
10045             
10046             if(this.labelsm > 0){
10047                 labelCfg.cls += ' col-sm-' + this.labelsm;
10048                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
10049             }
10050             
10051             if(this.labelxs > 0){
10052                 labelCfg.cls += ' col-xs-' + this.labelxs;
10053                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
10054             }
10055             
10056         } else if ( this.fieldLabel.length) {
10057 //                Roo.log(" label");
10058             cfg.cn = [
10059                 {
10060                    tag : 'i',
10061                    cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
10062                    tooltip : 'This field is required'
10063                },
10064                {
10065                    tag: 'label',
10066                    //cls : 'input-group-addon',
10067                    html : this.fieldLabel
10068
10069                },
10070
10071                combobox
10072
10073             ];
10074             
10075             if(this.indicatorpos == 'right'){
10076                 
10077                 cfg.cn = [
10078                     {
10079                        tag: 'label',
10080                        cn : [
10081                            {
10082                                tag : 'span',
10083                                html : this.fieldLabel
10084                            },
10085                            {
10086                               tag : 'i',
10087                               cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
10088                               tooltip : 'This field is required'
10089                            }
10090                        ]
10091
10092                     },
10093                     combobox
10094
10095                 ];
10096
10097             }
10098
10099         } else {
10100             
10101 //                Roo.log(" no label && no align");
10102                 cfg = combobox
10103                      
10104                 
10105         }
10106         
10107         var settings=this;
10108         ['xs','sm','md','lg'].map(function(size){
10109             if (settings[size]) {
10110                 cfg.cls += ' col-' + size + '-' + settings[size];
10111             }
10112         });
10113         
10114         return cfg;
10115         
10116     },
10117     
10118     
10119     
10120     // private
10121     onResize : function(w, h){
10122 //        Roo.bootstrap.TriggerField.superclass.onResize.apply(this, arguments);
10123 //        if(typeof w == 'number'){
10124 //            var x = w - this.trigger.getWidth();
10125 //            this.inputEl().setWidth(this.adjustWidth('input', x));
10126 //            this.trigger.setStyle('left', x+'px');
10127 //        }
10128     },
10129
10130     // private
10131     adjustSize : Roo.BoxComponent.prototype.adjustSize,
10132
10133     // private
10134     getResizeEl : function(){
10135         return this.inputEl();
10136     },
10137
10138     // private
10139     getPositionEl : function(){
10140         return this.inputEl();
10141     },
10142
10143     // private
10144     alignErrorIcon : function(){
10145         this.errorIcon.alignTo(this.inputEl(), 'tl-tr', [2, 0]);
10146     },
10147
10148     // private
10149     initEvents : function(){
10150         
10151         this.createList();
10152         
10153         Roo.bootstrap.TriggerField.superclass.initEvents.call(this);
10154         //this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
10155         if(!this.multiple && this.showToggleBtn){
10156             this.trigger = this.el.select('span.dropdown-toggle',true).first();
10157             if(this.hideTrigger){
10158                 this.trigger.setDisplayed(false);
10159             }
10160             this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
10161         }
10162         
10163         if(this.multiple){
10164             this.inputEl().on("click", this.onTriggerClick, this, {preventDefault:true});
10165         }
10166         
10167         if(this.removable && !this.editable && !this.tickable){
10168             var close = this.closeTriggerEl();
10169             
10170             if(close){
10171                 close.setVisibilityMode(Roo.Element.DISPLAY).hide();
10172                 close.on('click', this.removeBtnClick, this, close);
10173             }
10174         }
10175         
10176         //this.trigger.addClassOnOver('x-form-trigger-over');
10177         //this.trigger.addClassOnClick('x-form-trigger-click');
10178         
10179         //if(!this.width){
10180         //    this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
10181         //}
10182     },
10183     
10184     closeTriggerEl : function()
10185     {
10186         var close = this.el.select('.roo-combo-removable-btn', true).first();
10187         return close ? close : false;
10188     },
10189     
10190     removeBtnClick : function(e, h, el)
10191     {
10192         e.preventDefault();
10193         
10194         if(this.fireEvent("remove", this) !== false){
10195             this.reset();
10196             this.fireEvent("afterremove", this)
10197         }
10198     },
10199     
10200     createList : function()
10201     {
10202         this.list = Roo.get(document.body).createChild({
10203             tag: 'ul',
10204             cls: 'typeahead typeahead-long dropdown-menu',
10205             style: 'display:none'
10206         });
10207         
10208         this.list.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';;
10209         
10210     },
10211
10212     // private
10213     initTrigger : function(){
10214        
10215     },
10216
10217     // private
10218     onDestroy : function(){
10219         if(this.trigger){
10220             this.trigger.removeAllListeners();
10221           //  this.trigger.remove();
10222         }
10223         //if(this.wrap){
10224         //    this.wrap.remove();
10225         //}
10226         Roo.bootstrap.TriggerField.superclass.onDestroy.call(this);
10227     },
10228
10229     // private
10230     onFocus : function(){
10231         Roo.bootstrap.TriggerField.superclass.onFocus.call(this);
10232         /*
10233         if(!this.mimicing){
10234             this.wrap.addClass('x-trigger-wrap-focus');
10235             this.mimicing = true;
10236             Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
10237             if(this.monitorTab){
10238                 this.el.on("keydown", this.checkTab, this);
10239             }
10240         }
10241         */
10242     },
10243
10244     // private
10245     checkTab : function(e){
10246         if(e.getKey() == e.TAB){
10247             this.triggerBlur();
10248         }
10249     },
10250
10251     // private
10252     onBlur : function(){
10253         // do nothing
10254     },
10255
10256     // private
10257     mimicBlur : function(e, t){
10258         /*
10259         if(!this.wrap.contains(t) && this.validateBlur()){
10260             this.triggerBlur();
10261         }
10262         */
10263     },
10264
10265     // private
10266     triggerBlur : function(){
10267         this.mimicing = false;
10268         Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
10269         if(this.monitorTab){
10270             this.el.un("keydown", this.checkTab, this);
10271         }
10272         //this.wrap.removeClass('x-trigger-wrap-focus');
10273         Roo.bootstrap.TriggerField.superclass.onBlur.call(this);
10274     },
10275
10276     // private
10277     // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
10278     validateBlur : function(e, t){
10279         return true;
10280     },
10281
10282     // private
10283     onDisable : function(){
10284         this.inputEl().dom.disabled = true;
10285         //Roo.bootstrap.TriggerField.superclass.onDisable.call(this);
10286         //if(this.wrap){
10287         //    this.wrap.addClass('x-item-disabled');
10288         //}
10289     },
10290
10291     // private
10292     onEnable : function(){
10293         this.inputEl().dom.disabled = false;
10294         //Roo.bootstrap.TriggerField.superclass.onEnable.call(this);
10295         //if(this.wrap){
10296         //    this.el.removeClass('x-item-disabled');
10297         //}
10298     },
10299
10300     // private
10301     onShow : function(){
10302         var ae = this.getActionEl();
10303         
10304         if(ae){
10305             ae.dom.style.display = '';
10306             ae.dom.style.visibility = 'visible';
10307         }
10308     },
10309
10310     // private
10311     
10312     onHide : function(){
10313         var ae = this.getActionEl();
10314         ae.dom.style.display = 'none';
10315     },
10316
10317     /**
10318      * The function that should handle the trigger's click event.  This method does nothing by default until overridden
10319      * by an implementing function.
10320      * @method
10321      * @param {EventObject} e
10322      */
10323     onTriggerClick : Roo.emptyFn
10324 });
10325  /*
10326  * Based on:
10327  * Ext JS Library 1.1.1
10328  * Copyright(c) 2006-2007, Ext JS, LLC.
10329  *
10330  * Originally Released Under LGPL - original licence link has changed is not relivant.
10331  *
10332  * Fork - LGPL
10333  * <script type="text/javascript">
10334  */
10335
10336
10337 /**
10338  * @class Roo.data.SortTypes
10339  * @singleton
10340  * Defines the default sorting (casting?) comparison functions used when sorting data.
10341  */
10342 Roo.data.SortTypes = {
10343     /**
10344      * Default sort that does nothing
10345      * @param {Mixed} s The value being converted
10346      * @return {Mixed} The comparison value
10347      */
10348     none : function(s){
10349         return s;
10350     },
10351     
10352     /**
10353      * The regular expression used to strip tags
10354      * @type {RegExp}
10355      * @property
10356      */
10357     stripTagsRE : /<\/?[^>]+>/gi,
10358     
10359     /**
10360      * Strips all HTML tags to sort on text only
10361      * @param {Mixed} s The value being converted
10362      * @return {String} The comparison value
10363      */
10364     asText : function(s){
10365         return String(s).replace(this.stripTagsRE, "");
10366     },
10367     
10368     /**
10369      * Strips all HTML tags to sort on text only - Case insensitive
10370      * @param {Mixed} s The value being converted
10371      * @return {String} The comparison value
10372      */
10373     asUCText : function(s){
10374         return String(s).toUpperCase().replace(this.stripTagsRE, "");
10375     },
10376     
10377     /**
10378      * Case insensitive string
10379      * @param {Mixed} s The value being converted
10380      * @return {String} The comparison value
10381      */
10382     asUCString : function(s) {
10383         return String(s).toUpperCase();
10384     },
10385     
10386     /**
10387      * Date sorting
10388      * @param {Mixed} s The value being converted
10389      * @return {Number} The comparison value
10390      */
10391     asDate : function(s) {
10392         if(!s){
10393             return 0;
10394         }
10395         if(s instanceof Date){
10396             return s.getTime();
10397         }
10398         return Date.parse(String(s));
10399     },
10400     
10401     /**
10402      * Float sorting
10403      * @param {Mixed} s The value being converted
10404      * @return {Float} The comparison value
10405      */
10406     asFloat : function(s) {
10407         var val = parseFloat(String(s).replace(/,/g, ""));
10408         if(isNaN(val)) {
10409             val = 0;
10410         }
10411         return val;
10412     },
10413     
10414     /**
10415      * Integer sorting
10416      * @param {Mixed} s The value being converted
10417      * @return {Number} The comparison value
10418      */
10419     asInt : function(s) {
10420         var val = parseInt(String(s).replace(/,/g, ""));
10421         if(isNaN(val)) {
10422             val = 0;
10423         }
10424         return val;
10425     }
10426 };/*
10427  * Based on:
10428  * Ext JS Library 1.1.1
10429  * Copyright(c) 2006-2007, Ext JS, LLC.
10430  *
10431  * Originally Released Under LGPL - original licence link has changed is not relivant.
10432  *
10433  * Fork - LGPL
10434  * <script type="text/javascript">
10435  */
10436
10437 /**
10438 * @class Roo.data.Record
10439  * Instances of this class encapsulate both record <em>definition</em> information, and record
10440  * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
10441  * to access Records cached in an {@link Roo.data.Store} object.<br>
10442  * <p>
10443  * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
10444  * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
10445  * objects.<br>
10446  * <p>
10447  * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
10448  * @constructor
10449  * This constructor should not be used to create Record objects. Instead, use the constructor generated by
10450  * {@link #create}. The parameters are the same.
10451  * @param {Array} data An associative Array of data values keyed by the field name.
10452  * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
10453  * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
10454  * not specified an integer id is generated.
10455  */
10456 Roo.data.Record = function(data, id){
10457     this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
10458     this.data = data;
10459 };
10460
10461 /**
10462  * Generate a constructor for a specific record layout.
10463  * @param {Array} o An Array of field definition objects which specify field names, and optionally,
10464  * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
10465  * Each field definition object may contain the following properties: <ul>
10466  * <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,
10467  * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
10468  * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
10469  * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
10470  * is being used, then this is a string containing the javascript expression to reference the data relative to 
10471  * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
10472  * to the data item relative to the record element. If the mapping expression is the same as the field name,
10473  * this may be omitted.</p></li>
10474  * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
10475  * <ul><li>auto (Default, implies no conversion)</li>
10476  * <li>string</li>
10477  * <li>int</li>
10478  * <li>float</li>
10479  * <li>boolean</li>
10480  * <li>date</li></ul></p></li>
10481  * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
10482  * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
10483  * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
10484  * by the Reader into an object that will be stored in the Record. It is passed the
10485  * following parameters:<ul>
10486  * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
10487  * </ul></p></li>
10488  * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
10489  * </ul>
10490  * <br>usage:<br><pre><code>
10491 var TopicRecord = Roo.data.Record.create(
10492     {name: 'title', mapping: 'topic_title'},
10493     {name: 'author', mapping: 'username'},
10494     {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
10495     {name: 'lastPost', mapping: 'post_time', type: 'date'},
10496     {name: 'lastPoster', mapping: 'user2'},
10497     {name: 'excerpt', mapping: 'post_text'}
10498 );
10499
10500 var myNewRecord = new TopicRecord({
10501     title: 'Do my job please',
10502     author: 'noobie',
10503     totalPosts: 1,
10504     lastPost: new Date(),
10505     lastPoster: 'Animal',
10506     excerpt: 'No way dude!'
10507 });
10508 myStore.add(myNewRecord);
10509 </code></pre>
10510  * @method create
10511  * @static
10512  */
10513 Roo.data.Record.create = function(o){
10514     var f = function(){
10515         f.superclass.constructor.apply(this, arguments);
10516     };
10517     Roo.extend(f, Roo.data.Record);
10518     var p = f.prototype;
10519     p.fields = new Roo.util.MixedCollection(false, function(field){
10520         return field.name;
10521     });
10522     for(var i = 0, len = o.length; i < len; i++){
10523         p.fields.add(new Roo.data.Field(o[i]));
10524     }
10525     f.getField = function(name){
10526         return p.fields.get(name);  
10527     };
10528     return f;
10529 };
10530
10531 Roo.data.Record.AUTO_ID = 1000;
10532 Roo.data.Record.EDIT = 'edit';
10533 Roo.data.Record.REJECT = 'reject';
10534 Roo.data.Record.COMMIT = 'commit';
10535
10536 Roo.data.Record.prototype = {
10537     /**
10538      * Readonly flag - true if this record has been modified.
10539      * @type Boolean
10540      */
10541     dirty : false,
10542     editing : false,
10543     error: null,
10544     modified: null,
10545
10546     // private
10547     join : function(store){
10548         this.store = store;
10549     },
10550
10551     /**
10552      * Set the named field to the specified value.
10553      * @param {String} name The name of the field to set.
10554      * @param {Object} value The value to set the field to.
10555      */
10556     set : function(name, value){
10557         if(this.data[name] == value){
10558             return;
10559         }
10560         this.dirty = true;
10561         if(!this.modified){
10562             this.modified = {};
10563         }
10564         if(typeof this.modified[name] == 'undefined'){
10565             this.modified[name] = this.data[name];
10566         }
10567         this.data[name] = value;
10568         if(!this.editing && this.store){
10569             this.store.afterEdit(this);
10570         }       
10571     },
10572
10573     /**
10574      * Get the value of the named field.
10575      * @param {String} name The name of the field to get the value of.
10576      * @return {Object} The value of the field.
10577      */
10578     get : function(name){
10579         return this.data[name]; 
10580     },
10581
10582     // private
10583     beginEdit : function(){
10584         this.editing = true;
10585         this.modified = {}; 
10586     },
10587
10588     // private
10589     cancelEdit : function(){
10590         this.editing = false;
10591         delete this.modified;
10592     },
10593
10594     // private
10595     endEdit : function(){
10596         this.editing = false;
10597         if(this.dirty && this.store){
10598             this.store.afterEdit(this);
10599         }
10600     },
10601
10602     /**
10603      * Usually called by the {@link Roo.data.Store} which owns the Record.
10604      * Rejects all changes made to the Record since either creation, or the last commit operation.
10605      * Modified fields are reverted to their original values.
10606      * <p>
10607      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
10608      * of reject operations.
10609      */
10610     reject : function(){
10611         var m = this.modified;
10612         for(var n in m){
10613             if(typeof m[n] != "function"){
10614                 this.data[n] = m[n];
10615             }
10616         }
10617         this.dirty = false;
10618         delete this.modified;
10619         this.editing = false;
10620         if(this.store){
10621             this.store.afterReject(this);
10622         }
10623     },
10624
10625     /**
10626      * Usually called by the {@link Roo.data.Store} which owns the Record.
10627      * Commits all changes made to the Record since either creation, or the last commit operation.
10628      * <p>
10629      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
10630      * of commit operations.
10631      */
10632     commit : function(){
10633         this.dirty = false;
10634         delete this.modified;
10635         this.editing = false;
10636         if(this.store){
10637             this.store.afterCommit(this);
10638         }
10639     },
10640
10641     // private
10642     hasError : function(){
10643         return this.error != null;
10644     },
10645
10646     // private
10647     clearError : function(){
10648         this.error = null;
10649     },
10650
10651     /**
10652      * Creates a copy of this record.
10653      * @param {String} id (optional) A new record id if you don't want to use this record's id
10654      * @return {Record}
10655      */
10656     copy : function(newId) {
10657         return new this.constructor(Roo.apply({}, this.data), newId || this.id);
10658     }
10659 };/*
10660  * Based on:
10661  * Ext JS Library 1.1.1
10662  * Copyright(c) 2006-2007, Ext JS, LLC.
10663  *
10664  * Originally Released Under LGPL - original licence link has changed is not relivant.
10665  *
10666  * Fork - LGPL
10667  * <script type="text/javascript">
10668  */
10669
10670
10671
10672 /**
10673  * @class Roo.data.Store
10674  * @extends Roo.util.Observable
10675  * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
10676  * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
10677  * <p>
10678  * 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
10679  * has no knowledge of the format of the data returned by the Proxy.<br>
10680  * <p>
10681  * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
10682  * instances from the data object. These records are cached and made available through accessor functions.
10683  * @constructor
10684  * Creates a new Store.
10685  * @param {Object} config A config object containing the objects needed for the Store to access data,
10686  * and read the data into Records.
10687  */
10688 Roo.data.Store = function(config){
10689     this.data = new Roo.util.MixedCollection(false);
10690     this.data.getKey = function(o){
10691         return o.id;
10692     };
10693     this.baseParams = {};
10694     // private
10695     this.paramNames = {
10696         "start" : "start",
10697         "limit" : "limit",
10698         "sort" : "sort",
10699         "dir" : "dir",
10700         "multisort" : "_multisort"
10701     };
10702
10703     if(config && config.data){
10704         this.inlineData = config.data;
10705         delete config.data;
10706     }
10707
10708     Roo.apply(this, config);
10709     
10710     if(this.reader){ // reader passed
10711         this.reader = Roo.factory(this.reader, Roo.data);
10712         this.reader.xmodule = this.xmodule || false;
10713         if(!this.recordType){
10714             this.recordType = this.reader.recordType;
10715         }
10716         if(this.reader.onMetaChange){
10717             this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
10718         }
10719     }
10720
10721     if(this.recordType){
10722         this.fields = this.recordType.prototype.fields;
10723     }
10724     this.modified = [];
10725
10726     this.addEvents({
10727         /**
10728          * @event datachanged
10729          * Fires when the data cache has changed, and a widget which is using this Store
10730          * as a Record cache should refresh its view.
10731          * @param {Store} this
10732          */
10733         datachanged : true,
10734         /**
10735          * @event metachange
10736          * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
10737          * @param {Store} this
10738          * @param {Object} meta The JSON metadata
10739          */
10740         metachange : true,
10741         /**
10742          * @event add
10743          * Fires when Records have been added to the Store
10744          * @param {Store} this
10745          * @param {Roo.data.Record[]} records The array of Records added
10746          * @param {Number} index The index at which the record(s) were added
10747          */
10748         add : true,
10749         /**
10750          * @event remove
10751          * Fires when a Record has been removed from the Store
10752          * @param {Store} this
10753          * @param {Roo.data.Record} record The Record that was removed
10754          * @param {Number} index The index at which the record was removed
10755          */
10756         remove : true,
10757         /**
10758          * @event update
10759          * Fires when a Record has been updated
10760          * @param {Store} this
10761          * @param {Roo.data.Record} record The Record that was updated
10762          * @param {String} operation The update operation being performed.  Value may be one of:
10763          * <pre><code>
10764  Roo.data.Record.EDIT
10765  Roo.data.Record.REJECT
10766  Roo.data.Record.COMMIT
10767          * </code></pre>
10768          */
10769         update : true,
10770         /**
10771          * @event clear
10772          * Fires when the data cache has been cleared.
10773          * @param {Store} this
10774          */
10775         clear : true,
10776         /**
10777          * @event beforeload
10778          * Fires before a request is made for a new data object.  If the beforeload handler returns false
10779          * the load action will be canceled.
10780          * @param {Store} this
10781          * @param {Object} options The loading options that were specified (see {@link #load} for details)
10782          */
10783         beforeload : true,
10784         /**
10785          * @event beforeloadadd
10786          * Fires after a new set of Records has been loaded.
10787          * @param {Store} this
10788          * @param {Roo.data.Record[]} records The Records that were loaded
10789          * @param {Object} options The loading options that were specified (see {@link #load} for details)
10790          */
10791         beforeloadadd : true,
10792         /**
10793          * @event load
10794          * Fires after a new set of Records has been loaded, before they are added to the store.
10795          * @param {Store} this
10796          * @param {Roo.data.Record[]} records The Records that were loaded
10797          * @param {Object} options The loading options that were specified (see {@link #load} for details)
10798          * @params {Object} return from reader
10799          */
10800         load : true,
10801         /**
10802          * @event loadexception
10803          * Fires if an exception occurs in the Proxy during loading.
10804          * Called with the signature of the Proxy's "loadexception" event.
10805          * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
10806          * 
10807          * @param {Proxy} 
10808          * @param {Object} return from JsonData.reader() - success, totalRecords, records
10809          * @param {Object} load options 
10810          * @param {Object} jsonData from your request (normally this contains the Exception)
10811          */
10812         loadexception : true
10813     });
10814     
10815     if(this.proxy){
10816         this.proxy = Roo.factory(this.proxy, Roo.data);
10817         this.proxy.xmodule = this.xmodule || false;
10818         this.relayEvents(this.proxy,  ["loadexception"]);
10819     }
10820     this.sortToggle = {};
10821     this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
10822
10823     Roo.data.Store.superclass.constructor.call(this);
10824
10825     if(this.inlineData){
10826         this.loadData(this.inlineData);
10827         delete this.inlineData;
10828     }
10829 };
10830
10831 Roo.extend(Roo.data.Store, Roo.util.Observable, {
10832      /**
10833     * @cfg {boolean} isLocal   flag if data is locally available (and can be always looked up
10834     * without a remote query - used by combo/forms at present.
10835     */
10836     
10837     /**
10838     * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
10839     */
10840     /**
10841     * @cfg {Array} data Inline data to be loaded when the store is initialized.
10842     */
10843     /**
10844     * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
10845     * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
10846     */
10847     /**
10848     * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
10849     * on any HTTP request
10850     */
10851     /**
10852     * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
10853     */
10854     /**
10855     * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
10856     */
10857     multiSort: false,
10858     /**
10859     * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
10860     * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
10861     */
10862     remoteSort : false,
10863
10864     /**
10865     * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
10866      * loaded or when a record is removed. (defaults to false).
10867     */
10868     pruneModifiedRecords : false,
10869
10870     // private
10871     lastOptions : null,
10872
10873     /**
10874      * Add Records to the Store and fires the add event.
10875      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
10876      */
10877     add : function(records){
10878         records = [].concat(records);
10879         for(var i = 0, len = records.length; i < len; i++){
10880             records[i].join(this);
10881         }
10882         var index = this.data.length;
10883         this.data.addAll(records);
10884         this.fireEvent("add", this, records, index);
10885     },
10886
10887     /**
10888      * Remove a Record from the Store and fires the remove event.
10889      * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
10890      */
10891     remove : function(record){
10892         var index = this.data.indexOf(record);
10893         this.data.removeAt(index);
10894         if(this.pruneModifiedRecords){
10895             this.modified.remove(record);
10896         }
10897         this.fireEvent("remove", this, record, index);
10898     },
10899
10900     /**
10901      * Remove all Records from the Store and fires the clear event.
10902      */
10903     removeAll : function(){
10904         this.data.clear();
10905         if(this.pruneModifiedRecords){
10906             this.modified = [];
10907         }
10908         this.fireEvent("clear", this);
10909     },
10910
10911     /**
10912      * Inserts Records to the Store at the given index and fires the add event.
10913      * @param {Number} index The start index at which to insert the passed Records.
10914      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
10915      */
10916     insert : function(index, records){
10917         records = [].concat(records);
10918         for(var i = 0, len = records.length; i < len; i++){
10919             this.data.insert(index, records[i]);
10920             records[i].join(this);
10921         }
10922         this.fireEvent("add", this, records, index);
10923     },
10924
10925     /**
10926      * Get the index within the cache of the passed Record.
10927      * @param {Roo.data.Record} record The Roo.data.Record object to to find.
10928      * @return {Number} The index of the passed Record. Returns -1 if not found.
10929      */
10930     indexOf : function(record){
10931         return this.data.indexOf(record);
10932     },
10933
10934     /**
10935      * Get the index within the cache of the Record with the passed id.
10936      * @param {String} id The id of the Record to find.
10937      * @return {Number} The index of the Record. Returns -1 if not found.
10938      */
10939     indexOfId : function(id){
10940         return this.data.indexOfKey(id);
10941     },
10942
10943     /**
10944      * Get the Record with the specified id.
10945      * @param {String} id The id of the Record to find.
10946      * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
10947      */
10948     getById : function(id){
10949         return this.data.key(id);
10950     },
10951
10952     /**
10953      * Get the Record at the specified index.
10954      * @param {Number} index The index of the Record to find.
10955      * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
10956      */
10957     getAt : function(index){
10958         return this.data.itemAt(index);
10959     },
10960
10961     /**
10962      * Returns a range of Records between specified indices.
10963      * @param {Number} startIndex (optional) The starting index (defaults to 0)
10964      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
10965      * @return {Roo.data.Record[]} An array of Records
10966      */
10967     getRange : function(start, end){
10968         return this.data.getRange(start, end);
10969     },
10970
10971     // private
10972     storeOptions : function(o){
10973         o = Roo.apply({}, o);
10974         delete o.callback;
10975         delete o.scope;
10976         this.lastOptions = o;
10977     },
10978
10979     /**
10980      * Loads the Record cache from the configured Proxy using the configured Reader.
10981      * <p>
10982      * If using remote paging, then the first load call must specify the <em>start</em>
10983      * and <em>limit</em> properties in the options.params property to establish the initial
10984      * position within the dataset, and the number of Records to cache on each read from the Proxy.
10985      * <p>
10986      * <strong>It is important to note that for remote data sources, loading is asynchronous,
10987      * and this call will return before the new data has been loaded. Perform any post-processing
10988      * in a callback function, or in a "load" event handler.</strong>
10989      * <p>
10990      * @param {Object} options An object containing properties which control loading options:<ul>
10991      * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
10992      * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
10993      * passed the following arguments:<ul>
10994      * <li>r : Roo.data.Record[]</li>
10995      * <li>options: Options object from the load call</li>
10996      * <li>success: Boolean success indicator</li></ul></li>
10997      * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
10998      * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
10999      * </ul>
11000      */
11001     load : function(options){
11002         options = options || {};
11003         if(this.fireEvent("beforeload", this, options) !== false){
11004             this.storeOptions(options);
11005             var p = Roo.apply(options.params || {}, this.baseParams);
11006             // if meta was not loaded from remote source.. try requesting it.
11007             if (!this.reader.metaFromRemote) {
11008                 p._requestMeta = 1;
11009             }
11010             if(this.sortInfo && this.remoteSort){
11011                 var pn = this.paramNames;
11012                 p[pn["sort"]] = this.sortInfo.field;
11013                 p[pn["dir"]] = this.sortInfo.direction;
11014             }
11015             if (this.multiSort) {
11016                 var pn = this.paramNames;
11017                 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
11018             }
11019             
11020             this.proxy.load(p, this.reader, this.loadRecords, this, options);
11021         }
11022     },
11023
11024     /**
11025      * Reloads the Record cache from the configured Proxy using the configured Reader and
11026      * the options from the last load operation performed.
11027      * @param {Object} options (optional) An object containing properties which may override the options
11028      * used in the last load operation. See {@link #load} for details (defaults to null, in which case
11029      * the most recently used options are reused).
11030      */
11031     reload : function(options){
11032         this.load(Roo.applyIf(options||{}, this.lastOptions));
11033     },
11034
11035     // private
11036     // Called as a callback by the Reader during a load operation.
11037     loadRecords : function(o, options, success){
11038         if(!o || success === false){
11039             if(success !== false){
11040                 this.fireEvent("load", this, [], options, o);
11041             }
11042             if(options.callback){
11043                 options.callback.call(options.scope || this, [], options, false);
11044             }
11045             return;
11046         }
11047         // if data returned failure - throw an exception.
11048         if (o.success === false) {
11049             // show a message if no listener is registered.
11050             if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
11051                     Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
11052             }
11053             // loadmask wil be hooked into this..
11054             this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
11055             return;
11056         }
11057         var r = o.records, t = o.totalRecords || r.length;
11058         
11059         this.fireEvent("beforeloadadd", this, r, options, o);
11060         
11061         if(!options || options.add !== true){
11062             if(this.pruneModifiedRecords){
11063                 this.modified = [];
11064             }
11065             for(var i = 0, len = r.length; i < len; i++){
11066                 r[i].join(this);
11067             }
11068             if(this.snapshot){
11069                 this.data = this.snapshot;
11070                 delete this.snapshot;
11071             }
11072             this.data.clear();
11073             this.data.addAll(r);
11074             this.totalLength = t;
11075             this.applySort();
11076             this.fireEvent("datachanged", this);
11077         }else{
11078             this.totalLength = Math.max(t, this.data.length+r.length);
11079             this.add(r);
11080         }
11081         
11082         if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
11083                 
11084             var e = new Roo.data.Record({});
11085
11086             e.set(this.parent.displayField, this.parent.emptyTitle);
11087             e.set(this.parent.valueField, '');
11088
11089             this.insert(0, e);
11090         }
11091             
11092         this.fireEvent("load", this, r, options, o);
11093         if(options.callback){
11094             options.callback.call(options.scope || this, r, options, true);
11095         }
11096     },
11097
11098
11099     /**
11100      * Loads data from a passed data block. A Reader which understands the format of the data
11101      * must have been configured in the constructor.
11102      * @param {Object} data The data block from which to read the Records.  The format of the data expected
11103      * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
11104      * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
11105      */
11106     loadData : function(o, append){
11107         var r = this.reader.readRecords(o);
11108         this.loadRecords(r, {add: append}, true);
11109     },
11110
11111     /**
11112      * Gets the number of cached records.
11113      * <p>
11114      * <em>If using paging, this may not be the total size of the dataset. If the data object
11115      * used by the Reader contains the dataset size, then the getTotalCount() function returns
11116      * the data set size</em>
11117      */
11118     getCount : function(){
11119         return this.data.length || 0;
11120     },
11121
11122     /**
11123      * Gets the total number of records in the dataset as returned by the server.
11124      * <p>
11125      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
11126      * the dataset size</em>
11127      */
11128     getTotalCount : function(){
11129         return this.totalLength || 0;
11130     },
11131
11132     /**
11133      * Returns the sort state of the Store as an object with two properties:
11134      * <pre><code>
11135  field {String} The name of the field by which the Records are sorted
11136  direction {String} The sort order, "ASC" or "DESC"
11137      * </code></pre>
11138      */
11139     getSortState : function(){
11140         return this.sortInfo;
11141     },
11142
11143     // private
11144     applySort : function(){
11145         if(this.sortInfo && !this.remoteSort){
11146             var s = this.sortInfo, f = s.field;
11147             var st = this.fields.get(f).sortType;
11148             var fn = function(r1, r2){
11149                 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
11150                 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
11151             };
11152             this.data.sort(s.direction, fn);
11153             if(this.snapshot && this.snapshot != this.data){
11154                 this.snapshot.sort(s.direction, fn);
11155             }
11156         }
11157     },
11158
11159     /**
11160      * Sets the default sort column and order to be used by the next load operation.
11161      * @param {String} fieldName The name of the field to sort by.
11162      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
11163      */
11164     setDefaultSort : function(field, dir){
11165         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
11166     },
11167
11168     /**
11169      * Sort the Records.
11170      * If remote sorting is used, the sort is performed on the server, and the cache is
11171      * reloaded. If local sorting is used, the cache is sorted internally.
11172      * @param {String} fieldName The name of the field to sort by.
11173      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
11174      */
11175     sort : function(fieldName, dir){
11176         var f = this.fields.get(fieldName);
11177         if(!dir){
11178             this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
11179             
11180             if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
11181                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
11182             }else{
11183                 dir = f.sortDir;
11184             }
11185         }
11186         this.sortToggle[f.name] = dir;
11187         this.sortInfo = {field: f.name, direction: dir};
11188         if(!this.remoteSort){
11189             this.applySort();
11190             this.fireEvent("datachanged", this);
11191         }else{
11192             this.load(this.lastOptions);
11193         }
11194     },
11195
11196     /**
11197      * Calls the specified function for each of the Records in the cache.
11198      * @param {Function} fn The function to call. The Record is passed as the first parameter.
11199      * Returning <em>false</em> aborts and exits the iteration.
11200      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
11201      */
11202     each : function(fn, scope){
11203         this.data.each(fn, scope);
11204     },
11205
11206     /**
11207      * Gets all records modified since the last commit.  Modified records are persisted across load operations
11208      * (e.g., during paging).
11209      * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
11210      */
11211     getModifiedRecords : function(){
11212         return this.modified;
11213     },
11214
11215     // private
11216     createFilterFn : function(property, value, anyMatch){
11217         if(!value.exec){ // not a regex
11218             value = String(value);
11219             if(value.length == 0){
11220                 return false;
11221             }
11222             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
11223         }
11224         return function(r){
11225             return value.test(r.data[property]);
11226         };
11227     },
11228
11229     /**
11230      * Sums the value of <i>property</i> for each record between start and end and returns the result.
11231      * @param {String} property A field on your records
11232      * @param {Number} start The record index to start at (defaults to 0)
11233      * @param {Number} end The last record index to include (defaults to length - 1)
11234      * @return {Number} The sum
11235      */
11236     sum : function(property, start, end){
11237         var rs = this.data.items, v = 0;
11238         start = start || 0;
11239         end = (end || end === 0) ? end : rs.length-1;
11240
11241         for(var i = start; i <= end; i++){
11242             v += (rs[i].data[property] || 0);
11243         }
11244         return v;
11245     },
11246
11247     /**
11248      * Filter the records by a specified property.
11249      * @param {String} field A field on your records
11250      * @param {String/RegExp} value Either a string that the field
11251      * should start with or a RegExp to test against the field
11252      * @param {Boolean} anyMatch True to match any part not just the beginning
11253      */
11254     filter : function(property, value, anyMatch){
11255         var fn = this.createFilterFn(property, value, anyMatch);
11256         return fn ? this.filterBy(fn) : this.clearFilter();
11257     },
11258
11259     /**
11260      * Filter by a function. The specified function will be called with each
11261      * record in this data source. If the function returns true the record is included,
11262      * otherwise it is filtered.
11263      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
11264      * @param {Object} scope (optional) The scope of the function (defaults to this)
11265      */
11266     filterBy : function(fn, scope){
11267         this.snapshot = this.snapshot || this.data;
11268         this.data = this.queryBy(fn, scope||this);
11269         this.fireEvent("datachanged", this);
11270     },
11271
11272     /**
11273      * Query the records by a specified property.
11274      * @param {String} field A field on your records
11275      * @param {String/RegExp} value Either a string that the field
11276      * should start with or a RegExp to test against the field
11277      * @param {Boolean} anyMatch True to match any part not just the beginning
11278      * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
11279      */
11280     query : function(property, value, anyMatch){
11281         var fn = this.createFilterFn(property, value, anyMatch);
11282         return fn ? this.queryBy(fn) : this.data.clone();
11283     },
11284
11285     /**
11286      * Query by a function. The specified function will be called with each
11287      * record in this data source. If the function returns true the record is included
11288      * in the results.
11289      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
11290      * @param {Object} scope (optional) The scope of the function (defaults to this)
11291       @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
11292      **/
11293     queryBy : function(fn, scope){
11294         var data = this.snapshot || this.data;
11295         return data.filterBy(fn, scope||this);
11296     },
11297
11298     /**
11299      * Collects unique values for a particular dataIndex from this store.
11300      * @param {String} dataIndex The property to collect
11301      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
11302      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
11303      * @return {Array} An array of the unique values
11304      **/
11305     collect : function(dataIndex, allowNull, bypassFilter){
11306         var d = (bypassFilter === true && this.snapshot) ?
11307                 this.snapshot.items : this.data.items;
11308         var v, sv, r = [], l = {};
11309         for(var i = 0, len = d.length; i < len; i++){
11310             v = d[i].data[dataIndex];
11311             sv = String(v);
11312             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
11313                 l[sv] = true;
11314                 r[r.length] = v;
11315             }
11316         }
11317         return r;
11318     },
11319
11320     /**
11321      * Revert to a view of the Record cache with no filtering applied.
11322      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
11323      */
11324     clearFilter : function(suppressEvent){
11325         if(this.snapshot && this.snapshot != this.data){
11326             this.data = this.snapshot;
11327             delete this.snapshot;
11328             if(suppressEvent !== true){
11329                 this.fireEvent("datachanged", this);
11330             }
11331         }
11332     },
11333
11334     // private
11335     afterEdit : function(record){
11336         if(this.modified.indexOf(record) == -1){
11337             this.modified.push(record);
11338         }
11339         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
11340     },
11341     
11342     // private
11343     afterReject : function(record){
11344         this.modified.remove(record);
11345         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
11346     },
11347
11348     // private
11349     afterCommit : function(record){
11350         this.modified.remove(record);
11351         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
11352     },
11353
11354     /**
11355      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
11356      * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
11357      */
11358     commitChanges : function(){
11359         var m = this.modified.slice(0);
11360         this.modified = [];
11361         for(var i = 0, len = m.length; i < len; i++){
11362             m[i].commit();
11363         }
11364     },
11365
11366     /**
11367      * Cancel outstanding changes on all changed records.
11368      */
11369     rejectChanges : function(){
11370         var m = this.modified.slice(0);
11371         this.modified = [];
11372         for(var i = 0, len = m.length; i < len; i++){
11373             m[i].reject();
11374         }
11375     },
11376
11377     onMetaChange : function(meta, rtype, o){
11378         this.recordType = rtype;
11379         this.fields = rtype.prototype.fields;
11380         delete this.snapshot;
11381         this.sortInfo = meta.sortInfo || this.sortInfo;
11382         this.modified = [];
11383         this.fireEvent('metachange', this, this.reader.meta);
11384     },
11385     
11386     moveIndex : function(data, type)
11387     {
11388         var index = this.indexOf(data);
11389         
11390         var newIndex = index + type;
11391         
11392         this.remove(data);
11393         
11394         this.insert(newIndex, data);
11395         
11396     }
11397 });/*
11398  * Based on:
11399  * Ext JS Library 1.1.1
11400  * Copyright(c) 2006-2007, Ext JS, LLC.
11401  *
11402  * Originally Released Under LGPL - original licence link has changed is not relivant.
11403  *
11404  * Fork - LGPL
11405  * <script type="text/javascript">
11406  */
11407
11408 /**
11409  * @class Roo.data.SimpleStore
11410  * @extends Roo.data.Store
11411  * Small helper class to make creating Stores from Array data easier.
11412  * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
11413  * @cfg {Array} fields An array of field definition objects, or field name strings.
11414  * @cfg {Array} data The multi-dimensional array of data
11415  * @constructor
11416  * @param {Object} config
11417  */
11418 Roo.data.SimpleStore = function(config){
11419     Roo.data.SimpleStore.superclass.constructor.call(this, {
11420         isLocal : true,
11421         reader: new Roo.data.ArrayReader({
11422                 id: config.id
11423             },
11424             Roo.data.Record.create(config.fields)
11425         ),
11426         proxy : new Roo.data.MemoryProxy(config.data)
11427     });
11428     this.load();
11429 };
11430 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
11431  * Based on:
11432  * Ext JS Library 1.1.1
11433  * Copyright(c) 2006-2007, Ext JS, LLC.
11434  *
11435  * Originally Released Under LGPL - original licence link has changed is not relivant.
11436  *
11437  * Fork - LGPL
11438  * <script type="text/javascript">
11439  */
11440
11441 /**
11442 /**
11443  * @extends Roo.data.Store
11444  * @class Roo.data.JsonStore
11445  * Small helper class to make creating Stores for JSON data easier. <br/>
11446 <pre><code>
11447 var store = new Roo.data.JsonStore({
11448     url: 'get-images.php',
11449     root: 'images',
11450     fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
11451 });
11452 </code></pre>
11453  * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
11454  * JsonReader and HttpProxy (unless inline data is provided).</b>
11455  * @cfg {Array} fields An array of field definition objects, or field name strings.
11456  * @constructor
11457  * @param {Object} config
11458  */
11459 Roo.data.JsonStore = function(c){
11460     Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
11461         proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
11462         reader: new Roo.data.JsonReader(c, c.fields)
11463     }));
11464 };
11465 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
11466  * Based on:
11467  * Ext JS Library 1.1.1
11468  * Copyright(c) 2006-2007, Ext JS, LLC.
11469  *
11470  * Originally Released Under LGPL - original licence link has changed is not relivant.
11471  *
11472  * Fork - LGPL
11473  * <script type="text/javascript">
11474  */
11475
11476  
11477 Roo.data.Field = function(config){
11478     if(typeof config == "string"){
11479         config = {name: config};
11480     }
11481     Roo.apply(this, config);
11482     
11483     if(!this.type){
11484         this.type = "auto";
11485     }
11486     
11487     var st = Roo.data.SortTypes;
11488     // named sortTypes are supported, here we look them up
11489     if(typeof this.sortType == "string"){
11490         this.sortType = st[this.sortType];
11491     }
11492     
11493     // set default sortType for strings and dates
11494     if(!this.sortType){
11495         switch(this.type){
11496             case "string":
11497                 this.sortType = st.asUCString;
11498                 break;
11499             case "date":
11500                 this.sortType = st.asDate;
11501                 break;
11502             default:
11503                 this.sortType = st.none;
11504         }
11505     }
11506
11507     // define once
11508     var stripRe = /[\$,%]/g;
11509
11510     // prebuilt conversion function for this field, instead of
11511     // switching every time we're reading a value
11512     if(!this.convert){
11513         var cv, dateFormat = this.dateFormat;
11514         switch(this.type){
11515             case "":
11516             case "auto":
11517             case undefined:
11518                 cv = function(v){ return v; };
11519                 break;
11520             case "string":
11521                 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
11522                 break;
11523             case "int":
11524                 cv = function(v){
11525                     return v !== undefined && v !== null && v !== '' ?
11526                            parseInt(String(v).replace(stripRe, ""), 10) : '';
11527                     };
11528                 break;
11529             case "float":
11530                 cv = function(v){
11531                     return v !== undefined && v !== null && v !== '' ?
11532                            parseFloat(String(v).replace(stripRe, ""), 10) : ''; 
11533                     };
11534                 break;
11535             case "bool":
11536             case "boolean":
11537                 cv = function(v){ return v === true || v === "true" || v == 1; };
11538                 break;
11539             case "date":
11540                 cv = function(v){
11541                     if(!v){
11542                         return '';
11543                     }
11544                     if(v instanceof Date){
11545                         return v;
11546                     }
11547                     if(dateFormat){
11548                         if(dateFormat == "timestamp"){
11549                             return new Date(v*1000);
11550                         }
11551                         return Date.parseDate(v, dateFormat);
11552                     }
11553                     var parsed = Date.parse(v);
11554                     return parsed ? new Date(parsed) : null;
11555                 };
11556              break;
11557             
11558         }
11559         this.convert = cv;
11560     }
11561 };
11562
11563 Roo.data.Field.prototype = {
11564     dateFormat: null,
11565     defaultValue: "",
11566     mapping: null,
11567     sortType : null,
11568     sortDir : "ASC"
11569 };/*
11570  * Based on:
11571  * Ext JS Library 1.1.1
11572  * Copyright(c) 2006-2007, Ext JS, LLC.
11573  *
11574  * Originally Released Under LGPL - original licence link has changed is not relivant.
11575  *
11576  * Fork - LGPL
11577  * <script type="text/javascript">
11578  */
11579  
11580 // Base class for reading structured data from a data source.  This class is intended to be
11581 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
11582
11583 /**
11584  * @class Roo.data.DataReader
11585  * Base class for reading structured data from a data source.  This class is intended to be
11586  * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
11587  */
11588
11589 Roo.data.DataReader = function(meta, recordType){
11590     
11591     this.meta = meta;
11592     
11593     this.recordType = recordType instanceof Array ? 
11594         Roo.data.Record.create(recordType) : recordType;
11595 };
11596
11597 Roo.data.DataReader.prototype = {
11598      /**
11599      * Create an empty record
11600      * @param {Object} data (optional) - overlay some values
11601      * @return {Roo.data.Record} record created.
11602      */
11603     newRow :  function(d) {
11604         var da =  {};
11605         this.recordType.prototype.fields.each(function(c) {
11606             switch( c.type) {
11607                 case 'int' : da[c.name] = 0; break;
11608                 case 'date' : da[c.name] = new Date(); break;
11609                 case 'float' : da[c.name] = 0.0; break;
11610                 case 'boolean' : da[c.name] = false; break;
11611                 default : da[c.name] = ""; break;
11612             }
11613             
11614         });
11615         return new this.recordType(Roo.apply(da, d));
11616     }
11617     
11618 };/*
11619  * Based on:
11620  * Ext JS Library 1.1.1
11621  * Copyright(c) 2006-2007, Ext JS, LLC.
11622  *
11623  * Originally Released Under LGPL - original licence link has changed is not relivant.
11624  *
11625  * Fork - LGPL
11626  * <script type="text/javascript">
11627  */
11628
11629 /**
11630  * @class Roo.data.DataProxy
11631  * @extends Roo.data.Observable
11632  * This class is an abstract base class for implementations which provide retrieval of
11633  * unformatted data objects.<br>
11634  * <p>
11635  * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
11636  * (of the appropriate type which knows how to parse the data object) to provide a block of
11637  * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
11638  * <p>
11639  * Custom implementations must implement the load method as described in
11640  * {@link Roo.data.HttpProxy#load}.
11641  */
11642 Roo.data.DataProxy = function(){
11643     this.addEvents({
11644         /**
11645          * @event beforeload
11646          * Fires before a network request is made to retrieve a data object.
11647          * @param {Object} This DataProxy object.
11648          * @param {Object} params The params parameter to the load function.
11649          */
11650         beforeload : true,
11651         /**
11652          * @event load
11653          * Fires before the load method's callback is called.
11654          * @param {Object} This DataProxy object.
11655          * @param {Object} o The data object.
11656          * @param {Object} arg The callback argument object passed to the load function.
11657          */
11658         load : true,
11659         /**
11660          * @event loadexception
11661          * Fires if an Exception occurs during data retrieval.
11662          * @param {Object} This DataProxy object.
11663          * @param {Object} o The data object.
11664          * @param {Object} arg The callback argument object passed to the load function.
11665          * @param {Object} e The Exception.
11666          */
11667         loadexception : true
11668     });
11669     Roo.data.DataProxy.superclass.constructor.call(this);
11670 };
11671
11672 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
11673
11674     /**
11675      * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
11676      */
11677 /*
11678  * Based on:
11679  * Ext JS Library 1.1.1
11680  * Copyright(c) 2006-2007, Ext JS, LLC.
11681  *
11682  * Originally Released Under LGPL - original licence link has changed is not relivant.
11683  *
11684  * Fork - LGPL
11685  * <script type="text/javascript">
11686  */
11687 /**
11688  * @class Roo.data.MemoryProxy
11689  * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
11690  * to the Reader when its load method is called.
11691  * @constructor
11692  * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
11693  */
11694 Roo.data.MemoryProxy = function(data){
11695     if (data.data) {
11696         data = data.data;
11697     }
11698     Roo.data.MemoryProxy.superclass.constructor.call(this);
11699     this.data = data;
11700 };
11701
11702 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
11703     
11704     /**
11705      * Load data from the requested source (in this case an in-memory
11706      * data object passed to the constructor), read the data object into
11707      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
11708      * process that block using the passed callback.
11709      * @param {Object} params This parameter is not used by the MemoryProxy class.
11710      * @param {Roo.data.DataReader} reader The Reader object which converts the data
11711      * object into a block of Roo.data.Records.
11712      * @param {Function} callback The function into which to pass the block of Roo.data.records.
11713      * The function must be passed <ul>
11714      * <li>The Record block object</li>
11715      * <li>The "arg" argument from the load function</li>
11716      * <li>A boolean success indicator</li>
11717      * </ul>
11718      * @param {Object} scope The scope in which to call the callback
11719      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
11720      */
11721     load : function(params, reader, callback, scope, arg){
11722         params = params || {};
11723         var result;
11724         try {
11725             result = reader.readRecords(this.data);
11726         }catch(e){
11727             this.fireEvent("loadexception", this, arg, null, e);
11728             callback.call(scope, null, arg, false);
11729             return;
11730         }
11731         callback.call(scope, result, arg, true);
11732     },
11733     
11734     // private
11735     update : function(params, records){
11736         
11737     }
11738 });/*
11739  * Based on:
11740  * Ext JS Library 1.1.1
11741  * Copyright(c) 2006-2007, Ext JS, LLC.
11742  *
11743  * Originally Released Under LGPL - original licence link has changed is not relivant.
11744  *
11745  * Fork - LGPL
11746  * <script type="text/javascript">
11747  */
11748 /**
11749  * @class Roo.data.HttpProxy
11750  * @extends Roo.data.DataProxy
11751  * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
11752  * configured to reference a certain URL.<br><br>
11753  * <p>
11754  * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
11755  * from which the running page was served.<br><br>
11756  * <p>
11757  * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
11758  * <p>
11759  * Be aware that to enable the browser to parse an XML document, the server must set
11760  * the Content-Type header in the HTTP response to "text/xml".
11761  * @constructor
11762  * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
11763  * an {@link Roo.data.Connection} object.  If a Connection config is passed, the singleton {@link Roo.Ajax} object
11764  * will be used to make the request.
11765  */
11766 Roo.data.HttpProxy = function(conn){
11767     Roo.data.HttpProxy.superclass.constructor.call(this);
11768     // is conn a conn config or a real conn?
11769     this.conn = conn;
11770     this.useAjax = !conn || !conn.events;
11771   
11772 };
11773
11774 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
11775     // thse are take from connection...
11776     
11777     /**
11778      * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
11779      */
11780     /**
11781      * @cfg {Object} extraParams (Optional) An object containing properties which are used as
11782      * extra parameters to each request made by this object. (defaults to undefined)
11783      */
11784     /**
11785      * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
11786      *  to each request made by this object. (defaults to undefined)
11787      */
11788     /**
11789      * @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)
11790      */
11791     /**
11792      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11793      */
11794      /**
11795      * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
11796      * @type Boolean
11797      */
11798   
11799
11800     /**
11801      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11802      * @type Boolean
11803      */
11804     /**
11805      * Return the {@link Roo.data.Connection} object being used by this Proxy.
11806      * @return {Connection} The Connection object. This object may be used to subscribe to events on
11807      * a finer-grained basis than the DataProxy events.
11808      */
11809     getConnection : function(){
11810         return this.useAjax ? Roo.Ajax : this.conn;
11811     },
11812
11813     /**
11814      * Load data from the configured {@link Roo.data.Connection}, read the data object into
11815      * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
11816      * process that block using the passed callback.
11817      * @param {Object} params An object containing properties which are to be used as HTTP parameters
11818      * for the request to the remote server.
11819      * @param {Roo.data.DataReader} reader The Reader object which converts the data
11820      * object into a block of Roo.data.Records.
11821      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
11822      * The function must be passed <ul>
11823      * <li>The Record block object</li>
11824      * <li>The "arg" argument from the load function</li>
11825      * <li>A boolean success indicator</li>
11826      * </ul>
11827      * @param {Object} scope The scope in which to call the callback
11828      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
11829      */
11830     load : function(params, reader, callback, scope, arg){
11831         if(this.fireEvent("beforeload", this, params) !== false){
11832             var  o = {
11833                 params : params || {},
11834                 request: {
11835                     callback : callback,
11836                     scope : scope,
11837                     arg : arg
11838                 },
11839                 reader: reader,
11840                 callback : this.loadResponse,
11841                 scope: this
11842             };
11843             if(this.useAjax){
11844                 Roo.applyIf(o, this.conn);
11845                 if(this.activeRequest){
11846                     Roo.Ajax.abort(this.activeRequest);
11847                 }
11848                 this.activeRequest = Roo.Ajax.request(o);
11849             }else{
11850                 this.conn.request(o);
11851             }
11852         }else{
11853             callback.call(scope||this, null, arg, false);
11854         }
11855     },
11856
11857     // private
11858     loadResponse : function(o, success, response){
11859         delete this.activeRequest;
11860         if(!success){
11861             this.fireEvent("loadexception", this, o, response);
11862             o.request.callback.call(o.request.scope, null, o.request.arg, false);
11863             return;
11864         }
11865         var result;
11866         try {
11867             result = o.reader.read(response);
11868         }catch(e){
11869             this.fireEvent("loadexception", this, o, response, e);
11870             o.request.callback.call(o.request.scope, null, o.request.arg, false);
11871             return;
11872         }
11873         
11874         this.fireEvent("load", this, o, o.request.arg);
11875         o.request.callback.call(o.request.scope, result, o.request.arg, true);
11876     },
11877
11878     // private
11879     update : function(dataSet){
11880
11881     },
11882
11883     // private
11884     updateResponse : function(dataSet){
11885
11886     }
11887 });/*
11888  * Based on:
11889  * Ext JS Library 1.1.1
11890  * Copyright(c) 2006-2007, Ext JS, LLC.
11891  *
11892  * Originally Released Under LGPL - original licence link has changed is not relivant.
11893  *
11894  * Fork - LGPL
11895  * <script type="text/javascript">
11896  */
11897
11898 /**
11899  * @class Roo.data.ScriptTagProxy
11900  * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
11901  * other than the originating domain of the running page.<br><br>
11902  * <p>
11903  * <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
11904  * of the running page, you must use this class, rather than DataProxy.</em><br><br>
11905  * <p>
11906  * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
11907  * source code that is used as the source inside a &lt;script> tag.<br><br>
11908  * <p>
11909  * In order for the browser to process the returned data, the server must wrap the data object
11910  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
11911  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
11912  * depending on whether the callback name was passed:
11913  * <p>
11914  * <pre><code>
11915 boolean scriptTag = false;
11916 String cb = request.getParameter("callback");
11917 if (cb != null) {
11918     scriptTag = true;
11919     response.setContentType("text/javascript");
11920 } else {
11921     response.setContentType("application/x-json");
11922 }
11923 Writer out = response.getWriter();
11924 if (scriptTag) {
11925     out.write(cb + "(");
11926 }
11927 out.print(dataBlock.toJsonString());
11928 if (scriptTag) {
11929     out.write(");");
11930 }
11931 </pre></code>
11932  *
11933  * @constructor
11934  * @param {Object} config A configuration object.
11935  */
11936 Roo.data.ScriptTagProxy = function(config){
11937     Roo.data.ScriptTagProxy.superclass.constructor.call(this);
11938     Roo.apply(this, config);
11939     this.head = document.getElementsByTagName("head")[0];
11940 };
11941
11942 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
11943
11944 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
11945     /**
11946      * @cfg {String} url The URL from which to request the data object.
11947      */
11948     /**
11949      * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
11950      */
11951     timeout : 30000,
11952     /**
11953      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
11954      * the server the name of the callback function set up by the load call to process the returned data object.
11955      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
11956      * javascript output which calls this named function passing the data object as its only parameter.
11957      */
11958     callbackParam : "callback",
11959     /**
11960      *  @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
11961      * name to the request.
11962      */
11963     nocache : true,
11964
11965     /**
11966      * Load data from the configured URL, read the data object into
11967      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
11968      * process that block using the passed callback.
11969      * @param {Object} params An object containing properties which are to be used as HTTP parameters
11970      * for the request to the remote server.
11971      * @param {Roo.data.DataReader} reader The Reader object which converts the data
11972      * object into a block of Roo.data.Records.
11973      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
11974      * The function must be passed <ul>
11975      * <li>The Record block object</li>
11976      * <li>The "arg" argument from the load function</li>
11977      * <li>A boolean success indicator</li>
11978      * </ul>
11979      * @param {Object} scope The scope in which to call the callback
11980      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
11981      */
11982     load : function(params, reader, callback, scope, arg){
11983         if(this.fireEvent("beforeload", this, params) !== false){
11984
11985             var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
11986
11987             var url = this.url;
11988             url += (url.indexOf("?") != -1 ? "&" : "?") + p;
11989             if(this.nocache){
11990                 url += "&_dc=" + (new Date().getTime());
11991             }
11992             var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
11993             var trans = {
11994                 id : transId,
11995                 cb : "stcCallback"+transId,
11996                 scriptId : "stcScript"+transId,
11997                 params : params,
11998                 arg : arg,
11999                 url : url,
12000                 callback : callback,
12001                 scope : scope,
12002                 reader : reader
12003             };
12004             var conn = this;
12005
12006             window[trans.cb] = function(o){
12007                 conn.handleResponse(o, trans);
12008             };
12009
12010             url += String.format("&{0}={1}", this.callbackParam, trans.cb);
12011
12012             if(this.autoAbort !== false){
12013                 this.abort();
12014             }
12015
12016             trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
12017
12018             var script = document.createElement("script");
12019             script.setAttribute("src", url);
12020             script.setAttribute("type", "text/javascript");
12021             script.setAttribute("id", trans.scriptId);
12022             this.head.appendChild(script);
12023
12024             this.trans = trans;
12025         }else{
12026             callback.call(scope||this, null, arg, false);
12027         }
12028     },
12029
12030     // private
12031     isLoading : function(){
12032         return this.trans ? true : false;
12033     },
12034
12035     /**
12036      * Abort the current server request.
12037      */
12038     abort : function(){
12039         if(this.isLoading()){
12040             this.destroyTrans(this.trans);
12041         }
12042     },
12043
12044     // private
12045     destroyTrans : function(trans, isLoaded){
12046         this.head.removeChild(document.getElementById(trans.scriptId));
12047         clearTimeout(trans.timeoutId);
12048         if(isLoaded){
12049             window[trans.cb] = undefined;
12050             try{
12051                 delete window[trans.cb];
12052             }catch(e){}
12053         }else{
12054             // if hasn't been loaded, wait for load to remove it to prevent script error
12055             window[trans.cb] = function(){
12056                 window[trans.cb] = undefined;
12057                 try{
12058                     delete window[trans.cb];
12059                 }catch(e){}
12060             };
12061         }
12062     },
12063
12064     // private
12065     handleResponse : function(o, trans){
12066         this.trans = false;
12067         this.destroyTrans(trans, true);
12068         var result;
12069         try {
12070             result = trans.reader.readRecords(o);
12071         }catch(e){
12072             this.fireEvent("loadexception", this, o, trans.arg, e);
12073             trans.callback.call(trans.scope||window, null, trans.arg, false);
12074             return;
12075         }
12076         this.fireEvent("load", this, o, trans.arg);
12077         trans.callback.call(trans.scope||window, result, trans.arg, true);
12078     },
12079
12080     // private
12081     handleFailure : function(trans){
12082         this.trans = false;
12083         this.destroyTrans(trans, false);
12084         this.fireEvent("loadexception", this, null, trans.arg);
12085         trans.callback.call(trans.scope||window, null, trans.arg, false);
12086     }
12087 });/*
12088  * Based on:
12089  * Ext JS Library 1.1.1
12090  * Copyright(c) 2006-2007, Ext JS, LLC.
12091  *
12092  * Originally Released Under LGPL - original licence link has changed is not relivant.
12093  *
12094  * Fork - LGPL
12095  * <script type="text/javascript">
12096  */
12097
12098 /**
12099  * @class Roo.data.JsonReader
12100  * @extends Roo.data.DataReader
12101  * Data reader class to create an Array of Roo.data.Record objects from a JSON response
12102  * based on mappings in a provided Roo.data.Record constructor.
12103  * 
12104  * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
12105  * in the reply previously. 
12106  * 
12107  * <p>
12108  * Example code:
12109  * <pre><code>
12110 var RecordDef = Roo.data.Record.create([
12111     {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
12112     {name: 'occupation'}                 // This field will use "occupation" as the mapping.
12113 ]);
12114 var myReader = new Roo.data.JsonReader({
12115     totalProperty: "results",    // The property which contains the total dataset size (optional)
12116     root: "rows",                // The property which contains an Array of row objects
12117     id: "id"                     // The property within each row object that provides an ID for the record (optional)
12118 }, RecordDef);
12119 </code></pre>
12120  * <p>
12121  * This would consume a JSON file like this:
12122  * <pre><code>
12123 { 'results': 2, 'rows': [
12124     { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
12125     { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
12126 }
12127 </code></pre>
12128  * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
12129  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
12130  * paged from the remote server.
12131  * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
12132  * @cfg {String} root name of the property which contains the Array of row objects.
12133  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
12134  * @cfg {Array} fields Array of field definition objects
12135  * @constructor
12136  * Create a new JsonReader
12137  * @param {Object} meta Metadata configuration options
12138  * @param {Object} recordType Either an Array of field definition objects,
12139  * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
12140  */
12141 Roo.data.JsonReader = function(meta, recordType){
12142     
12143     meta = meta || {};
12144     // set some defaults:
12145     Roo.applyIf(meta, {
12146         totalProperty: 'total',
12147         successProperty : 'success',
12148         root : 'data',
12149         id : 'id'
12150     });
12151     
12152     Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
12153 };
12154 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
12155     
12156     /**
12157      * @prop {Boolean} metaFromRemote  - if the meta data was loaded from the remote source.
12158      * Used by Store query builder to append _requestMeta to params.
12159      * 
12160      */
12161     metaFromRemote : false,
12162     /**
12163      * This method is only used by a DataProxy which has retrieved data from a remote server.
12164      * @param {Object} response The XHR object which contains the JSON data in its responseText.
12165      * @return {Object} data A data block which is used by an Roo.data.Store object as
12166      * a cache of Roo.data.Records.
12167      */
12168     read : function(response){
12169         var json = response.responseText;
12170        
12171         var o = /* eval:var:o */ eval("("+json+")");
12172         if(!o) {
12173             throw {message: "JsonReader.read: Json object not found"};
12174         }
12175         
12176         if(o.metaData){
12177             
12178             delete this.ef;
12179             this.metaFromRemote = true;
12180             this.meta = o.metaData;
12181             this.recordType = Roo.data.Record.create(o.metaData.fields);
12182             this.onMetaChange(this.meta, this.recordType, o);
12183         }
12184         return this.readRecords(o);
12185     },
12186
12187     // private function a store will implement
12188     onMetaChange : function(meta, recordType, o){
12189
12190     },
12191
12192     /**
12193          * @ignore
12194          */
12195     simpleAccess: function(obj, subsc) {
12196         return obj[subsc];
12197     },
12198
12199         /**
12200          * @ignore
12201          */
12202     getJsonAccessor: function(){
12203         var re = /[\[\.]/;
12204         return function(expr) {
12205             try {
12206                 return(re.test(expr))
12207                     ? new Function("obj", "return obj." + expr)
12208                     : function(obj){
12209                         return obj[expr];
12210                     };
12211             } catch(e){}
12212             return Roo.emptyFn;
12213         };
12214     }(),
12215
12216     /**
12217      * Create a data block containing Roo.data.Records from an XML document.
12218      * @param {Object} o An object which contains an Array of row objects in the property specified
12219      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
12220      * which contains the total size of the dataset.
12221      * @return {Object} data A data block which is used by an Roo.data.Store object as
12222      * a cache of Roo.data.Records.
12223      */
12224     readRecords : function(o){
12225         /**
12226          * After any data loads, the raw JSON data is available for further custom processing.
12227          * @type Object
12228          */
12229         this.o = o;
12230         var s = this.meta, Record = this.recordType,
12231             f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
12232
12233 //      Generate extraction functions for the totalProperty, the root, the id, and for each field
12234         if (!this.ef) {
12235             if(s.totalProperty) {
12236                     this.getTotal = this.getJsonAccessor(s.totalProperty);
12237                 }
12238                 if(s.successProperty) {
12239                     this.getSuccess = this.getJsonAccessor(s.successProperty);
12240                 }
12241                 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
12242                 if (s.id) {
12243                         var g = this.getJsonAccessor(s.id);
12244                         this.getId = function(rec) {
12245                                 var r = g(rec);  
12246                                 return (r === undefined || r === "") ? null : r;
12247                         };
12248                 } else {
12249                         this.getId = function(){return null;};
12250                 }
12251             this.ef = [];
12252             for(var jj = 0; jj < fl; jj++){
12253                 f = fi[jj];
12254                 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
12255                 this.ef[jj] = this.getJsonAccessor(map);
12256             }
12257         }
12258
12259         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
12260         if(s.totalProperty){
12261             var vt = parseInt(this.getTotal(o), 10);
12262             if(!isNaN(vt)){
12263                 totalRecords = vt;
12264             }
12265         }
12266         if(s.successProperty){
12267             var vs = this.getSuccess(o);
12268             if(vs === false || vs === 'false'){
12269                 success = false;
12270             }
12271         }
12272         var records = [];
12273         for(var i = 0; i < c; i++){
12274                 var n = root[i];
12275             var values = {};
12276             var id = this.getId(n);
12277             for(var j = 0; j < fl; j++){
12278                 f = fi[j];
12279             var v = this.ef[j](n);
12280             if (!f.convert) {
12281                 Roo.log('missing convert for ' + f.name);
12282                 Roo.log(f);
12283                 continue;
12284             }
12285             values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
12286             }
12287             var record = new Record(values, id);
12288             record.json = n;
12289             records[i] = record;
12290         }
12291         return {
12292             raw : o,
12293             success : success,
12294             records : records,
12295             totalRecords : totalRecords
12296         };
12297     }
12298 });/*
12299  * Based on:
12300  * Ext JS Library 1.1.1
12301  * Copyright(c) 2006-2007, Ext JS, LLC.
12302  *
12303  * Originally Released Under LGPL - original licence link has changed is not relivant.
12304  *
12305  * Fork - LGPL
12306  * <script type="text/javascript">
12307  */
12308
12309 /**
12310  * @class Roo.data.ArrayReader
12311  * @extends Roo.data.DataReader
12312  * Data reader class to create an Array of Roo.data.Record objects from an Array.
12313  * Each element of that Array represents a row of data fields. The
12314  * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
12315  * of the field definition if it exists, or the field's ordinal position in the definition.<br>
12316  * <p>
12317  * Example code:.
12318  * <pre><code>
12319 var RecordDef = Roo.data.Record.create([
12320     {name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
12321     {name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.
12322 ]);
12323 var myReader = new Roo.data.ArrayReader({
12324     id: 0                     // The subscript within row Array that provides an ID for the Record (optional)
12325 }, RecordDef);
12326 </code></pre>
12327  * <p>
12328  * This would consume an Array like this:
12329  * <pre><code>
12330 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
12331   </code></pre>
12332  * @cfg {String} id (optional) The subscript within row Array that provides an ID for the Record
12333  * @constructor
12334  * Create a new JsonReader
12335  * @param {Object} meta Metadata configuration options.
12336  * @param {Object} recordType Either an Array of field definition objects
12337  * as specified to {@link Roo.data.Record#create},
12338  * or an {@link Roo.data.Record} object
12339  * created using {@link Roo.data.Record#create}.
12340  */
12341 Roo.data.ArrayReader = function(meta, recordType){
12342     Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType);
12343 };
12344
12345 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
12346     /**
12347      * Create a data block containing Roo.data.Records from an XML document.
12348      * @param {Object} o An Array of row objects which represents the dataset.
12349      * @return {Object} data A data block which is used by an Roo.data.Store object as
12350      * a cache of Roo.data.Records.
12351      */
12352     readRecords : function(o){
12353         var sid = this.meta ? this.meta.id : null;
12354         var recordType = this.recordType, fields = recordType.prototype.fields;
12355         var records = [];
12356         var root = o;
12357             for(var i = 0; i < root.length; i++){
12358                     var n = root[i];
12359                 var values = {};
12360                 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
12361                 for(var j = 0, jlen = fields.length; j < jlen; j++){
12362                 var f = fields.items[j];
12363                 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
12364                 var v = n[k] !== undefined ? n[k] : f.defaultValue;
12365                 v = f.convert(v);
12366                 values[f.name] = v;
12367             }
12368                 var record = new recordType(values, id);
12369                 record.json = n;
12370                 records[records.length] = record;
12371             }
12372             return {
12373                 records : records,
12374                 totalRecords : records.length
12375             };
12376     }
12377 });/*
12378  * - LGPL
12379  * * 
12380  */
12381
12382 /**
12383  * @class Roo.bootstrap.ComboBox
12384  * @extends Roo.bootstrap.TriggerField
12385  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
12386  * @cfg {Boolean} append (true|false) default false
12387  * @cfg {Boolean} autoFocus (true|false) auto focus the first item, default true
12388  * @cfg {Boolean} tickable ComboBox with tickable selections (true|false), default false
12389  * @cfg {Boolean} triggerList trigger show the list or not (true|false) default true
12390  * @cfg {Boolean} showToggleBtn show toggle button or not (true|false) default true
12391  * @cfg {String} btnPosition set the position of the trigger button (left | right) default right
12392  * @cfg {Boolean} animate default true
12393  * @cfg {Boolean} emptyResultText only for touch device
12394  * @cfg {String} triggerText multiple combobox trigger button text default 'Select'
12395  * @cfg {String} emptyTitle default ''
12396  * @constructor
12397  * Create a new ComboBox.
12398  * @param {Object} config Configuration options
12399  */
12400 Roo.bootstrap.ComboBox = function(config){
12401     Roo.bootstrap.ComboBox.superclass.constructor.call(this, config);
12402     this.addEvents({
12403         /**
12404          * @event expand
12405          * Fires when the dropdown list is expanded
12406         * @param {Roo.bootstrap.ComboBox} combo This combo box
12407         */
12408         'expand' : true,
12409         /**
12410          * @event collapse
12411          * Fires when the dropdown list is collapsed
12412         * @param {Roo.bootstrap.ComboBox} combo This combo box
12413         */
12414         'collapse' : true,
12415         /**
12416          * @event beforeselect
12417          * Fires before a list item is selected. Return false to cancel the selection.
12418         * @param {Roo.bootstrap.ComboBox} combo This combo box
12419         * @param {Roo.data.Record} record The data record returned from the underlying store
12420         * @param {Number} index The index of the selected item in the dropdown list
12421         */
12422         'beforeselect' : true,
12423         /**
12424          * @event select
12425          * Fires when a list item is selected
12426         * @param {Roo.bootstrap.ComboBox} combo This combo box
12427         * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
12428         * @param {Number} index The index of the selected item in the dropdown list
12429         */
12430         'select' : true,
12431         /**
12432          * @event beforequery
12433          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
12434          * The event object passed has these properties:
12435         * @param {Roo.bootstrap.ComboBox} combo This combo box
12436         * @param {String} query The query
12437         * @param {Boolean} forceAll true to force "all" query
12438         * @param {Boolean} cancel true to cancel the query
12439         * @param {Object} e The query event object
12440         */
12441         'beforequery': true,
12442          /**
12443          * @event add
12444          * Fires when the 'add' icon is pressed (add a listener to enable add button)
12445         * @param {Roo.bootstrap.ComboBox} combo This combo box
12446         */
12447         'add' : true,
12448         /**
12449          * @event edit
12450          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
12451         * @param {Roo.bootstrap.ComboBox} combo This combo box
12452         * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
12453         */
12454         'edit' : true,
12455         /**
12456          * @event remove
12457          * Fires when the remove value from the combobox array
12458         * @param {Roo.bootstrap.ComboBox} combo This combo box
12459         */
12460         'remove' : true,
12461         /**
12462          * @event afterremove
12463          * Fires when the remove value from the combobox array
12464         * @param {Roo.bootstrap.ComboBox} combo This combo box
12465         */
12466         'afterremove' : true,
12467         /**
12468          * @event specialfilter
12469          * Fires when specialfilter
12470             * @param {Roo.bootstrap.ComboBox} combo This combo box
12471             */
12472         'specialfilter' : true,
12473         /**
12474          * @event tick
12475          * Fires when tick the element
12476             * @param {Roo.bootstrap.ComboBox} combo This combo box
12477             */
12478         'tick' : true,
12479         /**
12480          * @event touchviewdisplay
12481          * Fires when touch view require special display (default is using displayField)
12482             * @param {Roo.bootstrap.ComboBox} combo This combo box
12483             * @param {Object} cfg set html .
12484             */
12485         'touchviewdisplay' : true
12486         
12487     });
12488     
12489     this.item = [];
12490     this.tickItems = [];
12491     
12492     this.selectedIndex = -1;
12493     if(this.mode == 'local'){
12494         if(config.queryDelay === undefined){
12495             this.queryDelay = 10;
12496         }
12497         if(config.minChars === undefined){
12498             this.minChars = 0;
12499         }
12500     }
12501 };
12502
12503 Roo.extend(Roo.bootstrap.ComboBox, Roo.bootstrap.TriggerField, {
12504      
12505     /**
12506      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
12507      * rendering into an Roo.Editor, defaults to false)
12508      */
12509     /**
12510      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
12511      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
12512      */
12513     /**
12514      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
12515      */
12516     /**
12517      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
12518      * the dropdown list (defaults to undefined, with no header element)
12519      */
12520
12521      /**
12522      * @cfg {String/Roo.Template} tpl The template to use to render the output
12523      */
12524      
12525      /**
12526      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
12527      */
12528     listWidth: undefined,
12529     /**
12530      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
12531      * mode = 'remote' or 'text' if mode = 'local')
12532      */
12533     displayField: undefined,
12534     
12535     /**
12536      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
12537      * mode = 'remote' or 'value' if mode = 'local'). 
12538      * Note: use of a valueField requires the user make a selection
12539      * in order for a value to be mapped.
12540      */
12541     valueField: undefined,
12542     /**
12543      * @cfg {String} modalTitle The title of the dialog that pops up on mobile views.
12544      */
12545     modalTitle : '',
12546     
12547     /**
12548      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
12549      * field's data value (defaults to the underlying DOM element's name)
12550      */
12551     hiddenName: undefined,
12552     /**
12553      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
12554      */
12555     listClass: '',
12556     /**
12557      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
12558      */
12559     selectedClass: 'active',
12560     
12561     /**
12562      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
12563      */
12564     shadow:'sides',
12565     /**
12566      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
12567      * anchor positions (defaults to 'tl-bl')
12568      */
12569     listAlign: 'tl-bl?',
12570     /**
12571      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
12572      */
12573     maxHeight: 300,
12574     /**
12575      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
12576      * query specified by the allQuery config option (defaults to 'query')
12577      */
12578     triggerAction: 'query',
12579     /**
12580      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
12581      * (defaults to 4, does not apply if editable = false)
12582      */
12583     minChars : 4,
12584     /**
12585      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
12586      * delay (typeAheadDelay) if it matches a known value (defaults to false)
12587      */
12588     typeAhead: false,
12589     /**
12590      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
12591      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
12592      */
12593     queryDelay: 500,
12594     /**
12595      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
12596      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
12597      */
12598     pageSize: 0,
12599     /**
12600      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
12601      * when editable = true (defaults to false)
12602      */
12603     selectOnFocus:false,
12604     /**
12605      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
12606      */
12607     queryParam: 'query',
12608     /**
12609      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
12610      * when mode = 'remote' (defaults to 'Loading...')
12611      */
12612     loadingText: 'Loading...',
12613     /**
12614      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
12615      */
12616     resizable: false,
12617     /**
12618      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
12619      */
12620     handleHeight : 8,
12621     /**
12622      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
12623      * traditional select (defaults to true)
12624      */
12625     editable: true,
12626     /**
12627      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
12628      */
12629     allQuery: '',
12630     /**
12631      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
12632      */
12633     mode: 'remote',
12634     /**
12635      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
12636      * listWidth has a higher value)
12637      */
12638     minListWidth : 70,
12639     /**
12640      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
12641      * allow the user to set arbitrary text into the field (defaults to false)
12642      */
12643     forceSelection:false,
12644     /**
12645      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
12646      * if typeAhead = true (defaults to 250)
12647      */
12648     typeAheadDelay : 250,
12649     /**
12650      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
12651      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
12652      */
12653     valueNotFoundText : undefined,
12654     /**
12655      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
12656      */
12657     blockFocus : false,
12658     
12659     /**
12660      * @cfg {Boolean} disableClear Disable showing of clear button.
12661      */
12662     disableClear : false,
12663     /**
12664      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
12665      */
12666     alwaysQuery : false,
12667     
12668     /**
12669      * @cfg {Boolean} multiple  (true|false) ComboBobArray, default false
12670      */
12671     multiple : false,
12672     
12673     /**
12674      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
12675      */
12676     invalidClass : "has-warning",
12677     
12678     /**
12679      * @cfg {String} validClass The CSS class to use when marking a field valid (defaults to "x-form-invalid")
12680      */
12681     validClass : "has-success",
12682     
12683     /**
12684      * @cfg {Boolean} specialFilter (true|false) special filter default false
12685      */
12686     specialFilter : false,
12687     
12688     /**
12689      * @cfg {Boolean} mobileTouchView (true|false) show mobile touch view when using a mobile default true
12690      */
12691     mobileTouchView : true,
12692     
12693     /**
12694      * @cfg {Boolean} useNativeIOS (true|false) render it as classic select for ios, not support dynamic load data (default false)
12695      */
12696     useNativeIOS : false,
12697     
12698     ios_options : false,
12699     
12700     //private
12701     addicon : false,
12702     editicon: false,
12703     
12704     page: 0,
12705     hasQuery: false,
12706     append: false,
12707     loadNext: false,
12708     autoFocus : true,
12709     tickable : false,
12710     btnPosition : 'right',
12711     triggerList : true,
12712     showToggleBtn : true,
12713     animate : true,
12714     emptyResultText: 'Empty',
12715     triggerText : 'Select',
12716     emptyTitle : '',
12717     
12718     // element that contains real text value.. (when hidden is used..)
12719     
12720     getAutoCreate : function()
12721     {   
12722         var cfg = false;
12723         //render
12724         /*
12725          * Render classic select for iso
12726          */
12727         
12728         if(Roo.isIOS && this.useNativeIOS){
12729             cfg = this.getAutoCreateNativeIOS();
12730             return cfg;
12731         }
12732         
12733         /*
12734          * Touch Devices
12735          */
12736         
12737         if(Roo.isTouch && this.mobileTouchView){
12738             cfg = this.getAutoCreateTouchView();
12739             return cfg;;
12740         }
12741         
12742         /*
12743          *  Normal ComboBox
12744          */
12745         if(!this.tickable){
12746             cfg = Roo.bootstrap.ComboBox.superclass.getAutoCreate.call(this);
12747             return cfg;
12748         }
12749         
12750         /*
12751          *  ComboBox with tickable selections
12752          */
12753              
12754         var align = this.labelAlign || this.parentLabelAlign();
12755         
12756         cfg = {
12757             cls : 'form-group roo-combobox-tickable' //input-group
12758         };
12759         
12760         var btn_text_select = '';
12761         var btn_text_done = '';
12762         var btn_text_cancel = '';
12763         
12764         if (this.btn_text_show) {
12765             btn_text_select = 'Select';
12766             btn_text_done = 'Done';
12767             btn_text_cancel = 'Cancel'; 
12768         }
12769         
12770         var buttons = {
12771             tag : 'div',
12772             cls : 'tickable-buttons',
12773             cn : [
12774                 {
12775                     tag : 'button',
12776                     type : 'button',
12777                     cls : 'btn btn-link btn-edit pull-' + this.btnPosition,
12778                     //html : this.triggerText
12779                     html: btn_text_select
12780                 },
12781                 {
12782                     tag : 'button',
12783                     type : 'button',
12784                     name : 'ok',
12785                     cls : 'btn btn-link btn-ok pull-' + this.btnPosition,
12786                     //html : 'Done'
12787                     html: btn_text_done
12788                 },
12789                 {
12790                     tag : 'button',
12791                     type : 'button',
12792                     name : 'cancel',
12793                     cls : 'btn btn-link btn-cancel pull-' + this.btnPosition,
12794                     //html : 'Cancel'
12795                     html: btn_text_cancel
12796                 }
12797             ]
12798         };
12799         
12800         if(this.editable){
12801             buttons.cn.unshift({
12802                 tag: 'input',
12803                 cls: 'roo-select2-search-field-input'
12804             });
12805         }
12806         
12807         var _this = this;
12808         
12809         Roo.each(buttons.cn, function(c){
12810             if (_this.size) {
12811                 c.cls += ' btn-' + _this.size;
12812             }
12813
12814             if (_this.disabled) {
12815                 c.disabled = true;
12816             }
12817         });
12818         
12819         var box = {
12820             tag: 'div',
12821             cn: [
12822                 {
12823                     tag: 'input',
12824                     type : 'hidden',
12825                     cls: 'form-hidden-field'
12826                 },
12827                 {
12828                     tag: 'ul',
12829                     cls: 'roo-select2-choices',
12830                     cn:[
12831                         {
12832                             tag: 'li',
12833                             cls: 'roo-select2-search-field',
12834                             cn: [
12835                                 buttons
12836                             ]
12837                         }
12838                     ]
12839                 }
12840             ]
12841         };
12842         
12843         var combobox = {
12844             cls: 'roo-select2-container input-group roo-select2-container-multi',
12845             cn: [
12846                 box
12847 //                {
12848 //                    tag: 'ul',
12849 //                    cls: 'typeahead typeahead-long dropdown-menu',
12850 //                    style: 'display:none; max-height:' + this.maxHeight + 'px;'
12851 //                }
12852             ]
12853         };
12854         
12855         if(this.hasFeedback && !this.allowBlank){
12856             
12857             var feedback = {
12858                 tag: 'span',
12859                 cls: 'glyphicon form-control-feedback'
12860             };
12861
12862             combobox.cn.push(feedback);
12863         }
12864         
12865         
12866         if (align ==='left' && this.fieldLabel.length) {
12867             
12868             cfg.cls += ' roo-form-group-label-left';
12869             
12870             cfg.cn = [
12871                 {
12872                     tag : 'i',
12873                     cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
12874                     tooltip : 'This field is required'
12875                 },
12876                 {
12877                     tag: 'label',
12878                     'for' :  id,
12879                     cls : 'control-label',
12880                     html : this.fieldLabel
12881
12882                 },
12883                 {
12884                     cls : "", 
12885                     cn: [
12886                         combobox
12887                     ]
12888                 }
12889
12890             ];
12891             
12892             var labelCfg = cfg.cn[1];
12893             var contentCfg = cfg.cn[2];
12894             
12895
12896             if(this.indicatorpos == 'right'){
12897                 
12898                 cfg.cn = [
12899                     {
12900                         tag: 'label',
12901                         'for' :  id,
12902                         cls : 'control-label',
12903                         cn : [
12904                             {
12905                                 tag : 'span',
12906                                 html : this.fieldLabel
12907                             },
12908                             {
12909                                 tag : 'i',
12910                                 cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
12911                                 tooltip : 'This field is required'
12912                             }
12913                         ]
12914                     },
12915                     {
12916                         cls : "",
12917                         cn: [
12918                             combobox
12919                         ]
12920                     }
12921
12922                 ];
12923                 
12924                 
12925                 
12926                 labelCfg = cfg.cn[0];
12927                 contentCfg = cfg.cn[1];
12928             
12929             }
12930             
12931             if(this.labelWidth > 12){
12932                 labelCfg.style = "width: " + this.labelWidth + 'px';
12933             }
12934             
12935             if(this.labelWidth < 13 && this.labelmd == 0){
12936                 this.labelmd = this.labelWidth;
12937             }
12938             
12939             if(this.labellg > 0){
12940                 labelCfg.cls += ' col-lg-' + this.labellg;
12941                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
12942             }
12943             
12944             if(this.labelmd > 0){
12945                 labelCfg.cls += ' col-md-' + this.labelmd;
12946                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
12947             }
12948             
12949             if(this.labelsm > 0){
12950                 labelCfg.cls += ' col-sm-' + this.labelsm;
12951                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
12952             }
12953             
12954             if(this.labelxs > 0){
12955                 labelCfg.cls += ' col-xs-' + this.labelxs;
12956                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
12957             }
12958                 
12959                 
12960         } else if ( this.fieldLabel.length) {
12961 //                Roo.log(" label");
12962                  cfg.cn = [
12963                     {
12964                         tag : 'i',
12965                         cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
12966                         tooltip : 'This field is required'
12967                     },
12968                     {
12969                         tag: 'label',
12970                         //cls : 'input-group-addon',
12971                         html : this.fieldLabel
12972                     },
12973                     combobox
12974                 ];
12975                 
12976                 if(this.indicatorpos == 'right'){
12977                     cfg.cn = [
12978                         {
12979                             tag: 'label',
12980                             //cls : 'input-group-addon',
12981                             html : this.fieldLabel
12982                         },
12983                         {
12984                             tag : 'i',
12985                             cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
12986                             tooltip : 'This field is required'
12987                         },
12988                         combobox
12989                     ];
12990                     
12991                 }
12992
12993         } else {
12994             
12995 //                Roo.log(" no label && no align");
12996                 cfg = combobox
12997                      
12998                 
12999         }
13000          
13001         var settings=this;
13002         ['xs','sm','md','lg'].map(function(size){
13003             if (settings[size]) {
13004                 cfg.cls += ' col-' + size + '-' + settings[size];
13005             }
13006         });
13007         
13008         return cfg;
13009         
13010     },
13011     
13012     _initEventsCalled : false,
13013     
13014     // private
13015     initEvents: function()
13016     {   
13017         if (this._initEventsCalled) { // as we call render... prevent looping...
13018             return;
13019         }
13020         this._initEventsCalled = true;
13021         
13022         if (!this.store) {
13023             throw "can not find store for combo";
13024         }
13025         
13026         this.indicator = this.indicatorEl();
13027         
13028         this.store = Roo.factory(this.store, Roo.data);
13029         this.store.parent = this;
13030         
13031         // if we are building from html. then this element is so complex, that we can not really
13032         // use the rendered HTML.
13033         // so we have to trash and replace the previous code.
13034         if (Roo.XComponent.build_from_html) {
13035             // remove this element....
13036             var e = this.el.dom, k=0;
13037             while (e ) { e = e.previousSibling;  ++k;}
13038
13039             this.el.remove();
13040             
13041             this.el=false;
13042             this.rendered = false;
13043             
13044             this.render(this.parent().getChildContainer(true), k);
13045         }
13046         
13047         if(Roo.isIOS && this.useNativeIOS){
13048             this.initIOSView();
13049             return;
13050         }
13051         
13052         /*
13053          * Touch Devices
13054          */
13055         
13056         if(Roo.isTouch && this.mobileTouchView){
13057             this.initTouchView();
13058             return;
13059         }
13060         
13061         if(this.tickable){
13062             this.initTickableEvents();
13063             return;
13064         }
13065         
13066         Roo.bootstrap.ComboBox.superclass.initEvents.call(this);
13067         
13068         if(this.hiddenName){
13069             
13070             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
13071             
13072             this.hiddenField.dom.value =
13073                 this.hiddenValue !== undefined ? this.hiddenValue :
13074                 this.value !== undefined ? this.value : '';
13075
13076             // prevent input submission
13077             this.el.dom.removeAttribute('name');
13078             this.hiddenField.dom.setAttribute('name', this.hiddenName);
13079              
13080              
13081         }
13082         //if(Roo.isGecko){
13083         //    this.el.dom.setAttribute('autocomplete', 'off');
13084         //}
13085         
13086         var cls = 'x-combo-list';
13087         
13088         //this.list = new Roo.Layer({
13089         //    shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
13090         //});
13091         
13092         var _this = this;
13093         
13094         (function(){
13095             var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
13096             _this.list.setWidth(lw);
13097         }).defer(100);
13098         
13099         this.list.on('mouseover', this.onViewOver, this);
13100         this.list.on('mousemove', this.onViewMove, this);
13101         this.list.on('scroll', this.onViewScroll, this);
13102         
13103         /*
13104         this.list.swallowEvent('mousewheel');
13105         this.assetHeight = 0;
13106
13107         if(this.title){
13108             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
13109             this.assetHeight += this.header.getHeight();
13110         }
13111
13112         this.innerList = this.list.createChild({cls:cls+'-inner'});
13113         this.innerList.on('mouseover', this.onViewOver, this);
13114         this.innerList.on('mousemove', this.onViewMove, this);
13115         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
13116         
13117         if(this.allowBlank && !this.pageSize && !this.disableClear){
13118             this.footer = this.list.createChild({cls:cls+'-ft'});
13119             this.pageTb = new Roo.Toolbar(this.footer);
13120            
13121         }
13122         if(this.pageSize){
13123             this.footer = this.list.createChild({cls:cls+'-ft'});
13124             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
13125                     {pageSize: this.pageSize});
13126             
13127         }
13128         
13129         if (this.pageTb && this.allowBlank && !this.disableClear) {
13130             var _this = this;
13131             this.pageTb.add(new Roo.Toolbar.Fill(), {
13132                 cls: 'x-btn-icon x-btn-clear',
13133                 text: '&#160;',
13134                 handler: function()
13135                 {
13136                     _this.collapse();
13137                     _this.clearValue();
13138                     _this.onSelect(false, -1);
13139                 }
13140             });
13141         }
13142         if (this.footer) {
13143             this.assetHeight += this.footer.getHeight();
13144         }
13145         */
13146             
13147         if(!this.tpl){
13148             this.tpl = '<li><a href="#">{' + this.displayField + '}</a></li>';
13149         }
13150
13151         this.view = new Roo.View(this.list, this.tpl, {
13152             singleSelect:true, store: this.store, selectedClass: this.selectedClass
13153         });
13154         //this.view.wrapEl.setDisplayed(false);
13155         this.view.on('click', this.onViewClick, this);
13156         
13157         
13158         this.store.on('beforeload', this.onBeforeLoad, this);
13159         this.store.on('load', this.onLoad, this);
13160         this.store.on('loadexception', this.onLoadException, this);
13161         /*
13162         if(this.resizable){
13163             this.resizer = new Roo.Resizable(this.list,  {
13164                pinned:true, handles:'se'
13165             });
13166             this.resizer.on('resize', function(r, w, h){
13167                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
13168                 this.listWidth = w;
13169                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
13170                 this.restrictHeight();
13171             }, this);
13172             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
13173         }
13174         */
13175         if(!this.editable){
13176             this.editable = true;
13177             this.setEditable(false);
13178         }
13179         
13180         /*
13181         
13182         if (typeof(this.events.add.listeners) != 'undefined') {
13183             
13184             this.addicon = this.wrap.createChild(
13185                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
13186        
13187             this.addicon.on('click', function(e) {
13188                 this.fireEvent('add', this);
13189             }, this);
13190         }
13191         if (typeof(this.events.edit.listeners) != 'undefined') {
13192             
13193             this.editicon = this.wrap.createChild(
13194                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
13195             if (this.addicon) {
13196                 this.editicon.setStyle('margin-left', '40px');
13197             }
13198             this.editicon.on('click', function(e) {
13199                 
13200                 // we fire even  if inothing is selected..
13201                 this.fireEvent('edit', this, this.lastData );
13202                 
13203             }, this);
13204         }
13205         */
13206         
13207         this.keyNav = new Roo.KeyNav(this.inputEl(), {
13208             "up" : function(e){
13209                 this.inKeyMode = true;
13210                 this.selectPrev();
13211             },
13212
13213             "down" : function(e){
13214                 if(!this.isExpanded()){
13215                     this.onTriggerClick();
13216                 }else{
13217                     this.inKeyMode = true;
13218                     this.selectNext();
13219                 }
13220             },
13221
13222             "enter" : function(e){
13223 //                this.onViewClick();
13224                 //return true;
13225                 this.collapse();
13226                 
13227                 if(this.fireEvent("specialkey", this, e)){
13228                     this.onViewClick(false);
13229                 }
13230                 
13231                 return true;
13232             },
13233
13234             "esc" : function(e){
13235                 this.collapse();
13236             },
13237
13238             "tab" : function(e){
13239                 this.collapse();
13240                 
13241                 if(this.fireEvent("specialkey", this, e)){
13242                     this.onViewClick(false);
13243                 }
13244                 
13245                 return true;
13246             },
13247
13248             scope : this,
13249
13250             doRelay : function(foo, bar, hname){
13251                 if(hname == 'down' || this.scope.isExpanded()){
13252                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
13253                 }
13254                 return true;
13255             },
13256
13257             forceKeyDown: true
13258         });
13259         
13260         
13261         this.queryDelay = Math.max(this.queryDelay || 10,
13262                 this.mode == 'local' ? 10 : 250);
13263         
13264         
13265         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
13266         
13267         if(this.typeAhead){
13268             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
13269         }
13270         if(this.editable !== false){
13271             this.inputEl().on("keyup", this.onKeyUp, this);
13272         }
13273         if(this.forceSelection){
13274             this.inputEl().on('blur', this.doForce, this);
13275         }
13276         
13277         if(this.multiple){
13278             this.choices = this.el.select('ul.roo-select2-choices', true).first();
13279             this.searchField = this.el.select('ul li.roo-select2-search-field', true).first();
13280         }
13281     },
13282     
13283     initTickableEvents: function()
13284     {   
13285         this.createList();
13286         
13287         if(this.hiddenName){
13288             
13289             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
13290             
13291             this.hiddenField.dom.value =
13292                 this.hiddenValue !== undefined ? this.hiddenValue :
13293                 this.value !== undefined ? this.value : '';
13294
13295             // prevent input submission
13296             this.el.dom.removeAttribute('name');
13297             this.hiddenField.dom.setAttribute('name', this.hiddenName);
13298              
13299              
13300         }
13301         
13302 //        this.list = this.el.select('ul.dropdown-menu',true).first();
13303         
13304         this.choices = this.el.select('ul.roo-select2-choices', true).first();
13305         this.searchField = this.el.select('ul li.roo-select2-search-field', true).first();
13306         if(this.triggerList){
13307             this.searchField.on("click", this.onSearchFieldClick, this, {preventDefault:true});
13308         }
13309          
13310         this.trigger = this.el.select('.tickable-buttons > .btn-edit', true).first();
13311         this.trigger.on("click", this.onTickableTriggerClick, this, {preventDefault:true});
13312         
13313         this.okBtn = this.el.select('.tickable-buttons > .btn-ok', true).first();
13314         this.cancelBtn = this.el.select('.tickable-buttons > .btn-cancel', true).first();
13315         
13316         this.okBtn.on('click', this.onTickableFooterButtonClick, this, this.okBtn);
13317         this.cancelBtn.on('click', this.onTickableFooterButtonClick, this, this.cancelBtn);
13318         
13319         this.trigger.setVisibilityMode(Roo.Element.DISPLAY);
13320         this.okBtn.setVisibilityMode(Roo.Element.DISPLAY);
13321         this.cancelBtn.setVisibilityMode(Roo.Element.DISPLAY);
13322         
13323         this.okBtn.hide();
13324         this.cancelBtn.hide();
13325         
13326         var _this = this;
13327         
13328         (function(){
13329             var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
13330             _this.list.setWidth(lw);
13331         }).defer(100);
13332         
13333         this.list.on('mouseover', this.onViewOver, this);
13334         this.list.on('mousemove', this.onViewMove, this);
13335         
13336         this.list.on('scroll', this.onViewScroll, this);
13337         
13338         if(!this.tpl){
13339             this.tpl = '<li class="roo-select2-result"><div class="checkbox"><input id="{roo-id}" type="checkbox" {roo-data-checked}><label for="{roo-id}"><b>{' + this.displayField + '}</b></label></div></li>';
13340         }
13341
13342         this.view = new Roo.View(this.list, this.tpl, {
13343             singleSelect:true, tickable:true, parent:this, store: this.store, selectedClass: this.selectedClass
13344         });
13345         
13346         //this.view.wrapEl.setDisplayed(false);
13347         this.view.on('click', this.onViewClick, this);
13348         
13349         
13350         
13351         this.store.on('beforeload', this.onBeforeLoad, this);
13352         this.store.on('load', this.onLoad, this);
13353         this.store.on('loadexception', this.onLoadException, this);
13354         
13355         if(this.editable){
13356             this.keyNav = new Roo.KeyNav(this.tickableInputEl(), {
13357                 "up" : function(e){
13358                     this.inKeyMode = true;
13359                     this.selectPrev();
13360                 },
13361
13362                 "down" : function(e){
13363                     this.inKeyMode = true;
13364                     this.selectNext();
13365                 },
13366
13367                 "enter" : function(e){
13368                     if(this.fireEvent("specialkey", this, e)){
13369                         this.onViewClick(false);
13370                     }
13371                     
13372                     return true;
13373                 },
13374
13375                 "esc" : function(e){
13376                     this.onTickableFooterButtonClick(e, false, false);
13377                 },
13378
13379                 "tab" : function(e){
13380                     this.fireEvent("specialkey", this, e);
13381                     
13382                     this.onTickableFooterButtonClick(e, false, false);
13383                     
13384                     return true;
13385                 },
13386
13387                 scope : this,
13388
13389                 doRelay : function(e, fn, key){
13390                     if(this.scope.isExpanded()){
13391                        return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
13392                     }
13393                     return true;
13394                 },
13395
13396                 forceKeyDown: true
13397             });
13398         }
13399         
13400         this.queryDelay = Math.max(this.queryDelay || 10,
13401                 this.mode == 'local' ? 10 : 250);
13402         
13403         
13404         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
13405         
13406         if(this.typeAhead){
13407             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
13408         }
13409         
13410         if(this.editable !== false){
13411             this.tickableInputEl().on("keyup", this.onKeyUp, this);
13412         }
13413         
13414         this.indicator = this.indicatorEl();
13415         
13416         if(this.indicator){
13417             this.indicator.setVisibilityMode(Roo.Element.DISPLAY);
13418             this.indicator.hide();
13419         }
13420         
13421     },
13422
13423     onDestroy : function(){
13424         if(this.view){
13425             this.view.setStore(null);
13426             this.view.el.removeAllListeners();
13427             this.view.el.remove();
13428             this.view.purgeListeners();
13429         }
13430         if(this.list){
13431             this.list.dom.innerHTML  = '';
13432         }
13433         
13434         if(this.store){
13435             this.store.un('beforeload', this.onBeforeLoad, this);
13436             this.store.un('load', this.onLoad, this);
13437             this.store.un('loadexception', this.onLoadException, this);
13438         }
13439         Roo.bootstrap.ComboBox.superclass.onDestroy.call(this);
13440     },
13441
13442     // private
13443     fireKey : function(e){
13444         if(e.isNavKeyPress() && !this.list.isVisible()){
13445             this.fireEvent("specialkey", this, e);
13446         }
13447     },
13448
13449     // private
13450     onResize: function(w, h){
13451 //        Roo.bootstrap.ComboBox.superclass.onResize.apply(this, arguments);
13452 //        
13453 //        if(typeof w != 'number'){
13454 //            // we do not handle it!?!?
13455 //            return;
13456 //        }
13457 //        var tw = this.trigger.getWidth();
13458 //       // tw += this.addicon ? this.addicon.getWidth() : 0;
13459 //       // tw += this.editicon ? this.editicon.getWidth() : 0;
13460 //        var x = w - tw;
13461 //        this.inputEl().setWidth( this.adjustWidth('input', x));
13462 //            
13463 //        //this.trigger.setStyle('left', x+'px');
13464 //        
13465 //        if(this.list && this.listWidth === undefined){
13466 //            var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
13467 //            this.list.setWidth(lw);
13468 //            this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
13469 //        }
13470         
13471     
13472         
13473     },
13474
13475     /**
13476      * Allow or prevent the user from directly editing the field text.  If false is passed,
13477      * the user will only be able to select from the items defined in the dropdown list.  This method
13478      * is the runtime equivalent of setting the 'editable' config option at config time.
13479      * @param {Boolean} value True to allow the user to directly edit the field text
13480      */
13481     setEditable : function(value){
13482         if(value == this.editable){
13483             return;
13484         }
13485         this.editable = value;
13486         if(!value){
13487             this.inputEl().dom.setAttribute('readOnly', true);
13488             this.inputEl().on('mousedown', this.onTriggerClick,  this);
13489             this.inputEl().addClass('x-combo-noedit');
13490         }else{
13491             this.inputEl().dom.setAttribute('readOnly', false);
13492             this.inputEl().un('mousedown', this.onTriggerClick,  this);
13493             this.inputEl().removeClass('x-combo-noedit');
13494         }
13495     },
13496
13497     // private
13498     
13499     onBeforeLoad : function(combo,opts){
13500         if(!this.hasFocus){
13501             return;
13502         }
13503          if (!opts.add) {
13504             this.list.dom.innerHTML = '<li class="loading-indicator">'+(this.loadingText||'loading')+'</li>' ;
13505          }
13506         this.restrictHeight();
13507         this.selectedIndex = -1;
13508     },
13509
13510     // private
13511     onLoad : function(){
13512         
13513         this.hasQuery = false;
13514         
13515         if(!this.hasFocus){
13516             return;
13517         }
13518         
13519         if(typeof(this.loading) !== 'undefined' && this.loading !== null){
13520             this.loading.hide();
13521         }
13522         
13523         if(this.store.getCount() > 0){
13524             
13525             this.expand();
13526             this.restrictHeight();
13527             if(this.lastQuery == this.allQuery){
13528                 if(this.editable && !this.tickable){
13529                     this.inputEl().dom.select();
13530                 }
13531                 
13532                 if(
13533                     !this.selectByValue(this.value, true) &&
13534                     this.autoFocus && 
13535                     (
13536                         !this.store.lastOptions ||
13537                         typeof(this.store.lastOptions.add) == 'undefined' || 
13538                         this.store.lastOptions.add != true
13539                     )
13540                 ){
13541                     this.select(0, true);
13542                 }
13543             }else{
13544                 if(this.autoFocus){
13545                     this.selectNext();
13546                 }
13547                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
13548                     this.taTask.delay(this.typeAheadDelay);
13549                 }
13550             }
13551         }else{
13552             this.onEmptyResults();
13553         }
13554         
13555         //this.el.focus();
13556     },
13557     // private
13558     onLoadException : function()
13559     {
13560         this.hasQuery = false;
13561         
13562         if(typeof(this.loading) !== 'undefined' && this.loading !== null){
13563             this.loading.hide();
13564         }
13565         
13566         if(this.tickable && this.editable){
13567             return;
13568         }
13569         
13570         this.collapse();
13571         // only causes errors at present
13572         //Roo.log(this.store.reader.jsonData);
13573         //if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
13574             // fixme
13575             //Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
13576         //}
13577         
13578         
13579     },
13580     // private
13581     onTypeAhead : function(){
13582         if(this.store.getCount() > 0){
13583             var r = this.store.getAt(0);
13584             var newValue = r.data[this.displayField];
13585             var len = newValue.length;
13586             var selStart = this.getRawValue().length;
13587             
13588             if(selStart != len){
13589                 this.setRawValue(newValue);
13590                 this.selectText(selStart, newValue.length);
13591             }
13592         }
13593     },
13594
13595     // private
13596     onSelect : function(record, index){
13597         
13598         if(this.fireEvent('beforeselect', this, record, index) !== false){
13599         
13600             this.setFromData(index > -1 ? record.data : false);
13601             
13602             this.collapse();
13603             this.fireEvent('select', this, record, index);
13604         }
13605     },
13606
13607     /**
13608      * Returns the currently selected field value or empty string if no value is set.
13609      * @return {String} value The selected value
13610      */
13611     getValue : function()
13612     {
13613         if(Roo.isIOS && this.useNativeIOS){
13614             return this.ios_options[this.inputEl().dom.selectedIndex].data[this.valueField];
13615         }
13616         
13617         if(this.multiple){
13618             return (this.hiddenField) ? this.hiddenField.dom.value : this.value;
13619         }
13620         
13621         if(this.valueField){
13622             return typeof this.value != 'undefined' ? this.value : '';
13623         }else{
13624             return Roo.bootstrap.ComboBox.superclass.getValue.call(this);
13625         }
13626     },
13627     
13628     getRawValue : function()
13629     {
13630         if(Roo.isIOS && this.useNativeIOS){
13631             return this.ios_options[this.inputEl().dom.selectedIndex].data[this.displayField];
13632         }
13633         
13634         var v = this.inputEl().getValue();
13635         
13636         return v;
13637     },
13638
13639     /**
13640      * Clears any text/value currently set in the field
13641      */
13642     clearValue : function(){
13643         
13644         if(this.hiddenField){
13645             this.hiddenField.dom.value = '';
13646         }
13647         this.value = '';
13648         this.setRawValue('');
13649         this.lastSelectionText = '';
13650         this.lastData = false;
13651         
13652         var close = this.closeTriggerEl();
13653         
13654         if(close){
13655             close.hide();
13656         }
13657         
13658         this.validate();
13659         
13660     },
13661
13662     /**
13663      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
13664      * will be displayed in the field.  If the value does not match the data value of an existing item,
13665      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
13666      * Otherwise the field will be blank (although the value will still be set).
13667      * @param {String} value The value to match
13668      */
13669     setValue : function(v)
13670     {
13671         if(Roo.isIOS && this.useNativeIOS){
13672             this.setIOSValue(v);
13673             return;
13674         }
13675         
13676         if(this.multiple){
13677             this.syncValue();
13678             return;
13679         }
13680         
13681         var text = v;
13682         if(this.valueField){
13683             var r = this.findRecord(this.valueField, v);
13684             if(r){
13685                 text = r.data[this.displayField];
13686             }else if(this.valueNotFoundText !== undefined){
13687                 text = this.valueNotFoundText;
13688             }
13689         }
13690         this.lastSelectionText = text;
13691         if(this.hiddenField){
13692             this.hiddenField.dom.value = v;
13693         }
13694         Roo.bootstrap.ComboBox.superclass.setValue.call(this, text);
13695         this.value = v;
13696         
13697         var close = this.closeTriggerEl();
13698         
13699         if(close){
13700             (v && (v.length || v * 1 > 0)) ? close.show() : close.hide();
13701         }
13702         
13703         this.validate();
13704     },
13705     /**
13706      * @property {Object} the last set data for the element
13707      */
13708     
13709     lastData : false,
13710     /**
13711      * Sets the value of the field based on a object which is related to the record format for the store.
13712      * @param {Object} value the value to set as. or false on reset?
13713      */
13714     setFromData : function(o){
13715         
13716         if(this.multiple){
13717             this.addItem(o);
13718             return;
13719         }
13720             
13721         var dv = ''; // display value
13722         var vv = ''; // value value..
13723         this.lastData = o;
13724         if (this.displayField) {
13725             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
13726         } else {
13727             // this is an error condition!!!
13728             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
13729         }
13730         
13731         if(this.valueField){
13732             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
13733         }
13734         
13735         var close = this.closeTriggerEl();
13736         
13737         if(close){
13738             if(dv.length || vv * 1 > 0){
13739                 close.show() ;
13740                 this.blockFocus=true;
13741             } else {
13742                 close.hide();
13743             }             
13744         }
13745         
13746         if(this.hiddenField){
13747             this.hiddenField.dom.value = vv;
13748             
13749             this.lastSelectionText = dv;
13750             Roo.bootstrap.ComboBox.superclass.setValue.call(this, dv);
13751             this.value = vv;
13752             return;
13753         }
13754         // no hidden field.. - we store the value in 'value', but still display
13755         // display field!!!!
13756         this.lastSelectionText = dv;
13757         Roo.bootstrap.ComboBox.superclass.setValue.call(this, dv);
13758         this.value = vv;
13759         
13760         
13761         
13762     },
13763     // private
13764     reset : function(){
13765         // overridden so that last data is reset..
13766         
13767         if(this.multiple){
13768             this.clearItem();
13769             return;
13770         }
13771         
13772         this.setValue(this.originalValue);
13773         //this.clearInvalid();
13774         this.lastData = false;
13775         if (this.view) {
13776             this.view.clearSelections();
13777         }
13778         
13779         this.validate();
13780     },
13781     // private
13782     findRecord : function(prop, value){
13783         var record;
13784         if(this.store.getCount() > 0){
13785             this.store.each(function(r){
13786                 if(r.data[prop] == value){
13787                     record = r;
13788                     return false;
13789                 }
13790                 return true;
13791             });
13792         }
13793         return record;
13794     },
13795     
13796     getName: function()
13797     {
13798         // returns hidden if it's set..
13799         if (!this.rendered) {return ''};
13800         return !this.hiddenName && this.inputEl().dom.name  ? this.inputEl().dom.name : (this.hiddenName || '');
13801         
13802     },
13803     // private
13804     onViewMove : function(e, t){
13805         this.inKeyMode = false;
13806     },
13807
13808     // private
13809     onViewOver : function(e, t){
13810         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
13811             return;
13812         }
13813         var item = this.view.findItemFromChild(t);
13814         
13815         if(item){
13816             var index = this.view.indexOf(item);
13817             this.select(index, false);
13818         }
13819     },
13820
13821     // private
13822     onViewClick : function(view, doFocus, el, e)
13823     {
13824         var index = this.view.getSelectedIndexes()[0];
13825         
13826         var r = this.store.getAt(index);
13827         
13828         if(this.tickable){
13829             
13830             if(typeof(e) != 'undefined' && e.getTarget().nodeName.toLowerCase() != 'input'){
13831                 return;
13832             }
13833             
13834             var rm = false;
13835             var _this = this;
13836             
13837             Roo.each(this.tickItems, function(v,k){
13838                 
13839                 if(typeof(v) != 'undefined' && v[_this.valueField] == r.data[_this.valueField]){
13840                     Roo.log(v);
13841                     _this.tickItems.splice(k, 1);
13842                     
13843                     if(typeof(e) == 'undefined' && view == false){
13844                         Roo.get(_this.view.getNodes(index, index)[0]).select('input', true).first().dom.checked = false;
13845                     }
13846                     
13847                     rm = true;
13848                     return;
13849                 }
13850             });
13851             
13852             if(rm){
13853                 return;
13854             }
13855             
13856             if(this.fireEvent('tick', this, r, index, Roo.get(_this.view.getNodes(index, index)[0]).select('input', true).first().dom.checked) !== false){
13857                 this.tickItems.push(r.data);
13858             }
13859             
13860             if(typeof(e) == 'undefined' && view == false){
13861                 Roo.get(_this.view.getNodes(index, index)[0]).select('input', true).first().dom.checked = true;
13862             }
13863                     
13864             return;
13865         }
13866         
13867         if(r){
13868             this.onSelect(r, index);
13869         }
13870         if(doFocus !== false && !this.blockFocus){
13871             this.inputEl().focus();
13872         }
13873     },
13874
13875     // private
13876     restrictHeight : function(){
13877         //this.innerList.dom.style.height = '';
13878         //var inner = this.innerList.dom;
13879         //var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
13880         //this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
13881         //this.list.beginUpdate();
13882         //this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
13883         this.list.alignTo(this.inputEl(), this.listAlign);
13884         this.list.alignTo(this.inputEl(), this.listAlign);
13885         //this.list.endUpdate();
13886     },
13887
13888     // private
13889     onEmptyResults : function(){
13890         
13891         if(this.tickable && this.editable){
13892             this.restrictHeight();
13893             return;
13894         }
13895         
13896         this.collapse();
13897     },
13898
13899     /**
13900      * Returns true if the dropdown list is expanded, else false.
13901      */
13902     isExpanded : function(){
13903         return this.list.isVisible();
13904     },
13905
13906     /**
13907      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
13908      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
13909      * @param {String} value The data value of the item to select
13910      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
13911      * selected item if it is not currently in view (defaults to true)
13912      * @return {Boolean} True if the value matched an item in the list, else false
13913      */
13914     selectByValue : function(v, scrollIntoView){
13915         if(v !== undefined && v !== null){
13916             var r = this.findRecord(this.valueField || this.displayField, v);
13917             if(r){
13918                 this.select(this.store.indexOf(r), scrollIntoView);
13919                 return true;
13920             }
13921         }
13922         return false;
13923     },
13924
13925     /**
13926      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
13927      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
13928      * @param {Number} index The zero-based index of the list item to select
13929      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
13930      * selected item if it is not currently in view (defaults to true)
13931      */
13932     select : function(index, scrollIntoView){
13933         this.selectedIndex = index;
13934         this.view.select(index);
13935         if(scrollIntoView !== false){
13936             var el = this.view.getNode(index);
13937             /*
13938              * el && !this.multiple && !this.tickable // not sure why we disable multiple before..
13939              */
13940             if(el){
13941                 this.list.scrollChildIntoView(el, false);
13942             }
13943         }
13944     },
13945
13946     // private
13947     selectNext : function(){
13948         var ct = this.store.getCount();
13949         if(ct > 0){
13950             if(this.selectedIndex == -1){
13951                 this.select(0);
13952             }else if(this.selectedIndex < ct-1){
13953                 this.select(this.selectedIndex+1);
13954             }
13955         }
13956     },
13957
13958     // private
13959     selectPrev : function(){
13960         var ct = this.store.getCount();
13961         if(ct > 0){
13962             if(this.selectedIndex == -1){
13963                 this.select(0);
13964             }else if(this.selectedIndex != 0){
13965                 this.select(this.selectedIndex-1);
13966             }
13967         }
13968     },
13969
13970     // private
13971     onKeyUp : function(e){
13972         if(this.editable !== false && !e.isSpecialKey()){
13973             this.lastKey = e.getKey();
13974             this.dqTask.delay(this.queryDelay);
13975         }
13976     },
13977
13978     // private
13979     validateBlur : function(){
13980         return !this.list || !this.list.isVisible();   
13981     },
13982
13983     // private
13984     initQuery : function(){
13985         
13986         var v = this.getRawValue();
13987         
13988         if(this.tickable && this.editable){
13989             v = this.tickableInputEl().getValue();
13990         }
13991         
13992         this.doQuery(v);
13993     },
13994
13995     // private
13996     doForce : function(){
13997         if(this.inputEl().dom.value.length > 0){
13998             this.inputEl().dom.value =
13999                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
14000              
14001         }
14002     },
14003
14004     /**
14005      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
14006      * query allowing the query action to be canceled if needed.
14007      * @param {String} query The SQL query to execute
14008      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
14009      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
14010      * saved in the current store (defaults to false)
14011      */
14012     doQuery : function(q, forceAll){
14013         
14014         if(q === undefined || q === null){
14015             q = '';
14016         }
14017         var qe = {
14018             query: q,
14019             forceAll: forceAll,
14020             combo: this,
14021             cancel:false
14022         };
14023         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
14024             return false;
14025         }
14026         q = qe.query;
14027         
14028         forceAll = qe.forceAll;
14029         if(forceAll === true || (q.length >= this.minChars)){
14030             
14031             this.hasQuery = true;
14032             
14033             if(this.lastQuery != q || this.alwaysQuery){
14034                 this.lastQuery = q;
14035                 if(this.mode == 'local'){
14036                     this.selectedIndex = -1;
14037                     if(forceAll){
14038                         this.store.clearFilter();
14039                     }else{
14040                         
14041                         if(this.specialFilter){
14042                             this.fireEvent('specialfilter', this);
14043                             this.onLoad();
14044                             return;
14045                         }
14046                         
14047                         this.store.filter(this.displayField, q);
14048                     }
14049                     
14050                     this.store.fireEvent("datachanged", this.store);
14051                     
14052                     this.onLoad();
14053                     
14054                     
14055                 }else{
14056                     
14057                     this.store.baseParams[this.queryParam] = q;
14058                     
14059                     var options = {params : this.getParams(q)};
14060                     
14061                     if(this.loadNext){
14062                         options.add = true;
14063                         options.params.start = this.page * this.pageSize;
14064                     }
14065                     
14066                     this.store.load(options);
14067                     
14068                     /*
14069                      *  this code will make the page width larger, at the beginning, the list not align correctly, 
14070                      *  we should expand the list on onLoad
14071                      *  so command out it
14072                      */
14073 //                    this.expand();
14074                 }
14075             }else{
14076                 this.selectedIndex = -1;
14077                 this.onLoad();   
14078             }
14079         }
14080         
14081         this.loadNext = false;
14082     },
14083     
14084     // private
14085     getParams : function(q){
14086         var p = {};
14087         //p[this.queryParam] = q;
14088         
14089         if(this.pageSize){
14090             p.start = 0;
14091             p.limit = this.pageSize;
14092         }
14093         return p;
14094     },
14095
14096     /**
14097      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
14098      */
14099     collapse : function(){
14100         if(!this.isExpanded()){
14101             return;
14102         }
14103         
14104         this.list.hide();
14105         
14106         this.hasFocus = false;
14107         
14108         if(this.tickable){
14109             this.okBtn.hide();
14110             this.cancelBtn.hide();
14111             this.trigger.show();
14112             
14113             if(this.editable){
14114                 this.tickableInputEl().dom.value = '';
14115                 this.tickableInputEl().blur();
14116             }
14117             
14118         }
14119         
14120         Roo.get(document).un('mousedown', this.collapseIf, this);
14121         Roo.get(document).un('mousewheel', this.collapseIf, this);
14122         if (!this.editable) {
14123             Roo.get(document).un('keydown', this.listKeyPress, this);
14124         }
14125         this.fireEvent('collapse', this);
14126         
14127         this.validate();
14128     },
14129
14130     // private
14131     collapseIf : function(e){
14132         var in_combo  = e.within(this.el);
14133         var in_list =  e.within(this.list);
14134         var is_list = (Roo.get(e.getTarget()).id == this.list.id) ? true : false;
14135         
14136         if (in_combo || in_list || is_list) {
14137             //e.stopPropagation();
14138             return;
14139         }
14140         
14141         if(this.tickable){
14142             this.onTickableFooterButtonClick(e, false, false);
14143         }
14144
14145         this.collapse();
14146         
14147     },
14148
14149     /**
14150      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
14151      */
14152     expand : function(){
14153        
14154         if(this.isExpanded() || !this.hasFocus){
14155             return;
14156         }
14157         
14158         var lw = this.listWidth || Math.max(this.inputEl().getWidth(), this.minListWidth);
14159         this.list.setWidth(lw);
14160         
14161         Roo.log('expand');
14162         
14163         this.list.show();
14164         
14165         this.restrictHeight();
14166         
14167         if(this.tickable){
14168             
14169             this.tickItems = Roo.apply([], this.item);
14170             
14171             this.okBtn.show();
14172             this.cancelBtn.show();
14173             this.trigger.hide();
14174             
14175             if(this.editable){
14176                 this.tickableInputEl().focus();
14177             }
14178             
14179         }
14180         
14181         Roo.get(document).on('mousedown', this.collapseIf, this);
14182         Roo.get(document).on('mousewheel', this.collapseIf, this);
14183         if (!this.editable) {
14184             Roo.get(document).on('keydown', this.listKeyPress, this);
14185         }
14186         
14187         this.fireEvent('expand', this);
14188     },
14189
14190     // private
14191     // Implements the default empty TriggerField.onTriggerClick function
14192     onTriggerClick : function(e)
14193     {
14194         Roo.log('trigger click');
14195         
14196         if(this.disabled || !this.triggerList){
14197             return;
14198         }
14199         
14200         this.page = 0;
14201         this.loadNext = false;
14202         
14203         if(this.isExpanded()){
14204             this.collapse();
14205             if (!this.blockFocus) {
14206                 this.inputEl().focus();
14207             }
14208             
14209         }else {
14210             this.hasFocus = true;
14211             if(this.triggerAction == 'all') {
14212                 this.doQuery(this.allQuery, true);
14213             } else {
14214                 this.doQuery(this.getRawValue());
14215             }
14216             if (!this.blockFocus) {
14217                 this.inputEl().focus();
14218             }
14219         }
14220     },
14221     
14222     onTickableTriggerClick : function(e)
14223     {
14224         if(this.disabled){
14225             return;
14226         }
14227         
14228         this.page = 0;
14229         this.loadNext = false;
14230         this.hasFocus = true;
14231         
14232         if(this.triggerAction == 'all') {
14233             this.doQuery(this.allQuery, true);
14234         } else {
14235             this.doQuery(this.getRawValue());
14236         }
14237     },
14238     
14239     onSearchFieldClick : function(e)
14240     {
14241         if(this.hasFocus && !this.disabled && e.getTarget().nodeName.toLowerCase() != 'button'){
14242             this.onTickableFooterButtonClick(e, false, false);
14243             return;
14244         }
14245         
14246         if(this.hasFocus || this.disabled || e.getTarget().nodeName.toLowerCase() == 'button'){
14247             return;
14248         }
14249         
14250         this.page = 0;
14251         this.loadNext = false;
14252         this.hasFocus = true;
14253         
14254         if(this.triggerAction == 'all') {
14255             this.doQuery(this.allQuery, true);
14256         } else {
14257             this.doQuery(this.getRawValue());
14258         }
14259     },
14260     
14261     listKeyPress : function(e)
14262     {
14263         //Roo.log('listkeypress');
14264         // scroll to first matching element based on key pres..
14265         if (e.isSpecialKey()) {
14266             return false;
14267         }
14268         var k = String.fromCharCode(e.getKey()).toUpperCase();
14269         //Roo.log(k);
14270         var match  = false;
14271         var csel = this.view.getSelectedNodes();
14272         var cselitem = false;
14273         if (csel.length) {
14274             var ix = this.view.indexOf(csel[0]);
14275             cselitem  = this.store.getAt(ix);
14276             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
14277                 cselitem = false;
14278             }
14279             
14280         }
14281         
14282         this.store.each(function(v) { 
14283             if (cselitem) {
14284                 // start at existing selection.
14285                 if (cselitem.id == v.id) {
14286                     cselitem = false;
14287                 }
14288                 return true;
14289             }
14290                 
14291             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
14292                 match = this.store.indexOf(v);
14293                 return false;
14294             }
14295             return true;
14296         }, this);
14297         
14298         if (match === false) {
14299             return true; // no more action?
14300         }
14301         // scroll to?
14302         this.view.select(match);
14303         var sn = Roo.get(this.view.getSelectedNodes()[0]);
14304         sn.scrollIntoView(sn.dom.parentNode, false);
14305     },
14306     
14307     onViewScroll : function(e, t){
14308         
14309         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){
14310             return;
14311         }
14312         
14313         this.hasQuery = true;
14314         
14315         this.loading = this.list.select('.loading', true).first();
14316         
14317         if(this.loading === null){
14318             this.list.createChild({
14319                 tag: 'div',
14320                 cls: 'loading roo-select2-more-results roo-select2-active',
14321                 html: 'Loading more results...'
14322             });
14323             
14324             this.loading = this.list.select('.loading', true).first();
14325             
14326             this.loading.setVisibilityMode(Roo.Element.DISPLAY);
14327             
14328             this.loading.hide();
14329         }
14330         
14331         this.loading.show();
14332         
14333         var _combo = this;
14334         
14335         this.page++;
14336         this.loadNext = true;
14337         
14338         (function() { _combo.doQuery(_combo.allQuery, true); }).defer(500);
14339         
14340         return;
14341     },
14342     
14343     addItem : function(o)
14344     {   
14345         var dv = ''; // display value
14346         
14347         if (this.displayField) {
14348             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
14349         } else {
14350             // this is an error condition!!!
14351             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
14352         }
14353         
14354         if(!dv.length){
14355             return;
14356         }
14357         
14358         var choice = this.choices.createChild({
14359             tag: 'li',
14360             cls: 'roo-select2-search-choice',
14361             cn: [
14362                 {
14363                     tag: 'div',
14364                     html: dv
14365                 },
14366                 {
14367                     tag: 'a',
14368                     href: '#',
14369                     cls: 'roo-select2-search-choice-close fa fa-times',
14370                     tabindex: '-1'
14371                 }
14372             ]
14373             
14374         }, this.searchField);
14375         
14376         var close = choice.select('a.roo-select2-search-choice-close', true).first();
14377         
14378         close.on('click', this.onRemoveItem, this, { item : choice, data : o} );
14379         
14380         this.item.push(o);
14381         
14382         this.lastData = o;
14383         
14384         this.syncValue();
14385         
14386         this.inputEl().dom.value = '';
14387         
14388         this.validate();
14389     },
14390     
14391     onRemoveItem : function(e, _self, o)
14392     {
14393         e.preventDefault();
14394         
14395         this.lastItem = Roo.apply([], this.item);
14396         
14397         var index = this.item.indexOf(o.data) * 1;
14398         
14399         if( index < 0){
14400             Roo.log('not this item?!');
14401             return;
14402         }
14403         
14404         this.item.splice(index, 1);
14405         o.item.remove();
14406         
14407         this.syncValue();
14408         
14409         this.fireEvent('remove', this, e);
14410         
14411         this.validate();
14412         
14413     },
14414     
14415     syncValue : function()
14416     {
14417         if(!this.item.length){
14418             this.clearValue();
14419             return;
14420         }
14421             
14422         var value = [];
14423         var _this = this;
14424         Roo.each(this.item, function(i){
14425             if(_this.valueField){
14426                 value.push(i[_this.valueField]);
14427                 return;
14428             }
14429
14430             value.push(i);
14431         });
14432
14433         this.value = value.join(',');
14434
14435         if(this.hiddenField){
14436             this.hiddenField.dom.value = this.value;
14437         }
14438         
14439         this.store.fireEvent("datachanged", this.store);
14440         
14441         this.validate();
14442     },
14443     
14444     clearItem : function()
14445     {
14446         if(!this.multiple){
14447             return;
14448         }
14449         
14450         this.item = [];
14451         
14452         Roo.each(this.choices.select('>li.roo-select2-search-choice', true).elements, function(c){
14453            c.remove();
14454         });
14455         
14456         this.syncValue();
14457         
14458         this.validate();
14459         
14460         if(this.tickable && !Roo.isTouch){
14461             this.view.refresh();
14462         }
14463     },
14464     
14465     inputEl: function ()
14466     {
14467         if(Roo.isIOS && this.useNativeIOS){
14468             return this.el.select('select.roo-ios-select', true).first();
14469         }
14470         
14471         if(Roo.isTouch && this.mobileTouchView){
14472             return this.el.select('input.form-control',true).first();
14473         }
14474         
14475         if(this.tickable){
14476             return this.searchField;
14477         }
14478         
14479         return this.el.select('input.form-control',true).first();
14480     },
14481     
14482     onTickableFooterButtonClick : function(e, btn, el)
14483     {
14484         e.preventDefault();
14485         
14486         this.lastItem = Roo.apply([], this.item);
14487         
14488         if(btn && btn.name == 'cancel'){
14489             this.tickItems = Roo.apply([], this.item);
14490             this.collapse();
14491             return;
14492         }
14493         
14494         this.clearItem();
14495         
14496         var _this = this;
14497         
14498         Roo.each(this.tickItems, function(o){
14499             _this.addItem(o);
14500         });
14501         
14502         this.collapse();
14503         
14504     },
14505     
14506     validate : function()
14507     {
14508         var v = this.getRawValue();
14509         
14510         if(this.multiple){
14511             v = this.getValue();
14512         }
14513         
14514         if(this.disabled || this.allowBlank || v.length){
14515             this.markValid();
14516             return true;
14517         }
14518         
14519         this.markInvalid();
14520         return false;
14521     },
14522     
14523     tickableInputEl : function()
14524     {
14525         if(!this.tickable || !this.editable){
14526             return this.inputEl();
14527         }
14528         
14529         return this.inputEl().select('.roo-select2-search-field-input', true).first();
14530     },
14531     
14532     
14533     getAutoCreateTouchView : function()
14534     {
14535         var id = Roo.id();
14536         
14537         var cfg = {
14538             cls: 'form-group' //input-group
14539         };
14540         
14541         var input =  {
14542             tag: 'input',
14543             id : id,
14544             type : this.inputType,
14545             cls : 'form-control x-combo-noedit',
14546             autocomplete: 'new-password',
14547             placeholder : this.placeholder || '',
14548             readonly : true
14549         };
14550         
14551         if (this.name) {
14552             input.name = this.name;
14553         }
14554         
14555         if (this.size) {
14556             input.cls += ' input-' + this.size;
14557         }
14558         
14559         if (this.disabled) {
14560             input.disabled = true;
14561         }
14562         
14563         var inputblock = {
14564             cls : '',
14565             cn : [
14566                 input
14567             ]
14568         };
14569         
14570         if(this.before){
14571             inputblock.cls += ' input-group';
14572             
14573             inputblock.cn.unshift({
14574                 tag :'span',
14575                 cls : 'input-group-addon',
14576                 html : this.before
14577             });
14578         }
14579         
14580         if(this.removable && !this.multiple){
14581             inputblock.cls += ' roo-removable';
14582             
14583             inputblock.cn.push({
14584                 tag: 'button',
14585                 html : 'x',
14586                 cls : 'roo-combo-removable-btn close'
14587             });
14588         }
14589
14590         if(this.hasFeedback && !this.allowBlank){
14591             
14592             inputblock.cls += ' has-feedback';
14593             
14594             inputblock.cn.push({
14595                 tag: 'span',
14596                 cls: 'glyphicon form-control-feedback'
14597             });
14598             
14599         }
14600         
14601         if (this.after) {
14602             
14603             inputblock.cls += (this.before) ? '' : ' input-group';
14604             
14605             inputblock.cn.push({
14606                 tag :'span',
14607                 cls : 'input-group-addon',
14608                 html : this.after
14609             });
14610         }
14611
14612         var box = {
14613             tag: 'div',
14614             cn: [
14615                 {
14616                     tag: 'input',
14617                     type : 'hidden',
14618                     cls: 'form-hidden-field'
14619                 },
14620                 inputblock
14621             ]
14622             
14623         };
14624         
14625         if(this.multiple){
14626             box = {
14627                 tag: 'div',
14628                 cn: [
14629                     {
14630                         tag: 'input',
14631                         type : 'hidden',
14632                         cls: 'form-hidden-field'
14633                     },
14634                     {
14635                         tag: 'ul',
14636                         cls: 'roo-select2-choices',
14637                         cn:[
14638                             {
14639                                 tag: 'li',
14640                                 cls: 'roo-select2-search-field',
14641                                 cn: [
14642
14643                                     inputblock
14644                                 ]
14645                             }
14646                         ]
14647                     }
14648                 ]
14649             }
14650         };
14651         
14652         var combobox = {
14653             cls: 'roo-select2-container input-group roo-touchview-combobox ',
14654             cn: [
14655                 box
14656             ]
14657         };
14658         
14659         if(!this.multiple && this.showToggleBtn){
14660             
14661             var caret = {
14662                         tag: 'span',
14663                         cls: 'caret'
14664             };
14665             
14666             if (this.caret != false) {
14667                 caret = {
14668                      tag: 'i',
14669                      cls: 'fa fa-' + this.caret
14670                 };
14671                 
14672             }
14673             
14674             combobox.cn.push({
14675                 tag :'span',
14676                 cls : 'input-group-addon btn dropdown-toggle',
14677                 cn : [
14678                     caret,
14679                     {
14680                         tag: 'span',
14681                         cls: 'combobox-clear',
14682                         cn  : [
14683                             {
14684                                 tag : 'i',
14685                                 cls: 'icon-remove'
14686                             }
14687                         ]
14688                     }
14689                 ]
14690
14691             })
14692         }
14693         
14694         if(this.multiple){
14695             combobox.cls += ' roo-select2-container-multi';
14696         }
14697         
14698         var align = this.labelAlign || this.parentLabelAlign();
14699         
14700         if (align ==='left' && this.fieldLabel.length) {
14701
14702             cfg.cn = [
14703                 {
14704                    tag : 'i',
14705                    cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
14706                    tooltip : 'This field is required'
14707                 },
14708                 {
14709                     tag: 'label',
14710                     cls : 'control-label',
14711                     html : this.fieldLabel
14712
14713                 },
14714                 {
14715                     cls : '', 
14716                     cn: [
14717                         combobox
14718                     ]
14719                 }
14720             ];
14721             
14722             var labelCfg = cfg.cn[1];
14723             var contentCfg = cfg.cn[2];
14724             
14725
14726             if(this.indicatorpos == 'right'){
14727                 cfg.cn = [
14728                     {
14729                         tag: 'label',
14730                         'for' :  id,
14731                         cls : 'control-label',
14732                         cn : [
14733                             {
14734                                 tag : 'span',
14735                                 html : this.fieldLabel
14736                             },
14737                             {
14738                                 tag : 'i',
14739                                 cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
14740                                 tooltip : 'This field is required'
14741                             }
14742                         ]
14743                     },
14744                     {
14745                         cls : "",
14746                         cn: [
14747                             combobox
14748                         ]
14749                     }
14750
14751                 ];
14752                 
14753                 labelCfg = cfg.cn[0];
14754                 contentCfg = cfg.cn[1];
14755             }
14756             
14757            
14758             
14759             if(this.labelWidth > 12){
14760                 labelCfg.style = "width: " + this.labelWidth + 'px';
14761             }
14762             
14763             if(this.labelWidth < 13 && this.labelmd == 0){
14764                 this.labelmd = this.labelWidth;
14765             }
14766             
14767             if(this.labellg > 0){
14768                 labelCfg.cls += ' col-lg-' + this.labellg;
14769                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
14770             }
14771             
14772             if(this.labelmd > 0){
14773                 labelCfg.cls += ' col-md-' + this.labelmd;
14774                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
14775             }
14776             
14777             if(this.labelsm > 0){
14778                 labelCfg.cls += ' col-sm-' + this.labelsm;
14779                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
14780             }
14781             
14782             if(this.labelxs > 0){
14783                 labelCfg.cls += ' col-xs-' + this.labelxs;
14784                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
14785             }
14786                 
14787                 
14788         } else if ( this.fieldLabel.length) {
14789             cfg.cn = [
14790                 {
14791                    tag : 'i',
14792                    cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
14793                    tooltip : 'This field is required'
14794                 },
14795                 {
14796                     tag: 'label',
14797                     cls : 'control-label',
14798                     html : this.fieldLabel
14799
14800                 },
14801                 {
14802                     cls : '', 
14803                     cn: [
14804                         combobox
14805                     ]
14806                 }
14807             ];
14808             
14809             if(this.indicatorpos == 'right'){
14810                 cfg.cn = [
14811                     {
14812                         tag: 'label',
14813                         cls : 'control-label',
14814                         html : this.fieldLabel,
14815                         cn : [
14816                             {
14817                                tag : 'i',
14818                                cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
14819                                tooltip : 'This field is required'
14820                             }
14821                         ]
14822                     },
14823                     {
14824                         cls : '', 
14825                         cn: [
14826                             combobox
14827                         ]
14828                     }
14829                 ];
14830             }
14831         } else {
14832             cfg.cn = combobox;    
14833         }
14834         
14835         
14836         var settings = this;
14837         
14838         ['xs','sm','md','lg'].map(function(size){
14839             if (settings[size]) {
14840                 cfg.cls += ' col-' + size + '-' + settings[size];
14841             }
14842         });
14843         
14844         return cfg;
14845     },
14846     
14847     initTouchView : function()
14848     {
14849         this.renderTouchView();
14850         
14851         this.touchViewEl.on('scroll', function(){
14852             this.el.dom.scrollTop = 0;
14853         }, this);
14854         
14855         this.originalValue = this.getValue();
14856         
14857         this.triggerEl = this.el.select('span.dropdown-toggle',true).first();
14858         
14859         this.inputEl().on("click", this.showTouchView, this);
14860         if (this.triggerEl) {
14861             this.triggerEl.on("click", this.showTouchView, this);
14862         }
14863         
14864         
14865         this.touchViewFooterEl.select('.roo-touch-view-cancel', true).first().on('click', this.hideTouchView, this);
14866         this.touchViewFooterEl.select('.roo-touch-view-ok', true).first().on('click', this.setTouchViewValue, this);
14867         
14868         this.maskEl = new Roo.LoadMask(this.touchViewEl, { store : this.store, msgCls: 'roo-el-mask-msg' });
14869         
14870         this.store.on('beforeload', this.onTouchViewBeforeLoad, this);
14871         this.store.on('load', this.onTouchViewLoad, this);
14872         this.store.on('loadexception', this.onTouchViewLoadException, this);
14873         
14874         if(this.hiddenName){
14875             
14876             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
14877             
14878             this.hiddenField.dom.value =
14879                 this.hiddenValue !== undefined ? this.hiddenValue :
14880                 this.value !== undefined ? this.value : '';
14881         
14882             this.el.dom.removeAttribute('name');
14883             this.hiddenField.dom.setAttribute('name', this.hiddenName);
14884         }
14885         
14886         if(this.multiple){
14887             this.choices = this.el.select('ul.roo-select2-choices', true).first();
14888             this.searchField = this.el.select('ul li.roo-select2-search-field', true).first();
14889         }
14890         
14891         if(this.removable && !this.multiple){
14892             var close = this.closeTriggerEl();
14893             if(close){
14894                 close.setVisibilityMode(Roo.Element.DISPLAY).hide();
14895                 close.on('click', this.removeBtnClick, this, close);
14896             }
14897         }
14898         /*
14899          * fix the bug in Safari iOS8
14900          */
14901         this.inputEl().on("focus", function(e){
14902             document.activeElement.blur();
14903         }, this);
14904         
14905         return;
14906         
14907         
14908     },
14909     
14910     renderTouchView : function()
14911     {
14912         this.touchViewEl = Roo.get(document.body).createChild(Roo.bootstrap.ComboBox.touchViewTemplate);
14913         this.touchViewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
14914         
14915         this.touchViewHeaderEl = this.touchViewEl.select('.modal-header', true).first();
14916         this.touchViewHeaderEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
14917         
14918         this.touchViewBodyEl = this.touchViewEl.select('.modal-body', true).first();
14919         this.touchViewBodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
14920         this.touchViewBodyEl.setStyle('overflow', 'auto');
14921         
14922         this.touchViewListGroup = this.touchViewBodyEl.select('.list-group', true).first();
14923         this.touchViewListGroup.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
14924         
14925         this.touchViewFooterEl = this.touchViewEl.select('.modal-footer', true).first();
14926         this.touchViewFooterEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
14927         
14928     },
14929     
14930     showTouchView : function()
14931     {
14932         if(this.disabled){
14933             return;
14934         }
14935         
14936         this.touchViewHeaderEl.hide();
14937
14938         if(this.modalTitle.length){
14939             this.touchViewHeaderEl.dom.innerHTML = this.modalTitle;
14940             this.touchViewHeaderEl.show();
14941         }
14942
14943         this.touchViewEl.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
14944         this.touchViewEl.show();
14945
14946         this.touchViewEl.select('.modal-dialog', true).first().setStyle({ margin : '0px', width : '100%'});
14947         
14948         //this.touchViewEl.select('.modal-dialog > .modal-content', true).first().setSize(
14949         //        Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
14950
14951         var bodyHeight = Roo.lib.Dom.getViewHeight() - this.touchViewFooterEl.getHeight() + this.touchViewBodyEl.getPadding('tb');
14952
14953         if(this.modalTitle.length){
14954             bodyHeight = bodyHeight - this.touchViewHeaderEl.getHeight();
14955         }
14956         
14957         this.touchViewBodyEl.setHeight(bodyHeight);
14958
14959         if(this.animate){
14960             var _this = this;
14961             (function(){ _this.touchViewEl.addClass('in'); }).defer(50);
14962         }else{
14963             this.touchViewEl.addClass('in');
14964         }
14965
14966         this.doTouchViewQuery();
14967         
14968     },
14969     
14970     hideTouchView : function()
14971     {
14972         this.touchViewEl.removeClass('in');
14973
14974         if(this.animate){
14975             var _this = this;
14976             (function(){ _this.touchViewEl.setStyle('display', 'none'); }).defer(150);
14977         }else{
14978             this.touchViewEl.setStyle('display', 'none');
14979         }
14980         
14981     },
14982     
14983     setTouchViewValue : function()
14984     {
14985         if(this.multiple){
14986             this.clearItem();
14987         
14988             var _this = this;
14989
14990             Roo.each(this.tickItems, function(o){
14991                 this.addItem(o);
14992             }, this);
14993         }
14994         
14995         this.hideTouchView();
14996     },
14997     
14998     doTouchViewQuery : function()
14999     {
15000         var qe = {
15001             query: '',
15002             forceAll: true,
15003             combo: this,
15004             cancel:false
15005         };
15006         
15007         if(this.fireEvent('beforequery', qe) ===false || qe.cancel){
15008             return false;
15009         }
15010         
15011         if(!this.alwaysQuery || this.mode == 'local'){
15012             this.onTouchViewLoad();
15013             return;
15014         }
15015         
15016         this.store.load();
15017     },
15018     
15019     onTouchViewBeforeLoad : function(combo,opts)
15020     {
15021         return;
15022     },
15023
15024     // private
15025     onTouchViewLoad : function()
15026     {
15027         if(this.store.getCount() < 1){
15028             this.onTouchViewEmptyResults();
15029             return;
15030         }
15031         
15032         this.clearTouchView();
15033         
15034         var rawValue = this.getRawValue();
15035         
15036         var template = (this.multiple) ? Roo.bootstrap.ComboBox.listItemCheckbox : Roo.bootstrap.ComboBox.listItemRadio;
15037         
15038         this.tickItems = [];
15039         
15040         this.store.data.each(function(d, rowIndex){
15041             var row = this.touchViewListGroup.createChild(template);
15042             
15043             if(typeof(d.data.cls) != 'undefined' && d.data.cls.length){
15044                 row.addClass(d.data.cls);
15045             }
15046             
15047             if(this.displayField && typeof(d.data[this.displayField]) != 'undefined'){
15048                 var cfg = {
15049                     data : d.data,
15050                     html : d.data[this.displayField]
15051                 };
15052                 
15053                 if(this.fireEvent('touchviewdisplay', this, cfg) !== false){
15054                     row.select('.roo-combobox-list-group-item-value', true).first().dom.innerHTML = cfg.html;
15055                 }
15056             }
15057             row.removeClass('selected');
15058             if(!this.multiple && this.valueField &&
15059                     typeof(d.data[this.valueField]) != 'undefined' && d.data[this.valueField] == this.getValue())
15060             {
15061                 // radio buttons..
15062                 row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
15063                 row.addClass('selected');
15064             }
15065             
15066             if(this.multiple && this.valueField &&
15067                     typeof(d.data[this.valueField]) != 'undefined' && this.getValue().indexOf(d.data[this.valueField]) != -1)
15068             {
15069                 
15070                 // checkboxes...
15071                 row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
15072                 this.tickItems.push(d.data);
15073             }
15074             
15075             row.on('click', this.onTouchViewClick, this, {row : row, rowIndex : rowIndex});
15076             
15077         }, this);
15078         
15079         var firstChecked = this.touchViewListGroup.select('.list-group-item > .roo-combobox-list-group-item-box > input:checked', true).first();
15080         
15081         var bodyHeight = Roo.lib.Dom.getViewHeight() - this.touchViewFooterEl.getHeight() + this.touchViewBodyEl.getPadding('tb');
15082
15083         if(this.modalTitle.length){
15084             bodyHeight = bodyHeight - this.touchViewHeaderEl.getHeight();
15085         }
15086
15087         var listHeight = this.touchViewListGroup.getHeight();
15088         
15089         var _this = this;
15090         
15091         if(firstChecked && listHeight > bodyHeight){
15092             (function() { firstChecked.findParent('li').scrollIntoView(_this.touchViewListGroup.dom); }).defer(500);
15093         }
15094         
15095     },
15096     
15097     onTouchViewLoadException : function()
15098     {
15099         this.hideTouchView();
15100     },
15101     
15102     onTouchViewEmptyResults : function()
15103     {
15104         this.clearTouchView();
15105         
15106         this.touchViewListGroup.createChild(Roo.bootstrap.ComboBox.emptyResult);
15107         
15108         this.touchViewListGroup.select('.roo-combobox-touch-view-empty-result', true).first().dom.innerHTML = this.emptyResultText;
15109         
15110     },
15111     
15112     clearTouchView : function()
15113     {
15114         this.touchViewListGroup.dom.innerHTML = '';
15115     },
15116     
15117     onTouchViewClick : function(e, el, o)
15118     {
15119         e.preventDefault();
15120         
15121         var row = o.row;
15122         var rowIndex = o.rowIndex;
15123         
15124         var r = this.store.getAt(rowIndex);
15125         
15126         if(this.fireEvent('beforeselect', this, r, rowIndex) !== false){
15127             
15128             if(!this.multiple){
15129                 Roo.each(this.touchViewListGroup.select('.list-group-item > .roo-combobox-list-group-item-box > input:checked', true).elements, function(c){
15130                     c.dom.removeAttribute('checked');
15131                 }, this);
15132
15133                 row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
15134
15135                 this.setFromData(r.data);
15136
15137                 var close = this.closeTriggerEl();
15138
15139                 if(close){
15140                     close.show();
15141                 }
15142
15143                 this.hideTouchView();
15144
15145                 this.fireEvent('select', this, r, rowIndex);
15146
15147                 return;
15148             }
15149
15150             if(this.valueField && typeof(r.data[this.valueField]) != 'undefined' && this.getValue().indexOf(r.data[this.valueField]) != -1){
15151                 row.select('.roo-combobox-list-group-item-box > input', true).first().dom.removeAttribute('checked');
15152                 this.tickItems.splice(this.tickItems.indexOf(r.data), 1);
15153                 return;
15154             }
15155
15156             row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
15157             this.addItem(r.data);
15158             this.tickItems.push(r.data);
15159         }
15160     },
15161     
15162     getAutoCreateNativeIOS : function()
15163     {
15164         var cfg = {
15165             cls: 'form-group' //input-group,
15166         };
15167         
15168         var combobox =  {
15169             tag: 'select',
15170             cls : 'roo-ios-select'
15171         };
15172         
15173         if (this.name) {
15174             combobox.name = this.name;
15175         }
15176         
15177         if (this.disabled) {
15178             combobox.disabled = true;
15179         }
15180         
15181         var settings = this;
15182         
15183         ['xs','sm','md','lg'].map(function(size){
15184             if (settings[size]) {
15185                 cfg.cls += ' col-' + size + '-' + settings[size];
15186             }
15187         });
15188         
15189         cfg.cn = combobox;
15190         
15191         return cfg;
15192         
15193     },
15194     
15195     initIOSView : function()
15196     {
15197         this.store.on('load', this.onIOSViewLoad, this);
15198         
15199         return;
15200     },
15201     
15202     onIOSViewLoad : function()
15203     {
15204         if(this.store.getCount() < 1){
15205             return;
15206         }
15207         
15208         this.clearIOSView();
15209         
15210         if(this.allowBlank) {
15211             
15212             var default_text = '-- SELECT --';
15213             
15214             var opt = this.inputEl().createChild({
15215                 tag: 'option',
15216                 value : 0,
15217                 html : default_text
15218             });
15219             
15220             var o = {};
15221             o[this.valueField] = 0;
15222             o[this.displayField] = default_text;
15223             
15224             this.ios_options.push({
15225                 data : o,
15226                 el : opt
15227             });
15228             
15229         }
15230         
15231         this.store.data.each(function(d, rowIndex){
15232             
15233             var html = '';
15234             
15235             if(this.displayField && typeof(d.data[this.displayField]) != 'undefined'){
15236                 html = d.data[this.displayField];
15237             }
15238             
15239             var value = '';
15240             
15241             if(this.valueField && typeof(d.data[this.valueField]) != 'undefined'){
15242                 value = d.data[this.valueField];
15243             }
15244             
15245             var option = {
15246                 tag: 'option',
15247                 value : value,
15248                 html : html
15249             };
15250             
15251             if(this.value == d.data[this.valueField]){
15252                 option['selected'] = true;
15253             }
15254             
15255             var opt = this.inputEl().createChild(option);
15256             
15257             this.ios_options.push({
15258                 data : d.data,
15259                 el : opt
15260             });
15261             
15262         }, this);
15263         
15264         this.inputEl().on('change', function(){
15265            this.fireEvent('select', this);
15266         }, this);
15267         
15268     },
15269     
15270     clearIOSView: function()
15271     {
15272         this.inputEl().dom.innerHTML = '';
15273         
15274         this.ios_options = [];
15275     },
15276     
15277     setIOSValue: function(v)
15278     {
15279         this.value = v;
15280         
15281         if(!this.ios_options){
15282             return;
15283         }
15284         
15285         Roo.each(this.ios_options, function(opts){
15286            
15287            opts.el.dom.removeAttribute('selected');
15288            
15289            if(opts.data[this.valueField] != v){
15290                return;
15291            }
15292            
15293            opts.el.dom.setAttribute('selected', true);
15294            
15295         }, this);
15296     }
15297
15298     /** 
15299     * @cfg {Boolean} grow 
15300     * @hide 
15301     */
15302     /** 
15303     * @cfg {Number} growMin 
15304     * @hide 
15305     */
15306     /** 
15307     * @cfg {Number} growMax 
15308     * @hide 
15309     */
15310     /**
15311      * @hide
15312      * @method autoSize
15313      */
15314 });
15315
15316 Roo.apply(Roo.bootstrap.ComboBox,  {
15317     
15318     header : {
15319         tag: 'div',
15320         cls: 'modal-header',
15321         cn: [
15322             {
15323                 tag: 'h4',
15324                 cls: 'modal-title'
15325             }
15326         ]
15327     },
15328     
15329     body : {
15330         tag: 'div',
15331         cls: 'modal-body',
15332         cn: [
15333             {
15334                 tag: 'ul',
15335                 cls: 'list-group'
15336             }
15337         ]
15338     },
15339     
15340     listItemRadio : {
15341         tag: 'li',
15342         cls: 'list-group-item',
15343         cn: [
15344             {
15345                 tag: 'span',
15346                 cls: 'roo-combobox-list-group-item-value'
15347             },
15348             {
15349                 tag: 'div',
15350                 cls: 'roo-combobox-list-group-item-box pull-xs-right radio-inline radio radio-info',
15351                 cn: [
15352                     {
15353                         tag: 'input',
15354                         type: 'radio'
15355                     },
15356                     {
15357                         tag: 'label'
15358                     }
15359                 ]
15360             }
15361         ]
15362     },
15363     
15364     listItemCheckbox : {
15365         tag: 'li',
15366         cls: 'list-group-item',
15367         cn: [
15368             {
15369                 tag: 'span',
15370                 cls: 'roo-combobox-list-group-item-value'
15371             },
15372             {
15373                 tag: 'div',
15374                 cls: 'roo-combobox-list-group-item-box pull-xs-right checkbox-inline checkbox checkbox-info',
15375                 cn: [
15376                     {
15377                         tag: 'input',
15378                         type: 'checkbox'
15379                     },
15380                     {
15381                         tag: 'label'
15382                     }
15383                 ]
15384             }
15385         ]
15386     },
15387     
15388     emptyResult : {
15389         tag: 'div',
15390         cls: 'alert alert-danger roo-combobox-touch-view-empty-result'
15391     },
15392     
15393     footer : {
15394         tag: 'div',
15395         cls: 'modal-footer',
15396         cn: [
15397             {
15398                 tag: 'div',
15399                 cls: 'row',
15400                 cn: [
15401                     {
15402                         tag: 'div',
15403                         cls: 'col-xs-6 text-left',
15404                         cn: {
15405                             tag: 'button',
15406                             cls: 'btn btn-danger roo-touch-view-cancel',
15407                             html: 'Cancel'
15408                         }
15409                     },
15410                     {
15411                         tag: 'div',
15412                         cls: 'col-xs-6 text-right',
15413                         cn: {
15414                             tag: 'button',
15415                             cls: 'btn btn-success roo-touch-view-ok',
15416                             html: 'OK'
15417                         }
15418                     }
15419                 ]
15420             }
15421         ]
15422         
15423     }
15424 });
15425
15426 Roo.apply(Roo.bootstrap.ComboBox,  {
15427     
15428     touchViewTemplate : {
15429         tag: 'div',
15430         cls: 'modal fade roo-combobox-touch-view',
15431         cn: [
15432             {
15433                 tag: 'div',
15434                 cls: 'modal-dialog',
15435                 style : 'position:fixed', // we have to fix position....
15436                 cn: [
15437                     {
15438                         tag: 'div',
15439                         cls: 'modal-content',
15440                         cn: [
15441                             Roo.bootstrap.ComboBox.header,
15442                             Roo.bootstrap.ComboBox.body,
15443                             Roo.bootstrap.ComboBox.footer
15444                         ]
15445                     }
15446                 ]
15447             }
15448         ]
15449     }
15450 });/*
15451  * Based on:
15452  * Ext JS Library 1.1.1
15453  * Copyright(c) 2006-2007, Ext JS, LLC.
15454  *
15455  * Originally Released Under LGPL - original licence link has changed is not relivant.
15456  *
15457  * Fork - LGPL
15458  * <script type="text/javascript">
15459  */
15460
15461 /**
15462  * @class Roo.View
15463  * @extends Roo.util.Observable
15464  * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template. 
15465  * This class also supports single and multi selection modes. <br>
15466  * Create a data model bound view:
15467  <pre><code>
15468  var store = new Roo.data.Store(...);
15469
15470  var view = new Roo.View({
15471     el : "my-element",
15472     tpl : '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // auto create template
15473  
15474     singleSelect: true,
15475     selectedClass: "ydataview-selected",
15476     store: store
15477  });
15478
15479  // listen for node click?
15480  view.on("click", function(vw, index, node, e){
15481  alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
15482  });
15483
15484  // load XML data
15485  dataModel.load("foobar.xml");
15486  </code></pre>
15487  For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
15488  * <br><br>
15489  * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
15490  * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
15491  * 
15492  * Note: old style constructor is still suported (container, template, config)
15493  * 
15494  * @constructor
15495  * Create a new View
15496  * @param {Object} config The config object
15497  * 
15498  */
15499 Roo.View = function(config, depreciated_tpl, depreciated_config){
15500     
15501     this.parent = false;
15502     
15503     if (typeof(depreciated_tpl) == 'undefined') {
15504         // new way.. - universal constructor.
15505         Roo.apply(this, config);
15506         this.el  = Roo.get(this.el);
15507     } else {
15508         // old format..
15509         this.el  = Roo.get(config);
15510         this.tpl = depreciated_tpl;
15511         Roo.apply(this, depreciated_config);
15512     }
15513     this.wrapEl  = this.el.wrap().wrap();
15514     ///this.el = this.wrapEla.appendChild(document.createElement("div"));
15515     
15516     
15517     if(typeof(this.tpl) == "string"){
15518         this.tpl = new Roo.Template(this.tpl);
15519     } else {
15520         // support xtype ctors..
15521         this.tpl = new Roo.factory(this.tpl, Roo);
15522     }
15523     
15524     
15525     this.tpl.compile();
15526     
15527     /** @private */
15528     this.addEvents({
15529         /**
15530          * @event beforeclick
15531          * Fires before a click is processed. Returns false to cancel the default action.
15532          * @param {Roo.View} this
15533          * @param {Number} index The index of the target node
15534          * @param {HTMLElement} node The target node
15535          * @param {Roo.EventObject} e The raw event object
15536          */
15537             "beforeclick" : true,
15538         /**
15539          * @event click
15540          * Fires when a template node is clicked.
15541          * @param {Roo.View} this
15542          * @param {Number} index The index of the target node
15543          * @param {HTMLElement} node The target node
15544          * @param {Roo.EventObject} e The raw event object
15545          */
15546             "click" : true,
15547         /**
15548          * @event dblclick
15549          * Fires when a template node is double clicked.
15550          * @param {Roo.View} this
15551          * @param {Number} index The index of the target node
15552          * @param {HTMLElement} node The target node
15553          * @param {Roo.EventObject} e The raw event object
15554          */
15555             "dblclick" : true,
15556         /**
15557          * @event contextmenu
15558          * Fires when a template node is right clicked.
15559          * @param {Roo.View} this
15560          * @param {Number} index The index of the target node
15561          * @param {HTMLElement} node The target node
15562          * @param {Roo.EventObject} e The raw event object
15563          */
15564             "contextmenu" : true,
15565         /**
15566          * @event selectionchange
15567          * Fires when the selected nodes change.
15568          * @param {Roo.View} this
15569          * @param {Array} selections Array of the selected nodes
15570          */
15571             "selectionchange" : true,
15572     
15573         /**
15574          * @event beforeselect
15575          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
15576          * @param {Roo.View} this
15577          * @param {HTMLElement} node The node to be selected
15578          * @param {Array} selections Array of currently selected nodes
15579          */
15580             "beforeselect" : true,
15581         /**
15582          * @event preparedata
15583          * Fires on every row to render, to allow you to change the data.
15584          * @param {Roo.View} this
15585          * @param {Object} data to be rendered (change this)
15586          */
15587           "preparedata" : true
15588           
15589           
15590         });
15591
15592
15593
15594     this.el.on({
15595         "click": this.onClick,
15596         "dblclick": this.onDblClick,
15597         "contextmenu": this.onContextMenu,
15598         scope:this
15599     });
15600
15601     this.selections = [];
15602     this.nodes = [];
15603     this.cmp = new Roo.CompositeElementLite([]);
15604     if(this.store){
15605         this.store = Roo.factory(this.store, Roo.data);
15606         this.setStore(this.store, true);
15607     }
15608     
15609     if ( this.footer && this.footer.xtype) {
15610            
15611          var fctr = this.wrapEl.appendChild(document.createElement("div"));
15612         
15613         this.footer.dataSource = this.store;
15614         this.footer.container = fctr;
15615         this.footer = Roo.factory(this.footer, Roo);
15616         fctr.insertFirst(this.el);
15617         
15618         // this is a bit insane - as the paging toolbar seems to detach the el..
15619 //        dom.parentNode.parentNode.parentNode
15620          // they get detached?
15621     }
15622     
15623     
15624     Roo.View.superclass.constructor.call(this);
15625     
15626     
15627 };
15628
15629 Roo.extend(Roo.View, Roo.util.Observable, {
15630     
15631      /**
15632      * @cfg {Roo.data.Store} store Data store to load data from.
15633      */
15634     store : false,
15635     
15636     /**
15637      * @cfg {String|Roo.Element} el The container element.
15638      */
15639     el : '',
15640     
15641     /**
15642      * @cfg {String|Roo.Template} tpl The template used by this View 
15643      */
15644     tpl : false,
15645     /**
15646      * @cfg {String} dataName the named area of the template to use as the data area
15647      *                          Works with domtemplates roo-name="name"
15648      */
15649     dataName: false,
15650     /**
15651      * @cfg {String} selectedClass The css class to add to selected nodes
15652      */
15653     selectedClass : "x-view-selected",
15654      /**
15655      * @cfg {String} emptyText The empty text to show when nothing is loaded.
15656      */
15657     emptyText : "",
15658     
15659     /**
15660      * @cfg {String} text to display on mask (default Loading)
15661      */
15662     mask : false,
15663     /**
15664      * @cfg {Boolean} multiSelect Allow multiple selection
15665      */
15666     multiSelect : false,
15667     /**
15668      * @cfg {Boolean} singleSelect Allow single selection
15669      */
15670     singleSelect:  false,
15671     
15672     /**
15673      * @cfg {Boolean} toggleSelect - selecting 
15674      */
15675     toggleSelect : false,
15676     
15677     /**
15678      * @cfg {Boolean} tickable - selecting 
15679      */
15680     tickable : false,
15681     
15682     /**
15683      * Returns the element this view is bound to.
15684      * @return {Roo.Element}
15685      */
15686     getEl : function(){
15687         return this.wrapEl;
15688     },
15689     
15690     
15691
15692     /**
15693      * Refreshes the view. - called by datachanged on the store. - do not call directly.
15694      */
15695     refresh : function(){
15696         //Roo.log('refresh');
15697         var t = this.tpl;
15698         
15699         // if we are using something like 'domtemplate', then
15700         // the what gets used is:
15701         // t.applySubtemplate(NAME, data, wrapping data..)
15702         // the outer template then get' applied with
15703         //     the store 'extra data'
15704         // and the body get's added to the
15705         //      roo-name="data" node?
15706         //      <span class='roo-tpl-{name}'></span> ?????
15707         
15708         
15709         
15710         this.clearSelections();
15711         this.el.update("");
15712         var html = [];
15713         var records = this.store.getRange();
15714         if(records.length < 1) {
15715             
15716             // is this valid??  = should it render a template??
15717             
15718             this.el.update(this.emptyText);
15719             return;
15720         }
15721         var el = this.el;
15722         if (this.dataName) {
15723             this.el.update(t.apply(this.store.meta)); //????
15724             el = this.el.child('.roo-tpl-' + this.dataName);
15725         }
15726         
15727         for(var i = 0, len = records.length; i < len; i++){
15728             var data = this.prepareData(records[i].data, i, records[i]);
15729             this.fireEvent("preparedata", this, data, i, records[i]);
15730             
15731             var d = Roo.apply({}, data);
15732             
15733             if(this.tickable){
15734                 Roo.apply(d, {'roo-id' : Roo.id()});
15735                 
15736                 var _this = this;
15737             
15738                 Roo.each(this.parent.item, function(item){
15739                     if(item[_this.parent.valueField] != data[_this.parent.valueField]){
15740                         return;
15741                     }
15742                     Roo.apply(d, {'roo-data-checked' : 'checked'});
15743                 });
15744             }
15745             
15746             html[html.length] = Roo.util.Format.trim(
15747                 this.dataName ?
15748                     t.applySubtemplate(this.dataName, d, this.store.meta) :
15749                     t.apply(d)
15750             );
15751         }
15752         
15753         
15754         
15755         el.update(html.join(""));
15756         this.nodes = el.dom.childNodes;
15757         this.updateIndexes(0);
15758     },
15759     
15760
15761     /**
15762      * Function to override to reformat the data that is sent to
15763      * the template for each node.
15764      * DEPRICATED - use the preparedata event handler.
15765      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
15766      * a JSON object for an UpdateManager bound view).
15767      */
15768     prepareData : function(data, index, record)
15769     {
15770         this.fireEvent("preparedata", this, data, index, record);
15771         return data;
15772     },
15773
15774     onUpdate : function(ds, record){
15775         // Roo.log('on update');   
15776         this.clearSelections();
15777         var index = this.store.indexOf(record);
15778         var n = this.nodes[index];
15779         this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
15780         n.parentNode.removeChild(n);
15781         this.updateIndexes(index, index);
15782     },
15783
15784     
15785     
15786 // --------- FIXME     
15787     onAdd : function(ds, records, index)
15788     {
15789         //Roo.log(['on Add', ds, records, index] );        
15790         this.clearSelections();
15791         if(this.nodes.length == 0){
15792             this.refresh();
15793             return;
15794         }
15795         var n = this.nodes[index];
15796         for(var i = 0, len = records.length; i < len; i++){
15797             var d = this.prepareData(records[i].data, i, records[i]);
15798             if(n){
15799                 this.tpl.insertBefore(n, d);
15800             }else{
15801                 
15802                 this.tpl.append(this.el, d);
15803             }
15804         }
15805         this.updateIndexes(index);
15806     },
15807
15808     onRemove : function(ds, record, index){
15809        // Roo.log('onRemove');
15810         this.clearSelections();
15811         var el = this.dataName  ?
15812             this.el.child('.roo-tpl-' + this.dataName) :
15813             this.el; 
15814         
15815         el.dom.removeChild(this.nodes[index]);
15816         this.updateIndexes(index);
15817     },
15818
15819     /**
15820      * Refresh an individual node.
15821      * @param {Number} index
15822      */
15823     refreshNode : function(index){
15824         this.onUpdate(this.store, this.store.getAt(index));
15825     },
15826
15827     updateIndexes : function(startIndex, endIndex){
15828         var ns = this.nodes;
15829         startIndex = startIndex || 0;
15830         endIndex = endIndex || ns.length - 1;
15831         for(var i = startIndex; i <= endIndex; i++){
15832             ns[i].nodeIndex = i;
15833         }
15834     },
15835
15836     /**
15837      * Changes the data store this view uses and refresh the view.
15838      * @param {Store} store
15839      */
15840     setStore : function(store, initial){
15841         if(!initial && this.store){
15842             this.store.un("datachanged", this.refresh);
15843             this.store.un("add", this.onAdd);
15844             this.store.un("remove", this.onRemove);
15845             this.store.un("update", this.onUpdate);
15846             this.store.un("clear", this.refresh);
15847             this.store.un("beforeload", this.onBeforeLoad);
15848             this.store.un("load", this.onLoad);
15849             this.store.un("loadexception", this.onLoad);
15850         }
15851         if(store){
15852           
15853             store.on("datachanged", this.refresh, this);
15854             store.on("add", this.onAdd, this);
15855             store.on("remove", this.onRemove, this);
15856             store.on("update", this.onUpdate, this);
15857             store.on("clear", this.refresh, this);
15858             store.on("beforeload", this.onBeforeLoad, this);
15859             store.on("load", this.onLoad, this);
15860             store.on("loadexception", this.onLoad, this);
15861         }
15862         
15863         if(store){
15864             this.refresh();
15865         }
15866     },
15867     /**
15868      * onbeforeLoad - masks the loading area.
15869      *
15870      */
15871     onBeforeLoad : function(store,opts)
15872     {
15873          //Roo.log('onBeforeLoad');   
15874         if (!opts.add) {
15875             this.el.update("");
15876         }
15877         this.el.mask(this.mask ? this.mask : "Loading" ); 
15878     },
15879     onLoad : function ()
15880     {
15881         this.el.unmask();
15882     },
15883     
15884
15885     /**
15886      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
15887      * @param {HTMLElement} node
15888      * @return {HTMLElement} The template node
15889      */
15890     findItemFromChild : function(node){
15891         var el = this.dataName  ?
15892             this.el.child('.roo-tpl-' + this.dataName,true) :
15893             this.el.dom; 
15894         
15895         if(!node || node.parentNode == el){
15896                     return node;
15897             }
15898             var p = node.parentNode;
15899             while(p && p != el){
15900             if(p.parentNode == el){
15901                 return p;
15902             }
15903             p = p.parentNode;
15904         }
15905             return null;
15906     },
15907
15908     /** @ignore */
15909     onClick : function(e){
15910         var item = this.findItemFromChild(e.getTarget());
15911         if(item){
15912             var index = this.indexOf(item);
15913             if(this.onItemClick(item, index, e) !== false){
15914                 this.fireEvent("click", this, index, item, e);
15915             }
15916         }else{
15917             this.clearSelections();
15918         }
15919     },
15920
15921     /** @ignore */
15922     onContextMenu : function(e){
15923         var item = this.findItemFromChild(e.getTarget());
15924         if(item){
15925             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
15926         }
15927     },
15928
15929     /** @ignore */
15930     onDblClick : function(e){
15931         var item = this.findItemFromChild(e.getTarget());
15932         if(item){
15933             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
15934         }
15935     },
15936
15937     onItemClick : function(item, index, e)
15938     {
15939         if(this.fireEvent("beforeclick", this, index, item, e) === false){
15940             return false;
15941         }
15942         if (this.toggleSelect) {
15943             var m = this.isSelected(item) ? 'unselect' : 'select';
15944             //Roo.log(m);
15945             var _t = this;
15946             _t[m](item, true, false);
15947             return true;
15948         }
15949         if(this.multiSelect || this.singleSelect){
15950             if(this.multiSelect && e.shiftKey && this.lastSelection){
15951                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
15952             }else{
15953                 this.select(item, this.multiSelect && e.ctrlKey);
15954                 this.lastSelection = item;
15955             }
15956             
15957             if(!this.tickable){
15958                 e.preventDefault();
15959             }
15960             
15961         }
15962         return true;
15963     },
15964
15965     /**
15966      * Get the number of selected nodes.
15967      * @return {Number}
15968      */
15969     getSelectionCount : function(){
15970         return this.selections.length;
15971     },
15972
15973     /**
15974      * Get the currently selected nodes.
15975      * @return {Array} An array of HTMLElements
15976      */
15977     getSelectedNodes : function(){
15978         return this.selections;
15979     },
15980
15981     /**
15982      * Get the indexes of the selected nodes.
15983      * @return {Array}
15984      */
15985     getSelectedIndexes : function(){
15986         var indexes = [], s = this.selections;
15987         for(var i = 0, len = s.length; i < len; i++){
15988             indexes.push(s[i].nodeIndex);
15989         }
15990         return indexes;
15991     },
15992
15993     /**
15994      * Clear all selections
15995      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
15996      */
15997     clearSelections : function(suppressEvent){
15998         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
15999             this.cmp.elements = this.selections;
16000             this.cmp.removeClass(this.selectedClass);
16001             this.selections = [];
16002             if(!suppressEvent){
16003                 this.fireEvent("selectionchange", this, this.selections);
16004             }
16005         }
16006     },
16007
16008     /**
16009      * Returns true if the passed node is selected
16010      * @param {HTMLElement/Number} node The node or node index
16011      * @return {Boolean}
16012      */
16013     isSelected : function(node){
16014         var s = this.selections;
16015         if(s.length < 1){
16016             return false;
16017         }
16018         node = this.getNode(node);
16019         return s.indexOf(node) !== -1;
16020     },
16021
16022     /**
16023      * Selects nodes.
16024      * @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
16025      * @param {Boolean} keepExisting (optional) true to keep existing selections
16026      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
16027      */
16028     select : function(nodeInfo, keepExisting, suppressEvent){
16029         if(nodeInfo instanceof Array){
16030             if(!keepExisting){
16031                 this.clearSelections(true);
16032             }
16033             for(var i = 0, len = nodeInfo.length; i < len; i++){
16034                 this.select(nodeInfo[i], true, true);
16035             }
16036             return;
16037         } 
16038         var node = this.getNode(nodeInfo);
16039         if(!node || this.isSelected(node)){
16040             return; // already selected.
16041         }
16042         if(!keepExisting){
16043             this.clearSelections(true);
16044         }
16045         
16046         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
16047             Roo.fly(node).addClass(this.selectedClass);
16048             this.selections.push(node);
16049             if(!suppressEvent){
16050                 this.fireEvent("selectionchange", this, this.selections);
16051             }
16052         }
16053         
16054         
16055     },
16056       /**
16057      * Unselects nodes.
16058      * @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
16059      * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
16060      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
16061      */
16062     unselect : function(nodeInfo, keepExisting, suppressEvent)
16063     {
16064         if(nodeInfo instanceof Array){
16065             Roo.each(this.selections, function(s) {
16066                 this.unselect(s, nodeInfo);
16067             }, this);
16068             return;
16069         }
16070         var node = this.getNode(nodeInfo);
16071         if(!node || !this.isSelected(node)){
16072             //Roo.log("not selected");
16073             return; // not selected.
16074         }
16075         // fireevent???
16076         var ns = [];
16077         Roo.each(this.selections, function(s) {
16078             if (s == node ) {
16079                 Roo.fly(node).removeClass(this.selectedClass);
16080
16081                 return;
16082             }
16083             ns.push(s);
16084         },this);
16085         
16086         this.selections= ns;
16087         this.fireEvent("selectionchange", this, this.selections);
16088     },
16089
16090     /**
16091      * Gets a template node.
16092      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
16093      * @return {HTMLElement} The node or null if it wasn't found
16094      */
16095     getNode : function(nodeInfo){
16096         if(typeof nodeInfo == "string"){
16097             return document.getElementById(nodeInfo);
16098         }else if(typeof nodeInfo == "number"){
16099             return this.nodes[nodeInfo];
16100         }
16101         return nodeInfo;
16102     },
16103
16104     /**
16105      * Gets a range template nodes.
16106      * @param {Number} startIndex
16107      * @param {Number} endIndex
16108      * @return {Array} An array of nodes
16109      */
16110     getNodes : function(start, end){
16111         var ns = this.nodes;
16112         start = start || 0;
16113         end = typeof end == "undefined" ? ns.length - 1 : end;
16114         var nodes = [];
16115         if(start <= end){
16116             for(var i = start; i <= end; i++){
16117                 nodes.push(ns[i]);
16118             }
16119         } else{
16120             for(var i = start; i >= end; i--){
16121                 nodes.push(ns[i]);
16122             }
16123         }
16124         return nodes;
16125     },
16126
16127     /**
16128      * Finds the index of the passed node
16129      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
16130      * @return {Number} The index of the node or -1
16131      */
16132     indexOf : function(node){
16133         node = this.getNode(node);
16134         if(typeof node.nodeIndex == "number"){
16135             return node.nodeIndex;
16136         }
16137         var ns = this.nodes;
16138         for(var i = 0, len = ns.length; i < len; i++){
16139             if(ns[i] == node){
16140                 return i;
16141             }
16142         }
16143         return -1;
16144     }
16145 });
16146 /*
16147  * - LGPL
16148  *
16149  * based on jquery fullcalendar
16150  * 
16151  */
16152
16153 Roo.bootstrap = Roo.bootstrap || {};
16154 /**
16155  * @class Roo.bootstrap.Calendar
16156  * @extends Roo.bootstrap.Component
16157  * Bootstrap Calendar class
16158  * @cfg {Boolean} loadMask (true|false) default false
16159  * @cfg {Object} header generate the user specific header of the calendar, default false
16160
16161  * @constructor
16162  * Create a new Container
16163  * @param {Object} config The config object
16164  */
16165
16166
16167
16168 Roo.bootstrap.Calendar = function(config){
16169     Roo.bootstrap.Calendar.superclass.constructor.call(this, config);
16170      this.addEvents({
16171         /**
16172              * @event select
16173              * Fires when a date is selected
16174              * @param {DatePicker} this
16175              * @param {Date} date The selected date
16176              */
16177         'select': true,
16178         /**
16179              * @event monthchange
16180              * Fires when the displayed month changes 
16181              * @param {DatePicker} this
16182              * @param {Date} date The selected month
16183              */
16184         'monthchange': true,
16185         /**
16186              * @event evententer
16187              * Fires when mouse over an event
16188              * @param {Calendar} this
16189              * @param {event} Event
16190              */
16191         'evententer': true,
16192         /**
16193              * @event eventleave
16194              * Fires when the mouse leaves an
16195              * @param {Calendar} this
16196              * @param {event}
16197              */
16198         'eventleave': true,
16199         /**
16200              * @event eventclick
16201              * Fires when the mouse click an
16202              * @param {Calendar} this
16203              * @param {event}
16204              */
16205         'eventclick': true
16206         
16207     });
16208
16209 };
16210
16211 Roo.extend(Roo.bootstrap.Calendar, Roo.bootstrap.Component,  {
16212     
16213      /**
16214      * @cfg {Number} startDay
16215      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
16216      */
16217     startDay : 0,
16218     
16219     loadMask : false,
16220     
16221     header : false,
16222       
16223     getAutoCreate : function(){
16224         
16225         
16226         var fc_button = function(name, corner, style, content ) {
16227             return Roo.apply({},{
16228                 tag : 'span',
16229                 cls : 'fc-button fc-button-'+name+' fc-state-default ' + 
16230                          (corner.length ?
16231                             'fc-corner-' + corner.split(' ').join(' fc-corner-') :
16232                             ''
16233                         ),
16234                 html : '<SPAN class="fc-text-'+style+ '">'+content +'</SPAN>',
16235                 unselectable: 'on'
16236             });
16237         };
16238         
16239         var header = {};
16240         
16241         if(!this.header){
16242             header = {
16243                 tag : 'table',
16244                 cls : 'fc-header',
16245                 style : 'width:100%',
16246                 cn : [
16247                     {
16248                         tag: 'tr',
16249                         cn : [
16250                             {
16251                                 tag : 'td',
16252                                 cls : 'fc-header-left',
16253                                 cn : [
16254                                     fc_button('prev', 'left', 'arrow', '&#8249;' ),
16255                                     fc_button('next', 'right', 'arrow', '&#8250;' ),
16256                                     { tag: 'span', cls: 'fc-header-space' },
16257                                     fc_button('today', 'left right', '', 'today' )  // neds state disabled..
16258
16259
16260                                 ]
16261                             },
16262
16263                             {
16264                                 tag : 'td',
16265                                 cls : 'fc-header-center',
16266                                 cn : [
16267                                     {
16268                                         tag: 'span',
16269                                         cls: 'fc-header-title',
16270                                         cn : {
16271                                             tag: 'H2',
16272                                             html : 'month / year'
16273                                         }
16274                                     }
16275
16276                                 ]
16277                             },
16278                             {
16279                                 tag : 'td',
16280                                 cls : 'fc-header-right',
16281                                 cn : [
16282                               /*      fc_button('month', 'left', '', 'month' ),
16283                                     fc_button('week', '', '', 'week' ),
16284                                     fc_button('day', 'right', '', 'day' )
16285                                 */    
16286
16287                                 ]
16288                             }
16289
16290                         ]
16291                     }
16292                 ]
16293             };
16294         }
16295         
16296         header = this.header;
16297         
16298        
16299         var cal_heads = function() {
16300             var ret = [];
16301             // fixme - handle this.
16302             
16303             for (var i =0; i < Date.dayNames.length; i++) {
16304                 var d = Date.dayNames[i];
16305                 ret.push({
16306                     tag: 'th',
16307                     cls : 'fc-day-header fc-' + d.substring(0,3).toLowerCase() + ' fc-widget-header',
16308                     html : d.substring(0,3)
16309                 });
16310                 
16311             }
16312             ret[0].cls += ' fc-first';
16313             ret[6].cls += ' fc-last';
16314             return ret;
16315         };
16316         var cal_cell = function(n) {
16317             return  {
16318                 tag: 'td',
16319                 cls : 'fc-day fc-'+n + ' fc-widget-content', ///fc-other-month fc-past
16320                 cn : [
16321                     {
16322                         cn : [
16323                             {
16324                                 cls: 'fc-day-number',
16325                                 html: 'D'
16326                             },
16327                             {
16328                                 cls: 'fc-day-content',
16329                              
16330                                 cn : [
16331                                      {
16332                                         style: 'position: relative;' // height: 17px;
16333                                     }
16334                                 ]
16335                             }
16336                             
16337                             
16338                         ]
16339                     }
16340                 ]
16341                 
16342             }
16343         };
16344         var cal_rows = function() {
16345             
16346             var ret = [];
16347             for (var r = 0; r < 6; r++) {
16348                 var row= {
16349                     tag : 'tr',
16350                     cls : 'fc-week',
16351                     cn : []
16352                 };
16353                 
16354                 for (var i =0; i < Date.dayNames.length; i++) {
16355                     var d = Date.dayNames[i];
16356                     row.cn.push(cal_cell(d.substring(0,3).toLowerCase()));
16357
16358                 }
16359                 row.cn[0].cls+=' fc-first';
16360                 row.cn[0].cn[0].style = 'min-height:90px';
16361                 row.cn[6].cls+=' fc-last';
16362                 ret.push(row);
16363                 
16364             }
16365             ret[0].cls += ' fc-first';
16366             ret[4].cls += ' fc-prev-last';
16367             ret[5].cls += ' fc-last';
16368             return ret;
16369             
16370         };
16371         
16372         var cal_table = {
16373             tag: 'table',
16374             cls: 'fc-border-separate',
16375             style : 'width:100%',
16376             cellspacing  : 0,
16377             cn : [
16378                 { 
16379                     tag: 'thead',
16380                     cn : [
16381                         { 
16382                             tag: 'tr',
16383                             cls : 'fc-first fc-last',
16384                             cn : cal_heads()
16385                         }
16386                     ]
16387                 },
16388                 { 
16389                     tag: 'tbody',
16390                     cn : cal_rows()
16391                 }
16392                   
16393             ]
16394         };
16395          
16396          var cfg = {
16397             cls : 'fc fc-ltr',
16398             cn : [
16399                 header,
16400                 {
16401                     cls : 'fc-content',
16402                     style : "position: relative;",
16403                     cn : [
16404                         {
16405                             cls : 'fc-view fc-view-month fc-grid',
16406                             style : 'position: relative',
16407                             unselectable : 'on',
16408                             cn : [
16409                                 {
16410                                     cls : 'fc-event-container',
16411                                     style : 'position:absolute;z-index:8;top:0;left:0;'
16412                                 },
16413                                 cal_table
16414                             ]
16415                         }
16416                     ]
16417     
16418                 }
16419            ] 
16420             
16421         };
16422         
16423          
16424         
16425         return cfg;
16426     },
16427     
16428     
16429     initEvents : function()
16430     {
16431         if(!this.store){
16432             throw "can not find store for calendar";
16433         }
16434         
16435         var mark = {
16436             tag: "div",
16437             cls:"x-dlg-mask",
16438             style: "text-align:center",
16439             cn: [
16440                 {
16441                     tag: "div",
16442                     style: "background-color:white;width:50%;margin:250 auto",
16443                     cn: [
16444                         {
16445                             tag: "img",
16446                             src: Roo.rootURL + '/images/ux/lightbox/loading.gif' 
16447                         },
16448                         {
16449                             tag: "span",
16450                             html: "Loading"
16451                         }
16452                         
16453                     ]
16454                 }
16455             ]
16456         };
16457         this.maskEl = Roo.DomHelper.append(this.el.select('.fc-content', true).first(), mark, true);
16458         
16459         var size = this.el.select('.fc-content', true).first().getSize();
16460         this.maskEl.setSize(size.width, size.height);
16461         this.maskEl.enableDisplayMode("block");
16462         if(!this.loadMask){
16463             this.maskEl.hide();
16464         }
16465         
16466         this.store = Roo.factory(this.store, Roo.data);
16467         this.store.on('load', this.onLoad, this);
16468         this.store.on('beforeload', this.onBeforeLoad, this);
16469         
16470         this.resize();
16471         
16472         this.cells = this.el.select('.fc-day',true);
16473         //Roo.log(this.cells);
16474         this.textNodes = this.el.query('.fc-day-number');
16475         this.cells.addClassOnOver('fc-state-hover');
16476         
16477         this.el.select('.fc-button-prev',true).on('click', this.showPrevMonth, this);
16478         this.el.select('.fc-button-next',true).on('click', this.showNextMonth, this);
16479         this.el.select('.fc-button-today',true).on('click', this.showToday, this);
16480         this.el.select('.fc-button',true).addClassOnOver('fc-state-hover');
16481         
16482         this.on('monthchange', this.onMonthChange, this);
16483         
16484         this.update(new Date().clearTime());
16485     },
16486     
16487     resize : function() {
16488         var sz  = this.el.getSize();
16489         
16490         this.el.select('.fc-day-header',true).setWidth(sz.width / 7);
16491         this.el.select('.fc-day-content div',true).setHeight(34);
16492     },
16493     
16494     
16495     // private
16496     showPrevMonth : function(e){
16497         this.update(this.activeDate.add("mo", -1));
16498     },
16499     showToday : function(e){
16500         this.update(new Date().clearTime());
16501     },
16502     // private
16503     showNextMonth : function(e){
16504         this.update(this.activeDate.add("mo", 1));
16505     },
16506
16507     // private
16508     showPrevYear : function(){
16509         this.update(this.activeDate.add("y", -1));
16510     },
16511
16512     // private
16513     showNextYear : function(){
16514         this.update(this.activeDate.add("y", 1));
16515     },
16516
16517     
16518    // private
16519     update : function(date)
16520     {
16521         var vd = this.activeDate;
16522         this.activeDate = date;
16523 //        if(vd && this.el){
16524 //            var t = date.getTime();
16525 //            if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
16526 //                Roo.log('using add remove');
16527 //                
16528 //                this.fireEvent('monthchange', this, date);
16529 //                
16530 //                this.cells.removeClass("fc-state-highlight");
16531 //                this.cells.each(function(c){
16532 //                   if(c.dateValue == t){
16533 //                       c.addClass("fc-state-highlight");
16534 //                       setTimeout(function(){
16535 //                            try{c.dom.firstChild.focus();}catch(e){}
16536 //                       }, 50);
16537 //                       return false;
16538 //                   }
16539 //                   return true;
16540 //                });
16541 //                return;
16542 //            }
16543 //        }
16544         
16545         var days = date.getDaysInMonth();
16546         
16547         var firstOfMonth = date.getFirstDateOfMonth();
16548         var startingPos = firstOfMonth.getDay()-this.startDay;
16549         
16550         if(startingPos < this.startDay){
16551             startingPos += 7;
16552         }
16553         
16554         var pm = date.add(Date.MONTH, -1);
16555         var prevStart = pm.getDaysInMonth()-startingPos;
16556 //        
16557         this.cells = this.el.select('.fc-day',true);
16558         this.textNodes = this.el.query('.fc-day-number');
16559         this.cells.addClassOnOver('fc-state-hover');
16560         
16561         var cells = this.cells.elements;
16562         var textEls = this.textNodes;
16563         
16564         Roo.each(cells, function(cell){
16565             cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
16566         });
16567         
16568         days += startingPos;
16569
16570         // convert everything to numbers so it's fast
16571         var day = 86400000;
16572         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
16573         //Roo.log(d);
16574         //Roo.log(pm);
16575         //Roo.log(prevStart);
16576         
16577         var today = new Date().clearTime().getTime();
16578         var sel = date.clearTime().getTime();
16579         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
16580         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
16581         var ddMatch = this.disabledDatesRE;
16582         var ddText = this.disabledDatesText;
16583         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
16584         var ddaysText = this.disabledDaysText;
16585         var format = this.format;
16586         
16587         var setCellClass = function(cal, cell){
16588             cell.row = 0;
16589             cell.events = [];
16590             cell.more = [];
16591             //Roo.log('set Cell Class');
16592             cell.title = "";
16593             var t = d.getTime();
16594             
16595             //Roo.log(d);
16596             
16597             cell.dateValue = t;
16598             if(t == today){
16599                 cell.className += " fc-today";
16600                 cell.className += " fc-state-highlight";
16601                 cell.title = cal.todayText;
16602             }
16603             if(t == sel){
16604                 // disable highlight in other month..
16605                 //cell.className += " fc-state-highlight";
16606                 
16607             }
16608             // disabling
16609             if(t < min) {
16610                 cell.className = " fc-state-disabled";
16611                 cell.title = cal.minText;
16612                 return;
16613             }
16614             if(t > max) {
16615                 cell.className = " fc-state-disabled";
16616                 cell.title = cal.maxText;
16617                 return;
16618             }
16619             if(ddays){
16620                 if(ddays.indexOf(d.getDay()) != -1){
16621                     cell.title = ddaysText;
16622                     cell.className = " fc-state-disabled";
16623                 }
16624             }
16625             if(ddMatch && format){
16626                 var fvalue = d.dateFormat(format);
16627                 if(ddMatch.test(fvalue)){
16628                     cell.title = ddText.replace("%0", fvalue);
16629                     cell.className = " fc-state-disabled";
16630                 }
16631             }
16632             
16633             if (!cell.initialClassName) {
16634                 cell.initialClassName = cell.dom.className;
16635             }
16636             
16637             cell.dom.className = cell.initialClassName  + ' ' +  cell.className;
16638         };
16639
16640         var i = 0;
16641         
16642         for(; i < startingPos; i++) {
16643             textEls[i].innerHTML = (++prevStart);
16644             d.setDate(d.getDate()+1);
16645             
16646             cells[i].className = "fc-past fc-other-month";
16647             setCellClass(this, cells[i]);
16648         }
16649         
16650         var intDay = 0;
16651         
16652         for(; i < days; i++){
16653             intDay = i - startingPos + 1;
16654             textEls[i].innerHTML = (intDay);
16655             d.setDate(d.getDate()+1);
16656             
16657             cells[i].className = ''; // "x-date-active";
16658             setCellClass(this, cells[i]);
16659         }
16660         var extraDays = 0;
16661         
16662         for(; i < 42; i++) {
16663             textEls[i].innerHTML = (++extraDays);
16664             d.setDate(d.getDate()+1);
16665             
16666             cells[i].className = "fc-future fc-other-month";
16667             setCellClass(this, cells[i]);
16668         }
16669         
16670         this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
16671         
16672         var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
16673         
16674         this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
16675         this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
16676         
16677         if(totalRows != 6){
16678             this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
16679             this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
16680         }
16681         
16682         this.fireEvent('monthchange', this, date);
16683         
16684         
16685         /*
16686         if(!this.internalRender){
16687             var main = this.el.dom.firstChild;
16688             var w = main.offsetWidth;
16689             this.el.setWidth(w + this.el.getBorderWidth("lr"));
16690             Roo.fly(main).setWidth(w);
16691             this.internalRender = true;
16692             // opera does not respect the auto grow header center column
16693             // then, after it gets a width opera refuses to recalculate
16694             // without a second pass
16695             if(Roo.isOpera && !this.secondPass){
16696                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
16697                 this.secondPass = true;
16698                 this.update.defer(10, this, [date]);
16699             }
16700         }
16701         */
16702         
16703     },
16704     
16705     findCell : function(dt) {
16706         dt = dt.clearTime().getTime();
16707         var ret = false;
16708         this.cells.each(function(c){
16709             //Roo.log("check " +c.dateValue + '?=' + dt);
16710             if(c.dateValue == dt){
16711                 ret = c;
16712                 return false;
16713             }
16714             return true;
16715         });
16716         
16717         return ret;
16718     },
16719     
16720     findCells : function(ev) {
16721         var s = ev.start.clone().clearTime().getTime();
16722        // Roo.log(s);
16723         var e= ev.end.clone().clearTime().getTime();
16724        // Roo.log(e);
16725         var ret = [];
16726         this.cells.each(function(c){
16727              ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
16728             
16729             if(c.dateValue > e){
16730                 return ;
16731             }
16732             if(c.dateValue < s){
16733                 return ;
16734             }
16735             ret.push(c);
16736         });
16737         
16738         return ret;    
16739     },
16740     
16741 //    findBestRow: function(cells)
16742 //    {
16743 //        var ret = 0;
16744 //        
16745 //        for (var i =0 ; i < cells.length;i++) {
16746 //            ret  = Math.max(cells[i].rows || 0,ret);
16747 //        }
16748 //        return ret;
16749 //        
16750 //    },
16751     
16752     
16753     addItem : function(ev)
16754     {
16755         // look for vertical location slot in
16756         var cells = this.findCells(ev);
16757         
16758 //        ev.row = this.findBestRow(cells);
16759         
16760         // work out the location.
16761         
16762         var crow = false;
16763         var rows = [];
16764         for(var i =0; i < cells.length; i++) {
16765             
16766             cells[i].row = cells[0].row;
16767             
16768             if(i == 0){
16769                 cells[i].row = cells[i].row + 1;
16770             }
16771             
16772             if (!crow) {
16773                 crow = {
16774                     start : cells[i],
16775                     end :  cells[i]
16776                 };
16777                 continue;
16778             }
16779             if (crow.start.getY() == cells[i].getY()) {
16780                 // on same row.
16781                 crow.end = cells[i];
16782                 continue;
16783             }
16784             // different row.
16785             rows.push(crow);
16786             crow = {
16787                 start: cells[i],
16788                 end : cells[i]
16789             };
16790             
16791         }
16792         
16793         rows.push(crow);
16794         ev.els = [];
16795         ev.rows = rows;
16796         ev.cells = cells;
16797         
16798         cells[0].events.push(ev);
16799         
16800         this.calevents.push(ev);
16801     },
16802     
16803     clearEvents: function() {
16804         
16805         if(!this.calevents){
16806             return;
16807         }
16808         
16809         Roo.each(this.cells.elements, function(c){
16810             c.row = 0;
16811             c.events = [];
16812             c.more = [];
16813         });
16814         
16815         Roo.each(this.calevents, function(e) {
16816             Roo.each(e.els, function(el) {
16817                 el.un('mouseenter' ,this.onEventEnter, this);
16818                 el.un('mouseleave' ,this.onEventLeave, this);
16819                 el.remove();
16820             },this);
16821         },this);
16822         
16823         Roo.each(Roo.select('.fc-more-event', true).elements, function(e){
16824             e.remove();
16825         });
16826         
16827     },
16828     
16829     renderEvents: function()
16830     {   
16831         var _this = this;
16832         
16833         this.cells.each(function(c) {
16834             
16835             if(c.row < 5){
16836                 return;
16837             }
16838             
16839             var ev = c.events;
16840             
16841             var r = 4;
16842             if(c.row != c.events.length){
16843                 r = 4 - (4 - (c.row - c.events.length));
16844             }
16845             
16846             c.events = ev.slice(0, r);
16847             c.more = ev.slice(r);
16848             
16849             if(c.more.length && c.more.length == 1){
16850                 c.events.push(c.more.pop());
16851             }
16852             
16853             c.row = (c.row - ev.length) + c.events.length + ((c.more.length) ? 1 : 0);
16854             
16855         });
16856             
16857         this.cells.each(function(c) {
16858             
16859             c.select('.fc-day-content div',true).first().setHeight(Math.max(34, c.row * 20));
16860             
16861             
16862             for (var e = 0; e < c.events.length; e++){
16863                 var ev = c.events[e];
16864                 var rows = ev.rows;
16865                 
16866                 for(var i = 0; i < rows.length; i++) {
16867                 
16868                     // how many rows should it span..
16869
16870                     var  cfg = {
16871                         cls : 'roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable',
16872                         style : 'position: absolute', // left: 387px; width: 121px; top: 359px;
16873
16874                         unselectable : "on",
16875                         cn : [
16876                             {
16877                                 cls: 'fc-event-inner',
16878                                 cn : [
16879     //                                {
16880     //                                  tag:'span',
16881     //                                  cls: 'fc-event-time',
16882     //                                  html : cells.length > 1 ? '' : ev.time
16883     //                                },
16884                                     {
16885                                       tag:'span',
16886                                       cls: 'fc-event-title',
16887                                       html : String.format('{0}', ev.title)
16888                                     }
16889
16890
16891                                 ]
16892                             },
16893                             {
16894                                 cls: 'ui-resizable-handle ui-resizable-e',
16895                                 html : '&nbsp;&nbsp;&nbsp'
16896                             }
16897
16898                         ]
16899                     };
16900
16901                     if (i == 0) {
16902                         cfg.cls += ' fc-event-start';
16903                     }
16904                     if ((i+1) == rows.length) {
16905                         cfg.cls += ' fc-event-end';
16906                     }
16907
16908                     var ctr = _this.el.select('.fc-event-container',true).first();
16909                     var cg = ctr.createChild(cfg);
16910
16911                     var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
16912                     var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
16913
16914                     var r = (c.more.length) ? 1 : 0;
16915                     cg.setXY([sbox.x +2, sbox.y + ((c.row - c.events.length - r + e) * 20)]);    
16916                     cg.setWidth(ebox.right - sbox.x -2);
16917
16918                     cg.on('mouseenter' ,_this.onEventEnter, _this, ev);
16919                     cg.on('mouseleave' ,_this.onEventLeave, _this, ev);
16920                     cg.on('click', _this.onEventClick, _this, ev);
16921
16922                     ev.els.push(cg);
16923                     
16924                 }
16925                 
16926             }
16927             
16928             
16929             if(c.more.length){
16930                 var  cfg = {
16931                     cls : 'fc-more-event roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable fc-event-start fc-event-end',
16932                     style : 'position: absolute',
16933                     unselectable : "on",
16934                     cn : [
16935                         {
16936                             cls: 'fc-event-inner',
16937                             cn : [
16938                                 {
16939                                   tag:'span',
16940                                   cls: 'fc-event-title',
16941                                   html : 'More'
16942                                 }
16943
16944
16945                             ]
16946                         },
16947                         {
16948                             cls: 'ui-resizable-handle ui-resizable-e',
16949                             html : '&nbsp;&nbsp;&nbsp'
16950                         }
16951
16952                     ]
16953                 };
16954
16955                 var ctr = _this.el.select('.fc-event-container',true).first();
16956                 var cg = ctr.createChild(cfg);
16957
16958                 var sbox = c.select('.fc-day-content',true).first().getBox();
16959                 var ebox = c.select('.fc-day-content',true).first().getBox();
16960                 //Roo.log(cg);
16961                 cg.setXY([sbox.x +2, sbox.y +((c.row - 1) * 20)]);    
16962                 cg.setWidth(ebox.right - sbox.x -2);
16963
16964                 cg.on('click', _this.onMoreEventClick, _this, c.more);
16965                 
16966             }
16967             
16968         });
16969         
16970         
16971         
16972     },
16973     
16974     onEventEnter: function (e, el,event,d) {
16975         this.fireEvent('evententer', this, el, event);
16976     },
16977     
16978     onEventLeave: function (e, el,event,d) {
16979         this.fireEvent('eventleave', this, el, event);
16980     },
16981     
16982     onEventClick: function (e, el,event,d) {
16983         this.fireEvent('eventclick', this, el, event);
16984     },
16985     
16986     onMonthChange: function () {
16987         this.store.load();
16988     },
16989     
16990     onMoreEventClick: function(e, el, more)
16991     {
16992         var _this = this;
16993         
16994         this.calpopover.placement = 'right';
16995         this.calpopover.setTitle('More');
16996         
16997         this.calpopover.setContent('');
16998         
16999         var ctr = this.calpopover.el.select('.popover-content', true).first();
17000         
17001         Roo.each(more, function(m){
17002             var cfg = {
17003                 cls : 'fc-event-hori fc-event-draggable',
17004                 html : m.title
17005             };
17006             var cg = ctr.createChild(cfg);
17007             
17008             cg.on('click', _this.onEventClick, _this, m);
17009         });
17010         
17011         this.calpopover.show(el);
17012         
17013         
17014     },
17015     
17016     onLoad: function () 
17017     {   
17018         this.calevents = [];
17019         var cal = this;
17020         
17021         if(this.store.getCount() > 0){
17022             this.store.data.each(function(d){
17023                cal.addItem({
17024                     id : d.data.id,
17025                     start: (typeof(d.data.start_dt) === 'string') ? new Date.parseDate(d.data.start_dt, 'Y-m-d H:i:s') : d.data.start_dt,
17026                     end : (typeof(d.data.end_dt) === 'string') ? new Date.parseDate(d.data.end_dt, 'Y-m-d H:i:s') : d.data.end_dt,
17027                     time : d.data.start_time,
17028                     title : d.data.title,
17029                     description : d.data.description,
17030                     venue : d.data.venue
17031                 });
17032             });
17033         }
17034         
17035         this.renderEvents();
17036         
17037         if(this.calevents.length && this.loadMask){
17038             this.maskEl.hide();
17039         }
17040     },
17041     
17042     onBeforeLoad: function()
17043     {
17044         this.clearEvents();
17045         if(this.loadMask){
17046             this.maskEl.show();
17047         }
17048     }
17049 });
17050
17051  
17052  /*
17053  * - LGPL
17054  *
17055  * element
17056  * 
17057  */
17058
17059 /**
17060  * @class Roo.bootstrap.Popover
17061  * @extends Roo.bootstrap.Component
17062  * Bootstrap Popover class
17063  * @cfg {String} html contents of the popover   (or false to use children..)
17064  * @cfg {String} title of popover (or false to hide)
17065  * @cfg {String} placement how it is placed
17066  * @cfg {String} trigger click || hover (or false to trigger manually)
17067  * @cfg {String} over what (parent or false to trigger manually.)
17068  * @cfg {Number} delay - delay before showing
17069  
17070  * @constructor
17071  * Create a new Popover
17072  * @param {Object} config The config object
17073  */
17074
17075 Roo.bootstrap.Popover = function(config){
17076     Roo.bootstrap.Popover.superclass.constructor.call(this, config);
17077     
17078     this.addEvents({
17079         // raw events
17080          /**
17081          * @event show
17082          * After the popover show
17083          * 
17084          * @param {Roo.bootstrap.Popover} this
17085          */
17086         "show" : true,
17087         /**
17088          * @event hide
17089          * After the popover hide
17090          * 
17091          * @param {Roo.bootstrap.Popover} this
17092          */
17093         "hide" : true
17094     });
17095 };
17096
17097 Roo.extend(Roo.bootstrap.Popover, Roo.bootstrap.Component,  {
17098     
17099     title: 'Fill in a title',
17100     html: false,
17101     
17102     placement : 'right',
17103     trigger : 'hover', // hover
17104     
17105     delay : 0,
17106     
17107     over: 'parent',
17108     
17109     can_build_overlaid : false,
17110     
17111     getChildContainer : function()
17112     {
17113         return this.el.select('.popover-content',true).first();
17114     },
17115     
17116     getAutoCreate : function(){
17117          
17118         var cfg = {
17119            cls : 'popover roo-dynamic',
17120            style: 'display:block',
17121            cn : [
17122                 {
17123                     cls : 'arrow'
17124                 },
17125                 {
17126                     cls : 'popover-inner',
17127                     cn : [
17128                         {
17129                             tag: 'h3',
17130                             cls: 'popover-title',
17131                             html : this.title
17132                         },
17133                         {
17134                             cls : 'popover-content',
17135                             html : this.html
17136                         }
17137                     ]
17138                     
17139                 }
17140            ]
17141         };
17142         
17143         return cfg;
17144     },
17145     setTitle: function(str)
17146     {
17147         this.title = str;
17148         this.el.select('.popover-title',true).first().dom.innerHTML = str;
17149     },
17150     setContent: function(str)
17151     {
17152         this.html = str;
17153         this.el.select('.popover-content',true).first().dom.innerHTML = str;
17154     },
17155     // as it get's added to the bottom of the page.
17156     onRender : function(ct, position)
17157     {
17158         Roo.bootstrap.Component.superclass.onRender.call(this, ct, position);
17159         if(!this.el){
17160             var cfg = Roo.apply({},  this.getAutoCreate());
17161             cfg.id = Roo.id();
17162             
17163             if (this.cls) {
17164                 cfg.cls += ' ' + this.cls;
17165             }
17166             if (this.style) {
17167                 cfg.style = this.style;
17168             }
17169             //Roo.log("adding to ");
17170             this.el = Roo.get(document.body).createChild(cfg, position);
17171 //            Roo.log(this.el);
17172         }
17173         this.initEvents();
17174     },
17175     
17176     initEvents : function()
17177     {
17178         this.el.select('.popover-title',true).setVisibilityMode(Roo.Element.DISPLAY);
17179         this.el.enableDisplayMode('block');
17180         this.el.hide();
17181         if (this.over === false) {
17182             return; 
17183         }
17184         if (this.triggers === false) {
17185             return;
17186         }
17187         var on_el = (this.over == 'parent') ? this.parent().el : Roo.get(this.over);
17188         var triggers = this.trigger ? this.trigger.split(' ') : [];
17189         Roo.each(triggers, function(trigger) {
17190         
17191             if (trigger == 'click') {
17192                 on_el.on('click', this.toggle, this);
17193             } else if (trigger != 'manual') {
17194                 var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focusin';
17195                 var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout';
17196       
17197                 on_el.on(eventIn  ,this.enter, this);
17198                 on_el.on(eventOut, this.leave, this);
17199             }
17200         }, this);
17201         
17202     },
17203     
17204     
17205     // private
17206     timeout : null,
17207     hoverState : null,
17208     
17209     toggle : function () {
17210         this.hoverState == 'in' ? this.leave() : this.enter();
17211     },
17212     
17213     enter : function () {
17214         
17215         clearTimeout(this.timeout);
17216     
17217         this.hoverState = 'in';
17218     
17219         if (!this.delay || !this.delay.show) {
17220             this.show();
17221             return;
17222         }
17223         var _t = this;
17224         this.timeout = setTimeout(function () {
17225             if (_t.hoverState == 'in') {
17226                 _t.show();
17227             }
17228         }, this.delay.show)
17229     },
17230     
17231     leave : function() {
17232         clearTimeout(this.timeout);
17233     
17234         this.hoverState = 'out';
17235     
17236         if (!this.delay || !this.delay.hide) {
17237             this.hide();
17238             return;
17239         }
17240         var _t = this;
17241         this.timeout = setTimeout(function () {
17242             if (_t.hoverState == 'out') {
17243                 _t.hide();
17244             }
17245         }, this.delay.hide)
17246     },
17247     
17248     show : function (on_el)
17249     {
17250         if (!on_el) {
17251             on_el= (this.over == 'parent') ? this.parent().el : Roo.get(this.over);
17252         }
17253         
17254         // set content.
17255         this.el.select('.popover-title',true).first().dom.innerHtml = this.title;
17256         if (this.html !== false) {
17257             this.el.select('.popover-content',true).first().dom.innerHtml = this.html;
17258         }
17259         this.el.removeClass(['fade','top','bottom', 'left', 'right','in']);
17260         if (!this.title.length) {
17261             this.el.select('.popover-title',true).hide();
17262         }
17263         
17264         var placement = typeof this.placement == 'function' ?
17265             this.placement.call(this, this.el, on_el) :
17266             this.placement;
17267             
17268         var autoToken = /\s?auto?\s?/i;
17269         var autoPlace = autoToken.test(placement);
17270         if (autoPlace) {
17271             placement = placement.replace(autoToken, '') || 'top';
17272         }
17273         
17274         //this.el.detach()
17275         //this.el.setXY([0,0]);
17276         this.el.show();
17277         this.el.dom.style.display='block';
17278         this.el.addClass(placement);
17279         
17280         //this.el.appendTo(on_el);
17281         
17282         var p = this.getPosition();
17283         var box = this.el.getBox();
17284         
17285         if (autoPlace) {
17286             // fixme..
17287         }
17288         var align = Roo.bootstrap.Popover.alignment[placement];
17289         this.el.alignTo(on_el, align[0],align[1]);
17290         //var arrow = this.el.select('.arrow',true).first();
17291         //arrow.set(align[2], 
17292         
17293         this.el.addClass('in');
17294         
17295         
17296         if (this.el.hasClass('fade')) {
17297             // fade it?
17298         }
17299         
17300         this.hoverState = 'in';
17301         
17302         this.fireEvent('show', this);
17303         
17304     },
17305     hide : function()
17306     {
17307         this.el.setXY([0,0]);
17308         this.el.removeClass('in');
17309         this.el.hide();
17310         this.hoverState = null;
17311         
17312         this.fireEvent('hide', this);
17313     }
17314     
17315 });
17316
17317 Roo.bootstrap.Popover.alignment = {
17318     'left' : ['r-l', [-10,0], 'right'],
17319     'right' : ['l-r', [10,0], 'left'],
17320     'bottom' : ['t-b', [0,10], 'top'],
17321     'top' : [ 'b-t', [0,-10], 'bottom']
17322 };
17323
17324  /*
17325  * - LGPL
17326  *
17327  * Progress
17328  * 
17329  */
17330
17331 /**
17332  * @class Roo.bootstrap.Progress
17333  * @extends Roo.bootstrap.Component
17334  * Bootstrap Progress class
17335  * @cfg {Boolean} striped striped of the progress bar
17336  * @cfg {Boolean} active animated of the progress bar
17337  * 
17338  * 
17339  * @constructor
17340  * Create a new Progress
17341  * @param {Object} config The config object
17342  */
17343
17344 Roo.bootstrap.Progress = function(config){
17345     Roo.bootstrap.Progress.superclass.constructor.call(this, config);
17346 };
17347
17348 Roo.extend(Roo.bootstrap.Progress, Roo.bootstrap.Component,  {
17349     
17350     striped : false,
17351     active: false,
17352     
17353     getAutoCreate : function(){
17354         var cfg = {
17355             tag: 'div',
17356             cls: 'progress'
17357         };
17358         
17359         
17360         if(this.striped){
17361             cfg.cls += ' progress-striped';
17362         }
17363       
17364         if(this.active){
17365             cfg.cls += ' active';
17366         }
17367         
17368         
17369         return cfg;
17370     }
17371    
17372 });
17373
17374  
17375
17376  /*
17377  * - LGPL
17378  *
17379  * ProgressBar
17380  * 
17381  */
17382
17383 /**
17384  * @class Roo.bootstrap.ProgressBar
17385  * @extends Roo.bootstrap.Component
17386  * Bootstrap ProgressBar class
17387  * @cfg {Number} aria_valuenow aria-value now
17388  * @cfg {Number} aria_valuemin aria-value min
17389  * @cfg {Number} aria_valuemax aria-value max
17390  * @cfg {String} label label for the progress bar
17391  * @cfg {String} panel (success | info | warning | danger )
17392  * @cfg {String} role role of the progress bar
17393  * @cfg {String} sr_only text
17394  * 
17395  * 
17396  * @constructor
17397  * Create a new ProgressBar
17398  * @param {Object} config The config object
17399  */
17400
17401 Roo.bootstrap.ProgressBar = function(config){
17402     Roo.bootstrap.ProgressBar.superclass.constructor.call(this, config);
17403 };
17404
17405 Roo.extend(Roo.bootstrap.ProgressBar, Roo.bootstrap.Component,  {
17406     
17407     aria_valuenow : 0,
17408     aria_valuemin : 0,
17409     aria_valuemax : 100,
17410     label : false,
17411     panel : false,
17412     role : false,
17413     sr_only: false,
17414     
17415     getAutoCreate : function()
17416     {
17417         
17418         var cfg = {
17419             tag: 'div',
17420             cls: 'progress-bar',
17421             style: 'width:' + Math.ceil((this.aria_valuenow / this.aria_valuemax) * 100) + '%'
17422         };
17423         
17424         if(this.sr_only){
17425             cfg.cn = {
17426                 tag: 'span',
17427                 cls: 'sr-only',
17428                 html: this.sr_only
17429             }
17430         }
17431         
17432         if(this.role){
17433             cfg.role = this.role;
17434         }
17435         
17436         if(this.aria_valuenow){
17437             cfg['aria-valuenow'] = this.aria_valuenow;
17438         }
17439         
17440         if(this.aria_valuemin){
17441             cfg['aria-valuemin'] = this.aria_valuemin;
17442         }
17443         
17444         if(this.aria_valuemax){
17445             cfg['aria-valuemax'] = this.aria_valuemax;
17446         }
17447         
17448         if(this.label && !this.sr_only){
17449             cfg.html = this.label;
17450         }
17451         
17452         if(this.panel){
17453             cfg.cls += ' progress-bar-' + this.panel;
17454         }
17455         
17456         return cfg;
17457     },
17458     
17459     update : function(aria_valuenow)
17460     {
17461         this.aria_valuenow = aria_valuenow;
17462         
17463         this.el.setStyle('width', Math.ceil((this.aria_valuenow / this.aria_valuemax) * 100) + '%');
17464     }
17465    
17466 });
17467
17468  
17469
17470  /*
17471  * - LGPL
17472  *
17473  * column
17474  * 
17475  */
17476
17477 /**
17478  * @class Roo.bootstrap.TabGroup
17479  * @extends Roo.bootstrap.Column
17480  * Bootstrap Column class
17481  * @cfg {String} navId the navigation id (for use with navbars) - will be auto generated if it does not exist..
17482  * @cfg {Boolean} carousel true to make the group behave like a carousel
17483  * @cfg {Boolean} bullets show bullets for the panels
17484  * @cfg {Boolean} autoslide (true|false) auto slide .. default false
17485  * @cfg {Number} timer auto slide timer .. default 0 millisecond
17486  * @cfg {Boolean} showarrow (true|false) show arrow default true
17487  * 
17488  * @constructor
17489  * Create a new TabGroup
17490  * @param {Object} config The config object
17491  */
17492
17493 Roo.bootstrap.TabGroup = function(config){
17494     Roo.bootstrap.TabGroup.superclass.constructor.call(this, config);
17495     if (!this.navId) {
17496         this.navId = Roo.id();
17497     }
17498     this.tabs = [];
17499     Roo.bootstrap.TabGroup.register(this);
17500     
17501 };
17502
17503 Roo.extend(Roo.bootstrap.TabGroup, Roo.bootstrap.Column,  {
17504     
17505     carousel : false,
17506     transition : false,
17507     bullets : 0,
17508     timer : 0,
17509     autoslide : false,
17510     slideFn : false,
17511     slideOnTouch : false,
17512     showarrow : true,
17513     
17514     getAutoCreate : function()
17515     {
17516         var cfg = Roo.apply({}, Roo.bootstrap.TabGroup.superclass.getAutoCreate.call(this));
17517         
17518         cfg.cls += ' tab-content';
17519         
17520         if (this.carousel) {
17521             cfg.cls += ' carousel slide';
17522             
17523             cfg.cn = [{
17524                cls : 'carousel-inner',
17525                cn : []
17526             }];
17527         
17528             if(this.bullets  && !Roo.isTouch){
17529                 
17530                 var bullets = {
17531                     cls : 'carousel-bullets',
17532                     cn : []
17533                 };
17534                
17535                 if(this.bullets_cls){
17536                     bullets.cls = bullets.cls + ' ' + this.bullets_cls;
17537                 }
17538                 
17539                 bullets.cn.push({
17540                     cls : 'clear'
17541                 });
17542                 
17543                 cfg.cn[0].cn.push(bullets);
17544             }
17545             
17546             if(this.showarrow){
17547                 cfg.cn[0].cn.push({
17548                     tag : 'div',
17549                     class : 'carousel-arrow',
17550                     cn : [
17551                         {
17552                             tag : 'div',
17553                             class : 'carousel-prev',
17554                             cn : [
17555                                 {
17556                                     tag : 'i',
17557                                     class : 'fa fa-chevron-left'
17558                                 }
17559                             ]
17560                         },
17561                         {
17562                             tag : 'div',
17563                             class : 'carousel-next',
17564                             cn : [
17565                                 {
17566                                     tag : 'i',
17567                                     class : 'fa fa-chevron-right'
17568                                 }
17569                             ]
17570                         }
17571                     ]
17572                 });
17573             }
17574             
17575         }
17576         
17577         return cfg;
17578     },
17579     
17580     initEvents:  function()
17581     {
17582 //        if(Roo.isTouch && this.slideOnTouch && !this.showarrow){
17583 //            this.el.on("touchstart", this.onTouchStart, this);
17584 //        }
17585         
17586         if(this.autoslide){
17587             var _this = this;
17588             
17589             this.slideFn = window.setInterval(function() {
17590                 _this.showPanelNext();
17591             }, this.timer);
17592         }
17593         
17594         if(this.showarrow){
17595             this.el.select('.carousel-prev', true).first().on('click', this.showPanelPrev, this);
17596             this.el.select('.carousel-next', true).first().on('click', this.showPanelNext, this);
17597         }
17598         
17599         
17600     },
17601     
17602 //    onTouchStart : function(e, el, o)
17603 //    {
17604 //        if(!this.slideOnTouch || !Roo.isTouch || Roo.get(e.getTarget()).hasClass('roo-button-text')){
17605 //            return;
17606 //        }
17607 //        
17608 //        this.showPanelNext();
17609 //    },
17610     
17611     
17612     getChildContainer : function()
17613     {
17614         return this.carousel ? this.el.select('.carousel-inner', true).first() : this.el;
17615     },
17616     
17617     /**
17618     * register a Navigation item
17619     * @param {Roo.bootstrap.NavItem} the navitem to add
17620     */
17621     register : function(item)
17622     {
17623         this.tabs.push( item);
17624         item.navId = this.navId; // not really needed..
17625         this.addBullet();
17626     
17627     },
17628     
17629     getActivePanel : function()
17630     {
17631         var r = false;
17632         Roo.each(this.tabs, function(t) {
17633             if (t.active) {
17634                 r = t;
17635                 return false;
17636             }
17637             return null;
17638         });
17639         return r;
17640         
17641     },
17642     getPanelByName : function(n)
17643     {
17644         var r = false;
17645         Roo.each(this.tabs, function(t) {
17646             if (t.tabId == n) {
17647                 r = t;
17648                 return false;
17649             }
17650             return null;
17651         });
17652         return r;
17653     },
17654     indexOfPanel : function(p)
17655     {
17656         var r = false;
17657         Roo.each(this.tabs, function(t,i) {
17658             if (t.tabId == p.tabId) {
17659                 r = i;
17660                 return false;
17661             }
17662             return null;
17663         });
17664         return r;
17665     },
17666     /**
17667      * show a specific panel
17668      * @param {Roo.bootstrap.TabPanel|number|string} panel to change to (use the tabId to specify a specific one)
17669      * @return {boolean} false if panel was not shown (invalid entry or beforedeactivate fails.)
17670      */
17671     showPanel : function (pan)
17672     {
17673         if(this.transition || typeof(pan) == 'undefined'){
17674             Roo.log("waiting for the transitionend");
17675             return;
17676         }
17677         
17678         if (typeof(pan) == 'number') {
17679             pan = this.tabs[pan];
17680         }
17681         
17682         if (typeof(pan) == 'string') {
17683             pan = this.getPanelByName(pan);
17684         }
17685         
17686         var cur = this.getActivePanel();
17687         
17688         if(!pan || !cur){
17689             Roo.log('pan or acitve pan is undefined');
17690             return false;
17691         }
17692         
17693         if (pan.tabId == this.getActivePanel().tabId) {
17694             return true;
17695         }
17696         
17697         if (false === cur.fireEvent('beforedeactivate')) {
17698             return false;
17699         }
17700         
17701         if(this.bullets > 0 && !Roo.isTouch){
17702             this.setActiveBullet(this.indexOfPanel(pan));
17703         }
17704         
17705         if (this.carousel && typeof(Roo.get(document.body).dom.style.transition) != 'undefined') {
17706             
17707             this.transition = true;
17708             var dir = this.indexOfPanel(pan) > this.indexOfPanel(cur)  ? 'next' : 'prev';
17709             var lr = dir == 'next' ? 'left' : 'right';
17710             pan.el.addClass(dir); // or prev
17711             pan.el.dom.offsetWidth; // find the offset with - causing a reflow?
17712             cur.el.addClass(lr); // or right
17713             pan.el.addClass(lr);
17714             
17715             var _this = this;
17716             cur.el.on('transitionend', function() {
17717                 Roo.log("trans end?");
17718                 
17719                 pan.el.removeClass([lr,dir]);
17720                 pan.setActive(true);
17721                 
17722                 cur.el.removeClass([lr]);
17723                 cur.setActive(false);
17724                 
17725                 _this.transition = false;
17726                 
17727             }, this, { single:  true } );
17728             
17729             return true;
17730         }
17731         
17732         cur.setActive(false);
17733         pan.setActive(true);
17734         
17735         return true;
17736         
17737     },
17738     showPanelNext : function()
17739     {
17740         var i = this.indexOfPanel(this.getActivePanel());
17741         
17742         if (i >= this.tabs.length - 1 && !this.autoslide) {
17743             return;
17744         }
17745         
17746         if (i >= this.tabs.length - 1 && this.autoslide) {
17747             i = -1;
17748         }
17749         
17750         this.showPanel(this.tabs[i+1]);
17751     },
17752     
17753     showPanelPrev : function()
17754     {
17755         var i = this.indexOfPanel(this.getActivePanel());
17756         
17757         if (i  < 1 && !this.autoslide) {
17758             return;
17759         }
17760         
17761         if (i < 1 && this.autoslide) {
17762             i = this.tabs.length;
17763         }
17764         
17765         this.showPanel(this.tabs[i-1]);
17766     },
17767     
17768     
17769     addBullet: function()
17770     {
17771         if(!this.bullets || Roo.isTouch){
17772             return;
17773         }
17774         var ctr = this.el.select('.carousel-bullets',true).first();
17775         var i = this.el.select('.carousel-bullets .bullet',true).getCount() ;
17776         var bullet = ctr.createChild({
17777             cls : 'bullet bullet-' + i
17778         },ctr.dom.lastChild);
17779         
17780         
17781         var _this = this;
17782         
17783         bullet.on('click', (function(e, el, o, ii, t){
17784
17785             e.preventDefault();
17786
17787             this.showPanel(ii);
17788
17789             if(this.autoslide && this.slideFn){
17790                 clearInterval(this.slideFn);
17791                 this.slideFn = window.setInterval(function() {
17792                     _this.showPanelNext();
17793                 }, this.timer);
17794             }
17795
17796         }).createDelegate(this, [i, bullet], true));
17797                 
17798         
17799     },
17800      
17801     setActiveBullet : function(i)
17802     {
17803         if(Roo.isTouch){
17804             return;
17805         }
17806         
17807         Roo.each(this.el.select('.bullet', true).elements, function(el){
17808             el.removeClass('selected');
17809         });
17810
17811         var bullet = this.el.select('.bullet-' + i, true).first();
17812         
17813         if(!bullet){
17814             return;
17815         }
17816         
17817         bullet.addClass('selected');
17818     }
17819     
17820     
17821   
17822 });
17823
17824  
17825
17826  
17827  
17828 Roo.apply(Roo.bootstrap.TabGroup, {
17829     
17830     groups: {},
17831      /**
17832     * register a Navigation Group
17833     * @param {Roo.bootstrap.NavGroup} the navgroup to add
17834     */
17835     register : function(navgrp)
17836     {
17837         this.groups[navgrp.navId] = navgrp;
17838         
17839     },
17840     /**
17841     * fetch a Navigation Group based on the navigation ID
17842     * if one does not exist , it will get created.
17843     * @param {string} the navgroup to add
17844     * @returns {Roo.bootstrap.NavGroup} the navgroup 
17845     */
17846     get: function(navId) {
17847         if (typeof(this.groups[navId]) == 'undefined') {
17848             this.register(new Roo.bootstrap.TabGroup({ navId : navId }));
17849         }
17850         return this.groups[navId] ;
17851     }
17852     
17853     
17854     
17855 });
17856
17857  /*
17858  * - LGPL
17859  *
17860  * TabPanel
17861  * 
17862  */
17863
17864 /**
17865  * @class Roo.bootstrap.TabPanel
17866  * @extends Roo.bootstrap.Component
17867  * Bootstrap TabPanel class
17868  * @cfg {Boolean} active panel active
17869  * @cfg {String} html panel content
17870  * @cfg {String} tabId  unique tab ID (will be autogenerated if not set. - used to match TabItem to Panel)
17871  * @cfg {String} navId The Roo.bootstrap.NavGroup which triggers show hide ()
17872  * @cfg {String} href click to link..
17873  * 
17874  * 
17875  * @constructor
17876  * Create a new TabPanel
17877  * @param {Object} config The config object
17878  */
17879
17880 Roo.bootstrap.TabPanel = function(config){
17881     Roo.bootstrap.TabPanel.superclass.constructor.call(this, config);
17882     this.addEvents({
17883         /**
17884              * @event changed
17885              * Fires when the active status changes
17886              * @param {Roo.bootstrap.TabPanel} this
17887              * @param {Boolean} state the new state
17888             
17889          */
17890         'changed': true,
17891         /**
17892              * @event beforedeactivate
17893              * Fires before a tab is de-activated - can be used to do validation on a form.
17894              * @param {Roo.bootstrap.TabPanel} this
17895              * @return {Boolean} false if there is an error
17896             
17897          */
17898         'beforedeactivate': true
17899      });
17900     
17901     this.tabId = this.tabId || Roo.id();
17902   
17903 };
17904
17905 Roo.extend(Roo.bootstrap.TabPanel, Roo.bootstrap.Component,  {
17906     
17907     active: false,
17908     html: false,
17909     tabId: false,
17910     navId : false,
17911     href : '',
17912     
17913     getAutoCreate : function(){
17914         var cfg = {
17915             tag: 'div',
17916             // item is needed for carousel - not sure if it has any effect otherwise
17917             cls: 'tab-pane item' + ((this.href.length) ? ' clickable ' : ''),
17918             html: this.html || ''
17919         };
17920         
17921         if(this.active){
17922             cfg.cls += ' active';
17923         }
17924         
17925         if(this.tabId){
17926             cfg.tabId = this.tabId;
17927         }
17928         
17929         
17930         return cfg;
17931     },
17932     
17933     initEvents:  function()
17934     {
17935         var p = this.parent();
17936         
17937         this.navId = this.navId || p.navId;
17938         
17939         if (typeof(this.navId) != 'undefined') {
17940             // not really needed.. but just in case.. parent should be a NavGroup.
17941             var tg = Roo.bootstrap.TabGroup.get(this.navId);
17942             
17943             tg.register(this);
17944             
17945             var i = tg.tabs.length - 1;
17946             
17947             if(this.active && tg.bullets > 0 && i < tg.bullets){
17948                 tg.setActiveBullet(i);
17949             }
17950         }
17951         
17952         this.el.on('click', this.onClick, this);
17953         
17954         if(Roo.isTouch){
17955             this.el.on("touchstart", this.onTouchStart, this);
17956             this.el.on("touchmove", this.onTouchMove, this);
17957             this.el.on("touchend", this.onTouchEnd, this);
17958         }
17959         
17960     },
17961     
17962     onRender : function(ct, position)
17963     {
17964         Roo.bootstrap.TabPanel.superclass.onRender.call(this, ct, position);
17965     },
17966     
17967     setActive : function(state)
17968     {
17969         Roo.log("panel - set active " + this.tabId + "=" + state);
17970         
17971         this.active = state;
17972         if (!state) {
17973             this.el.removeClass('active');
17974             
17975         } else  if (!this.el.hasClass('active')) {
17976             this.el.addClass('active');
17977         }
17978         
17979         this.fireEvent('changed', this, state);
17980     },
17981     
17982     onClick : function(e)
17983     {
17984         e.preventDefault();
17985         
17986         if(!this.href.length){
17987             return;
17988         }
17989         
17990         window.location.href = this.href;
17991     },
17992     
17993     startX : 0,
17994     startY : 0,
17995     endX : 0,
17996     endY : 0,
17997     swiping : false,
17998     
17999     onTouchStart : function(e)
18000     {
18001         this.swiping = false;
18002         
18003         this.startX = e.browserEvent.touches[0].clientX;
18004         this.startY = e.browserEvent.touches[0].clientY;
18005     },
18006     
18007     onTouchMove : function(e)
18008     {
18009         this.swiping = true;
18010         
18011         this.endX = e.browserEvent.touches[0].clientX;
18012         this.endY = e.browserEvent.touches[0].clientY;
18013     },
18014     
18015     onTouchEnd : function(e)
18016     {
18017         if(!this.swiping){
18018             this.onClick(e);
18019             return;
18020         }
18021         
18022         var tabGroup = this.parent();
18023         
18024         if(this.endX > this.startX){ // swiping right
18025             tabGroup.showPanelPrev();
18026             return;
18027         }
18028         
18029         if(this.startX > this.endX){ // swiping left
18030             tabGroup.showPanelNext();
18031             return;
18032         }
18033     }
18034     
18035     
18036 });
18037  
18038
18039  
18040
18041  /*
18042  * - LGPL
18043  *
18044  * DateField
18045  * 
18046  */
18047
18048 /**
18049  * @class Roo.bootstrap.DateField
18050  * @extends Roo.bootstrap.Input
18051  * Bootstrap DateField class
18052  * @cfg {Number} weekStart default 0
18053  * @cfg {String} viewMode default empty, (months|years)
18054  * @cfg {String} minViewMode default empty, (months|years)
18055  * @cfg {Number} startDate default -Infinity
18056  * @cfg {Number} endDate default Infinity
18057  * @cfg {Boolean} todayHighlight default false
18058  * @cfg {Boolean} todayBtn default false
18059  * @cfg {Boolean} calendarWeeks default false
18060  * @cfg {Object} daysOfWeekDisabled default empty
18061  * @cfg {Boolean} singleMode default false (true | false)
18062  * 
18063  * @cfg {Boolean} keyboardNavigation default true
18064  * @cfg {String} language default en
18065  * 
18066  * @constructor
18067  * Create a new DateField
18068  * @param {Object} config The config object
18069  */
18070
18071 Roo.bootstrap.DateField = function(config){
18072     Roo.bootstrap.DateField.superclass.constructor.call(this, config);
18073      this.addEvents({
18074             /**
18075              * @event show
18076              * Fires when this field show.
18077              * @param {Roo.bootstrap.DateField} this
18078              * @param {Mixed} date The date value
18079              */
18080             show : true,
18081             /**
18082              * @event show
18083              * Fires when this field hide.
18084              * @param {Roo.bootstrap.DateField} this
18085              * @param {Mixed} date The date value
18086              */
18087             hide : true,
18088             /**
18089              * @event select
18090              * Fires when select a date.
18091              * @param {Roo.bootstrap.DateField} this
18092              * @param {Mixed} date The date value
18093              */
18094             select : true,
18095             /**
18096              * @event beforeselect
18097              * Fires when before select a date.
18098              * @param {Roo.bootstrap.DateField} this
18099              * @param {Mixed} date The date value
18100              */
18101             beforeselect : true
18102         });
18103 };
18104
18105 Roo.extend(Roo.bootstrap.DateField, Roo.bootstrap.Input,  {
18106     
18107     /**
18108      * @cfg {String} format
18109      * The default date format string which can be overriden for localization support.  The format must be
18110      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
18111      */
18112     format : "m/d/y",
18113     /**
18114      * @cfg {String} altFormats
18115      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
18116      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
18117      */
18118     altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
18119     
18120     weekStart : 0,
18121     
18122     viewMode : '',
18123     
18124     minViewMode : '',
18125     
18126     todayHighlight : false,
18127     
18128     todayBtn: false,
18129     
18130     language: 'en',
18131     
18132     keyboardNavigation: true,
18133     
18134     calendarWeeks: false,
18135     
18136     startDate: -Infinity,
18137     
18138     endDate: Infinity,
18139     
18140     daysOfWeekDisabled: [],
18141     
18142     _events: [],
18143     
18144     singleMode : false,
18145     
18146     UTCDate: function()
18147     {
18148         return new Date(Date.UTC.apply(Date, arguments));
18149     },
18150     
18151     UTCToday: function()
18152     {
18153         var today = new Date();
18154         return this.UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
18155     },
18156     
18157     getDate: function() {
18158             var d = this.getUTCDate();
18159             return new Date(d.getTime() + (d.getTimezoneOffset()*60000));
18160     },
18161     
18162     getUTCDate: function() {
18163             return this.date;
18164     },
18165     
18166     setDate: function(d) {
18167             this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000)));
18168     },
18169     
18170     setUTCDate: function(d) {
18171             this.date = d;
18172             this.setValue(this.formatDate(this.date));
18173     },
18174         
18175     onRender: function(ct, position)
18176     {
18177         
18178         Roo.bootstrap.DateField.superclass.onRender.call(this, ct, position);
18179         
18180         this.language = this.language || 'en';
18181         this.language = this.language in Roo.bootstrap.DateField.dates ? this.language : this.language.split('-')[0];
18182         this.language = this.language in Roo.bootstrap.DateField.dates ? this.language : "en";
18183         
18184         this.isRTL = Roo.bootstrap.DateField.dates[this.language].rtl || false;
18185         this.format = this.format || 'm/d/y';
18186         this.isInline = false;
18187         this.isInput = true;
18188         this.component = this.el.select('.add-on', true).first() || false;
18189         this.component = (this.component && this.component.length === 0) ? false : this.component;
18190         this.hasInput = this.component && this.inputEl().length;
18191         
18192         if (typeof(this.minViewMode === 'string')) {
18193             switch (this.minViewMode) {
18194                 case 'months':
18195                     this.minViewMode = 1;
18196                     break;
18197                 case 'years':
18198                     this.minViewMode = 2;
18199                     break;
18200                 default:
18201                     this.minViewMode = 0;
18202                     break;
18203             }
18204         }
18205         
18206         if (typeof(this.viewMode === 'string')) {
18207             switch (this.viewMode) {
18208                 case 'months':
18209                     this.viewMode = 1;
18210                     break;
18211                 case 'years':
18212                     this.viewMode = 2;
18213                     break;
18214                 default:
18215                     this.viewMode = 0;
18216                     break;
18217             }
18218         }
18219                 
18220         this.pickerEl = Roo.get(document.body).createChild(Roo.bootstrap.DateField.template);
18221         
18222 //        this.el.select('>.input-group', true).first().createChild(Roo.bootstrap.DateField.template);
18223         
18224         this.picker().setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
18225         
18226         this.picker().on('mousedown', this.onMousedown, this);
18227         this.picker().on('click', this.onClick, this);
18228         
18229         this.picker().addClass('datepicker-dropdown');
18230         
18231         this.startViewMode = this.viewMode;
18232         
18233         if(this.singleMode){
18234             Roo.each(this.picker().select('thead > tr > th', true).elements, function(v){
18235                 v.setVisibilityMode(Roo.Element.DISPLAY);
18236                 v.hide();
18237             });
18238             
18239             Roo.each(this.picker().select('tbody > tr > td', true).elements, function(v){
18240                 v.setStyle('width', '189px');
18241             });
18242         }
18243         
18244         Roo.each(this.picker().select('tfoot th.today', true).elements, function(v){
18245             if(!this.calendarWeeks){
18246                 v.remove();
18247                 return;
18248             }
18249             
18250             v.dom.innerHTML = Roo.bootstrap.DateField.dates[this.language].today;
18251             v.attr('colspan', function(i, val){
18252                 return parseInt(val) + 1;
18253             });
18254         });
18255                         
18256         
18257         this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
18258         
18259         this.setStartDate(this.startDate);
18260         this.setEndDate(this.endDate);
18261         
18262         this.setDaysOfWeekDisabled(this.daysOfWeekDisabled);
18263         
18264         this.fillDow();
18265         this.fillMonths();
18266         this.update();
18267         this.showMode();
18268         
18269         if(this.isInline) {
18270             this.show();
18271         }
18272     },
18273     
18274     picker : function()
18275     {
18276         return this.pickerEl;
18277 //        return this.el.select('.datepicker', true).first();
18278     },
18279     
18280     fillDow: function()
18281     {
18282         var dowCnt = this.weekStart;
18283         
18284         var dow = {
18285             tag: 'tr',
18286             cn: [
18287                 
18288             ]
18289         };
18290         
18291         if(this.calendarWeeks){
18292             dow.cn.push({
18293                 tag: 'th',
18294                 cls: 'cw',
18295                 html: '&nbsp;'
18296             })
18297         }
18298         
18299         while (dowCnt < this.weekStart + 7) {
18300             dow.cn.push({
18301                 tag: 'th',
18302                 cls: 'dow',
18303                 html: Roo.bootstrap.DateField.dates[this.language].daysMin[(dowCnt++)%7]
18304             });
18305         }
18306         
18307         this.picker().select('>.datepicker-days thead', true).first().createChild(dow);
18308     },
18309     
18310     fillMonths: function()
18311     {    
18312         var i = 0;
18313         var months = this.picker().select('>.datepicker-months td', true).first();
18314         
18315         months.dom.innerHTML = '';
18316         
18317         while (i < 12) {
18318             var month = {
18319                 tag: 'span',
18320                 cls: 'month',
18321                 html: Roo.bootstrap.DateField.dates[this.language].monthsShort[i++]
18322             };
18323             
18324             months.createChild(month);
18325         }
18326         
18327     },
18328     
18329     update: function()
18330     {
18331         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;
18332         
18333         if (this.date < this.startDate) {
18334             this.viewDate = new Date(this.startDate);
18335         } else if (this.date > this.endDate) {
18336             this.viewDate = new Date(this.endDate);
18337         } else {
18338             this.viewDate = new Date(this.date);
18339         }
18340         
18341         this.fill();
18342     },
18343     
18344     fill: function() 
18345     {
18346         var d = new Date(this.viewDate),
18347                 year = d.getUTCFullYear(),
18348                 month = d.getUTCMonth(),
18349                 startYear = this.startDate !== -Infinity ? this.startDate.getUTCFullYear() : -Infinity,
18350                 startMonth = this.startDate !== -Infinity ? this.startDate.getUTCMonth() : -Infinity,
18351                 endYear = this.endDate !== Infinity ? this.endDate.getUTCFullYear() : Infinity,
18352                 endMonth = this.endDate !== Infinity ? this.endDate.getUTCMonth() : Infinity,
18353                 currentDate = this.date && this.date.valueOf(),
18354                 today = this.UTCToday();
18355         
18356         this.picker().select('>.datepicker-days thead th.switch', true).first().dom.innerHTML = Roo.bootstrap.DateField.dates[this.language].months[month]+' '+year;
18357         
18358 //        this.picker().select('>tfoot th.today', true).first().dom.innerHTML = Roo.bootstrap.DateField.dates[this.language].today;
18359         
18360 //        this.picker.select('>tfoot th.today').
18361 //                                              .text(dates[this.language].today)
18362 //                                              .toggle(this.todayBtn !== false);
18363     
18364         this.updateNavArrows();
18365         this.fillMonths();
18366                                                 
18367         var prevMonth = this.UTCDate(year, month-1, 28,0,0,0,0),
18368         
18369         day = prevMonth.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
18370          
18371         prevMonth.setUTCDate(day);
18372         
18373         prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.weekStart + 7)%7);
18374         
18375         var nextMonth = new Date(prevMonth);
18376         
18377         nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
18378         
18379         nextMonth = nextMonth.valueOf();
18380         
18381         var fillMonths = false;
18382         
18383         this.picker().select('>.datepicker-days tbody',true).first().dom.innerHTML = '';
18384         
18385         while(prevMonth.valueOf() < nextMonth) {
18386             var clsName = '';
18387             
18388             if (prevMonth.getUTCDay() === this.weekStart) {
18389                 if(fillMonths){
18390                     this.picker().select('>.datepicker-days tbody',true).first().createChild(fillMonths);
18391                 }
18392                     
18393                 fillMonths = {
18394                     tag: 'tr',
18395                     cn: []
18396                 };
18397                 
18398                 if(this.calendarWeeks){
18399                     // ISO 8601: First week contains first thursday.
18400                     // ISO also states week starts on Monday, but we can be more abstract here.
18401                     var
18402                     // Start of current week: based on weekstart/current date
18403                     ws = new Date(+prevMonth + (this.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
18404                     // Thursday of this week
18405                     th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
18406                     // First Thursday of year, year from thursday
18407                     yth = new Date(+(yth = this.UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5),
18408                     // Calendar week: ms between thursdays, div ms per day, div 7 days
18409                     calWeek =  (th - yth) / 864e5 / 7 + 1;
18410                     
18411                     fillMonths.cn.push({
18412                         tag: 'td',
18413                         cls: 'cw',
18414                         html: calWeek
18415                     });
18416                 }
18417             }
18418             
18419             if (prevMonth.getUTCFullYear() < year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() < month)) {
18420                 clsName += ' old';
18421             } else if (prevMonth.getUTCFullYear() > year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() > month)) {
18422                 clsName += ' new';
18423             }
18424             if (this.todayHighlight &&
18425                 prevMonth.getUTCFullYear() == today.getFullYear() &&
18426                 prevMonth.getUTCMonth() == today.getMonth() &&
18427                 prevMonth.getUTCDate() == today.getDate()) {
18428                 clsName += ' today';
18429             }
18430             
18431             if (currentDate && prevMonth.valueOf() === currentDate) {
18432                 clsName += ' active';
18433             }
18434             
18435             if (prevMonth.valueOf() < this.startDate || prevMonth.valueOf() > this.endDate ||
18436                     this.daysOfWeekDisabled.indexOf(prevMonth.getUTCDay()) !== -1) {
18437                     clsName += ' disabled';
18438             }
18439             
18440             fillMonths.cn.push({
18441                 tag: 'td',
18442                 cls: 'day ' + clsName,
18443                 html: prevMonth.getDate()
18444             });
18445             
18446             prevMonth.setDate(prevMonth.getDate()+1);
18447         }
18448           
18449         var currentYear = this.date && this.date.getUTCFullYear();
18450         var currentMonth = this.date && this.date.getUTCMonth();
18451         
18452         this.picker().select('>.datepicker-months th.switch',true).first().dom.innerHTML = year;
18453         
18454         Roo.each(this.picker().select('>.datepicker-months tbody span',true).elements, function(v,k){
18455             v.removeClass('active');
18456             
18457             if(currentYear === year && k === currentMonth){
18458                 v.addClass('active');
18459             }
18460             
18461             if (year < startYear || year > endYear || (year == startYear && k < startMonth) || (year == endYear && k > endMonth)) {
18462                 v.addClass('disabled');
18463             }
18464             
18465         });
18466         
18467         
18468         year = parseInt(year/10, 10) * 10;
18469         
18470         this.picker().select('>.datepicker-years th.switch', true).first().dom.innerHTML = year + '-' + (year + 9);
18471         
18472         this.picker().select('>.datepicker-years tbody td',true).first().dom.innerHTML = '';
18473         
18474         year -= 1;
18475         for (var i = -1; i < 11; i++) {
18476             this.picker().select('>.datepicker-years tbody td',true).first().createChild({
18477                 tag: 'span',
18478                 cls: 'year' + (i === -1 || i === 10 ? ' old' : '') + (currentYear === year ? ' active' : '') + (year < startYear || year > endYear ? ' disabled' : ''),
18479                 html: year
18480             });
18481             
18482             year += 1;
18483         }
18484     },
18485     
18486     showMode: function(dir) 
18487     {
18488         if (dir) {
18489             this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
18490         }
18491         
18492         Roo.each(this.picker().select('>div',true).elements, function(v){
18493             v.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
18494             v.hide();
18495         });
18496         this.picker().select('>.datepicker-'+Roo.bootstrap.DateField.modes[this.viewMode].clsName, true).first().show();
18497     },
18498     
18499     place: function()
18500     {
18501         if(this.isInline) {
18502             return;
18503         }
18504         
18505         this.picker().removeClass(['bottom', 'top']);
18506         
18507         if((Roo.lib.Dom.getViewHeight() + Roo.get(document.body).getScroll().top) - (this.inputEl().getBottom() + this.picker().getHeight()) < 0){
18508             /*
18509              * place to the top of element!
18510              *
18511              */
18512             
18513             this.picker().addClass('top');
18514             this.picker().setTop(this.inputEl().getTop() - this.picker().getHeight()).setLeft(this.inputEl().getLeft());
18515             
18516             return;
18517         }
18518         
18519         this.picker().addClass('bottom');
18520         
18521         this.picker().setTop(this.inputEl().getBottom()).setLeft(this.inputEl().getLeft());
18522     },
18523     
18524     parseDate : function(value)
18525     {
18526         if(!value || value instanceof Date){
18527             return value;
18528         }
18529         var v = Date.parseDate(value, this.format);
18530         if (!v && (this.useIso || value.match(/^(\d{4})-0?(\d+)-0?(\d+)/))) {
18531             v = Date.parseDate(value, 'Y-m-d');
18532         }
18533         if(!v && this.altFormats){
18534             if(!this.altFormatsArray){
18535                 this.altFormatsArray = this.altFormats.split("|");
18536             }
18537             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
18538                 v = Date.parseDate(value, this.altFormatsArray[i]);
18539             }
18540         }
18541         return v;
18542     },
18543     
18544     formatDate : function(date, fmt)
18545     {   
18546         return (!date || !(date instanceof Date)) ?
18547         date : date.dateFormat(fmt || this.format);
18548     },
18549     
18550     onFocus : function()
18551     {
18552         Roo.bootstrap.DateField.superclass.onFocus.call(this);
18553         this.show();
18554     },
18555     
18556     onBlur : function()
18557     {
18558         Roo.bootstrap.DateField.superclass.onBlur.call(this);
18559         
18560         var d = this.inputEl().getValue();
18561         
18562         this.setValue(d);
18563                 
18564         this.hide();
18565     },
18566     
18567     show : function()
18568     {
18569         this.picker().show();
18570         this.update();
18571         this.place();
18572         
18573         this.fireEvent('show', this, this.date);
18574     },
18575     
18576     hide : function()
18577     {
18578         if(this.isInline) {
18579             return;
18580         }
18581         this.picker().hide();
18582         this.viewMode = this.startViewMode;
18583         this.showMode();
18584         
18585         this.fireEvent('hide', this, this.date);
18586         
18587     },
18588     
18589     onMousedown: function(e)
18590     {
18591         e.stopPropagation();
18592         e.preventDefault();
18593     },
18594     
18595     keyup: function(e)
18596     {
18597         Roo.bootstrap.DateField.superclass.keyup.call(this);
18598         this.update();
18599     },
18600
18601     setValue: function(v)
18602     {
18603         if(this.fireEvent('beforeselect', this, v) !== false){
18604             var d = new Date(this.parseDate(v) ).clearTime();
18605         
18606             if(isNaN(d.getTime())){
18607                 this.date = this.viewDate = '';
18608                 Roo.bootstrap.DateField.superclass.setValue.call(this, '');
18609                 return;
18610             }
18611
18612             v = this.formatDate(d);
18613
18614             Roo.bootstrap.DateField.superclass.setValue.call(this, v);
18615
18616             this.date = new Date(d.getTime() - d.getTimezoneOffset()*60000);
18617
18618             this.update();
18619
18620             this.fireEvent('select', this, this.date);
18621         }
18622     },
18623     
18624     getValue: function()
18625     {
18626         return this.formatDate(this.date);
18627     },
18628     
18629     fireKey: function(e)
18630     {
18631         if (!this.picker().isVisible()){
18632             if (e.keyCode == 27) { // allow escape to hide and re-show picker
18633                 this.show();
18634             }
18635             return;
18636         }
18637         
18638         var dateChanged = false,
18639         dir, day, month,
18640         newDate, newViewDate;
18641         
18642         switch(e.keyCode){
18643             case 27: // escape
18644                 this.hide();
18645                 e.preventDefault();
18646                 break;
18647             case 37: // left
18648             case 39: // right
18649                 if (!this.keyboardNavigation) {
18650                     break;
18651                 }
18652                 dir = e.keyCode == 37 ? -1 : 1;
18653                 
18654                 if (e.ctrlKey){
18655                     newDate = this.moveYear(this.date, dir);
18656                     newViewDate = this.moveYear(this.viewDate, dir);
18657                 } else if (e.shiftKey){
18658                     newDate = this.moveMonth(this.date, dir);
18659                     newViewDate = this.moveMonth(this.viewDate, dir);
18660                 } else {
18661                     newDate = new Date(this.date);
18662                     newDate.setUTCDate(this.date.getUTCDate() + dir);
18663                     newViewDate = new Date(this.viewDate);
18664                     newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir);
18665                 }
18666                 if (this.dateWithinRange(newDate)){
18667                     this.date = newDate;
18668                     this.viewDate = newViewDate;
18669                     this.setValue(this.formatDate(this.date));
18670 //                    this.update();
18671                     e.preventDefault();
18672                     dateChanged = true;
18673                 }
18674                 break;
18675             case 38: // up
18676             case 40: // down
18677                 if (!this.keyboardNavigation) {
18678                     break;
18679                 }
18680                 dir = e.keyCode == 38 ? -1 : 1;
18681                 if (e.ctrlKey){
18682                     newDate = this.moveYear(this.date, dir);
18683                     newViewDate = this.moveYear(this.viewDate, dir);
18684                 } else if (e.shiftKey){
18685                     newDate = this.moveMonth(this.date, dir);
18686                     newViewDate = this.moveMonth(this.viewDate, dir);
18687                 } else {
18688                     newDate = new Date(this.date);
18689                     newDate.setUTCDate(this.date.getUTCDate() + dir * 7);
18690                     newViewDate = new Date(this.viewDate);
18691                     newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7);
18692                 }
18693                 if (this.dateWithinRange(newDate)){
18694                     this.date = newDate;
18695                     this.viewDate = newViewDate;
18696                     this.setValue(this.formatDate(this.date));
18697 //                    this.update();
18698                     e.preventDefault();
18699                     dateChanged = true;
18700                 }
18701                 break;
18702             case 13: // enter
18703                 this.setValue(this.formatDate(this.date));
18704                 this.hide();
18705                 e.preventDefault();
18706                 break;
18707             case 9: // tab
18708                 this.setValue(this.formatDate(this.date));
18709                 this.hide();
18710                 break;
18711             case 16: // shift
18712             case 17: // ctrl
18713             case 18: // alt
18714                 break;
18715             default :
18716                 this.hide();
18717                 
18718         }
18719     },
18720     
18721     
18722     onClick: function(e) 
18723     {
18724         e.stopPropagation();
18725         e.preventDefault();
18726         
18727         var target = e.getTarget();
18728         
18729         if(target.nodeName.toLowerCase() === 'i'){
18730             target = Roo.get(target).dom.parentNode;
18731         }
18732         
18733         var nodeName = target.nodeName;
18734         var className = target.className;
18735         var html = target.innerHTML;
18736         //Roo.log(nodeName);
18737         
18738         switch(nodeName.toLowerCase()) {
18739             case 'th':
18740                 switch(className) {
18741                     case 'switch':
18742                         this.showMode(1);
18743                         break;
18744                     case 'prev':
18745                     case 'next':
18746                         var dir = Roo.bootstrap.DateField.modes[this.viewMode].navStep * (className == 'prev' ? -1 : 1);
18747                         switch(this.viewMode){
18748                                 case 0:
18749                                         this.viewDate = this.moveMonth(this.viewDate, dir);
18750                                         break;
18751                                 case 1:
18752                                 case 2:
18753                                         this.viewDate = this.moveYear(this.viewDate, dir);
18754                                         break;
18755                         }
18756                         this.fill();
18757                         break;
18758                     case 'today':
18759                         var date = new Date();
18760                         this.date = this.UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
18761 //                        this.fill()
18762                         this.setValue(this.formatDate(this.date));
18763                         
18764                         this.hide();
18765                         break;
18766                 }
18767                 break;
18768             case 'span':
18769                 if (className.indexOf('disabled') < 0) {
18770                     this.viewDate.setUTCDate(1);
18771                     if (className.indexOf('month') > -1) {
18772                         this.viewDate.setUTCMonth(Roo.bootstrap.DateField.dates[this.language].monthsShort.indexOf(html));
18773                     } else {
18774                         var year = parseInt(html, 10) || 0;
18775                         this.viewDate.setUTCFullYear(year);
18776                         
18777                     }
18778                     
18779                     if(this.singleMode){
18780                         this.setValue(this.formatDate(this.viewDate));
18781                         this.hide();
18782                         return;
18783                     }
18784                     
18785                     this.showMode(-1);
18786                     this.fill();
18787                 }
18788                 break;
18789                 
18790             case 'td':
18791                 //Roo.log(className);
18792                 if (className.indexOf('day') > -1 && className.indexOf('disabled') < 0 ){
18793                     var day = parseInt(html, 10) || 1;
18794                     var year = this.viewDate.getUTCFullYear(),
18795                         month = this.viewDate.getUTCMonth();
18796
18797                     if (className.indexOf('old') > -1) {
18798                         if(month === 0 ){
18799                             month = 11;
18800                             year -= 1;
18801                         }else{
18802                             month -= 1;
18803                         }
18804                     } else if (className.indexOf('new') > -1) {
18805                         if (month == 11) {
18806                             month = 0;
18807                             year += 1;
18808                         } else {
18809                             month += 1;
18810                         }
18811                     }
18812                     //Roo.log([year,month,day]);
18813                     this.date = this.UTCDate(year, month, day,0,0,0,0);
18814                     this.viewDate = this.UTCDate(year, month, Math.min(28, day),0,0,0,0);
18815 //                    this.fill();
18816                     //Roo.log(this.formatDate(this.date));
18817                     this.setValue(this.formatDate(this.date));
18818                     this.hide();
18819                 }
18820                 break;
18821         }
18822     },
18823     
18824     setStartDate: function(startDate)
18825     {
18826         this.startDate = startDate || -Infinity;
18827         if (this.startDate !== -Infinity) {
18828             this.startDate = this.parseDate(this.startDate);
18829         }
18830         this.update();
18831         this.updateNavArrows();
18832     },
18833
18834     setEndDate: function(endDate)
18835     {
18836         this.endDate = endDate || Infinity;
18837         if (this.endDate !== Infinity) {
18838             this.endDate = this.parseDate(this.endDate);
18839         }
18840         this.update();
18841         this.updateNavArrows();
18842     },
18843     
18844     setDaysOfWeekDisabled: function(daysOfWeekDisabled)
18845     {
18846         this.daysOfWeekDisabled = daysOfWeekDisabled || [];
18847         if (typeof(this.daysOfWeekDisabled) !== 'object') {
18848             this.daysOfWeekDisabled = this.daysOfWeekDisabled.split(/,\s*/);
18849         }
18850         this.daysOfWeekDisabled = this.daysOfWeekDisabled.map(function (d) {
18851             return parseInt(d, 10);
18852         });
18853         this.update();
18854         this.updateNavArrows();
18855     },
18856     
18857     updateNavArrows: function() 
18858     {
18859         if(this.singleMode){
18860             return;
18861         }
18862         
18863         var d = new Date(this.viewDate),
18864         year = d.getUTCFullYear(),
18865         month = d.getUTCMonth();
18866         
18867         Roo.each(this.picker().select('.prev', true).elements, function(v){
18868             v.show();
18869             switch (this.viewMode) {
18870                 case 0:
18871
18872                     if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth()) {
18873                         v.hide();
18874                     }
18875                     break;
18876                 case 1:
18877                 case 2:
18878                     if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear()) {
18879                         v.hide();
18880                     }
18881                     break;
18882             }
18883         });
18884         
18885         Roo.each(this.picker().select('.next', true).elements, function(v){
18886             v.show();
18887             switch (this.viewMode) {
18888                 case 0:
18889
18890                     if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth()) {
18891                         v.hide();
18892                     }
18893                     break;
18894                 case 1:
18895                 case 2:
18896                     if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear()) {
18897                         v.hide();
18898                     }
18899                     break;
18900             }
18901         })
18902     },
18903     
18904     moveMonth: function(date, dir)
18905     {
18906         if (!dir) {
18907             return date;
18908         }
18909         var new_date = new Date(date.valueOf()),
18910         day = new_date.getUTCDate(),
18911         month = new_date.getUTCMonth(),
18912         mag = Math.abs(dir),
18913         new_month, test;
18914         dir = dir > 0 ? 1 : -1;
18915         if (mag == 1){
18916             test = dir == -1
18917             // If going back one month, make sure month is not current month
18918             // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
18919             ? function(){
18920                 return new_date.getUTCMonth() == month;
18921             }
18922             // If going forward one month, make sure month is as expected
18923             // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
18924             : function(){
18925                 return new_date.getUTCMonth() != new_month;
18926             };
18927             new_month = month + dir;
18928             new_date.setUTCMonth(new_month);
18929             // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
18930             if (new_month < 0 || new_month > 11) {
18931                 new_month = (new_month + 12) % 12;
18932             }
18933         } else {
18934             // For magnitudes >1, move one month at a time...
18935             for (var i=0; i<mag; i++) {
18936                 // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
18937                 new_date = this.moveMonth(new_date, dir);
18938             }
18939             // ...then reset the day, keeping it in the new month
18940             new_month = new_date.getUTCMonth();
18941             new_date.setUTCDate(day);
18942             test = function(){
18943                 return new_month != new_date.getUTCMonth();
18944             };
18945         }
18946         // Common date-resetting loop -- if date is beyond end of month, make it
18947         // end of month
18948         while (test()){
18949             new_date.setUTCDate(--day);
18950             new_date.setUTCMonth(new_month);
18951         }
18952         return new_date;
18953     },
18954
18955     moveYear: function(date, dir)
18956     {
18957         return this.moveMonth(date, dir*12);
18958     },
18959
18960     dateWithinRange: function(date)
18961     {
18962         return date >= this.startDate && date <= this.endDate;
18963     },
18964
18965     
18966     remove: function() 
18967     {
18968         this.picker().remove();
18969     },
18970     
18971     validateValue : function(value)
18972     {
18973         if(value.length < 1)  {
18974             if(this.allowBlank){
18975                 return true;
18976             }
18977             return false;
18978         }
18979         
18980         if(value.length < this.minLength){
18981             return false;
18982         }
18983         if(value.length > this.maxLength){
18984             return false;
18985         }
18986         if(this.vtype){
18987             var vt = Roo.form.VTypes;
18988             if(!vt[this.vtype](value, this)){
18989                 return false;
18990             }
18991         }
18992         if(typeof this.validator == "function"){
18993             var msg = this.validator(value);
18994             if(msg !== true){
18995                 return false;
18996             }
18997         }
18998         
18999         if(this.regex && !this.regex.test(value)){
19000             return false;
19001         }
19002         
19003         if(typeof(this.parseDate(value)) == 'undefined'){
19004             return false;
19005         }
19006         
19007         if (this.endDate !== Infinity && this.parseDate(value).getTime() > this.endDate.getTime()) {
19008             return false;
19009         }      
19010         
19011         if (this.startDate !== -Infinity && this.parseDate(value).getTime() < this.startDate.getTime()) {
19012             return false;
19013         } 
19014         
19015         
19016         return true;
19017     }
19018    
19019 });
19020
19021 Roo.apply(Roo.bootstrap.DateField,  {
19022     
19023     head : {
19024         tag: 'thead',
19025         cn: [
19026         {
19027             tag: 'tr',
19028             cn: [
19029             {
19030                 tag: 'th',
19031                 cls: 'prev',
19032                 html: '<i class="fa fa-arrow-left"/>'
19033             },
19034             {
19035                 tag: 'th',
19036                 cls: 'switch',
19037                 colspan: '5'
19038             },
19039             {
19040                 tag: 'th',
19041                 cls: 'next',
19042                 html: '<i class="fa fa-arrow-right"/>'
19043             }
19044
19045             ]
19046         }
19047         ]
19048     },
19049     
19050     content : {
19051         tag: 'tbody',
19052         cn: [
19053         {
19054             tag: 'tr',
19055             cn: [
19056             {
19057                 tag: 'td',
19058                 colspan: '7'
19059             }
19060             ]
19061         }
19062         ]
19063     },
19064     
19065     footer : {
19066         tag: 'tfoot',
19067         cn: [
19068         {
19069             tag: 'tr',
19070             cn: [
19071             {
19072                 tag: 'th',
19073                 colspan: '7',
19074                 cls: 'today'
19075             }
19076                     
19077             ]
19078         }
19079         ]
19080     },
19081     
19082     dates:{
19083         en: {
19084             days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
19085             daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
19086             daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
19087             months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
19088             monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
19089             today: "Today"
19090         }
19091     },
19092     
19093     modes: [
19094     {
19095         clsName: 'days',
19096         navFnc: 'Month',
19097         navStep: 1
19098     },
19099     {
19100         clsName: 'months',
19101         navFnc: 'FullYear',
19102         navStep: 1
19103     },
19104     {
19105         clsName: 'years',
19106         navFnc: 'FullYear',
19107         navStep: 10
19108     }]
19109 });
19110
19111 Roo.apply(Roo.bootstrap.DateField,  {
19112   
19113     template : {
19114         tag: 'div',
19115         cls: 'datepicker dropdown-menu roo-dynamic',
19116         cn: [
19117         {
19118             tag: 'div',
19119             cls: 'datepicker-days',
19120             cn: [
19121             {
19122                 tag: 'table',
19123                 cls: 'table-condensed',
19124                 cn:[
19125                 Roo.bootstrap.DateField.head,
19126                 {
19127                     tag: 'tbody'
19128                 },
19129                 Roo.bootstrap.DateField.footer
19130                 ]
19131             }
19132             ]
19133         },
19134         {
19135             tag: 'div',
19136             cls: 'datepicker-months',
19137             cn: [
19138             {
19139                 tag: 'table',
19140                 cls: 'table-condensed',
19141                 cn:[
19142                 Roo.bootstrap.DateField.head,
19143                 Roo.bootstrap.DateField.content,
19144                 Roo.bootstrap.DateField.footer
19145                 ]
19146             }
19147             ]
19148         },
19149         {
19150             tag: 'div',
19151             cls: 'datepicker-years',
19152             cn: [
19153             {
19154                 tag: 'table',
19155                 cls: 'table-condensed',
19156                 cn:[
19157                 Roo.bootstrap.DateField.head,
19158                 Roo.bootstrap.DateField.content,
19159                 Roo.bootstrap.DateField.footer
19160                 ]
19161             }
19162             ]
19163         }
19164         ]
19165     }
19166 });
19167
19168  
19169
19170  /*
19171  * - LGPL
19172  *
19173  * TimeField
19174  * 
19175  */
19176
19177 /**
19178  * @class Roo.bootstrap.TimeField
19179  * @extends Roo.bootstrap.Input
19180  * Bootstrap DateField class
19181  * 
19182  * 
19183  * @constructor
19184  * Create a new TimeField
19185  * @param {Object} config The config object
19186  */
19187
19188 Roo.bootstrap.TimeField = function(config){
19189     Roo.bootstrap.TimeField.superclass.constructor.call(this, config);
19190     this.addEvents({
19191             /**
19192              * @event show
19193              * Fires when this field show.
19194              * @param {Roo.bootstrap.DateField} thisthis
19195              * @param {Mixed} date The date value
19196              */
19197             show : true,
19198             /**
19199              * @event show
19200              * Fires when this field hide.
19201              * @param {Roo.bootstrap.DateField} this
19202              * @param {Mixed} date The date value
19203              */
19204             hide : true,
19205             /**
19206              * @event select
19207              * Fires when select a date.
19208              * @param {Roo.bootstrap.DateField} this
19209              * @param {Mixed} date The date value
19210              */
19211             select : true
19212         });
19213 };
19214
19215 Roo.extend(Roo.bootstrap.TimeField, Roo.bootstrap.Input,  {
19216     
19217     /**
19218      * @cfg {String} format
19219      * The default time format string which can be overriden for localization support.  The format must be
19220      * valid according to {@link Date#parseDate} (defaults to 'H:i').
19221      */
19222     format : "H:i",
19223        
19224     onRender: function(ct, position)
19225     {
19226         
19227         Roo.bootstrap.TimeField.superclass.onRender.call(this, ct, position);
19228                 
19229         this.el.select('>.input-group', true).first().createChild(Roo.bootstrap.TimeField.template);
19230         
19231         this.picker().setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
19232         
19233         this.pop = this.picker().select('>.datepicker-time',true).first();
19234         this.pop.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
19235         
19236         this.picker().on('mousedown', this.onMousedown, this);
19237         this.picker().on('click', this.onClick, this);
19238         
19239         this.picker().addClass('datepicker-dropdown');
19240     
19241         this.fillTime();
19242         this.update();
19243             
19244         this.pop.select('span.hours-up', true).first().on('click', this.onIncrementHours, this);
19245         this.pop.select('span.hours-down', true).first().on('click', this.onDecrementHours, this);
19246         this.pop.select('span.minutes-up', true).first().on('click', this.onIncrementMinutes, this);
19247         this.pop.select('span.minutes-down', true).first().on('click', this.onDecrementMinutes, this);
19248         this.pop.select('button.period', true).first().on('click', this.onTogglePeriod, this);
19249         this.pop.select('button.ok', true).first().on('click', this.setTime, this);
19250
19251     },
19252     
19253     fireKey: function(e){
19254         if (!this.picker().isVisible()){
19255             if (e.keyCode == 27) { // allow escape to hide and re-show picker
19256                 this.show();
19257             }
19258             return;
19259         }
19260
19261         e.preventDefault();
19262         
19263         switch(e.keyCode){
19264             case 27: // escape
19265                 this.hide();
19266                 break;
19267             case 37: // left
19268             case 39: // right
19269                 this.onTogglePeriod();
19270                 break;
19271             case 38: // up
19272                 this.onIncrementMinutes();
19273                 break;
19274             case 40: // down
19275                 this.onDecrementMinutes();
19276                 break;
19277             case 13: // enter
19278             case 9: // tab
19279                 this.setTime();
19280                 break;
19281         }
19282     },
19283     
19284     onClick: function(e) {
19285         e.stopPropagation();
19286         e.preventDefault();
19287     },
19288     
19289     picker : function()
19290     {
19291         return this.el.select('.datepicker', true).first();
19292     },
19293     
19294     fillTime: function()
19295     {    
19296         var time = this.pop.select('tbody', true).first();
19297         
19298         time.dom.innerHTML = '';
19299         
19300         time.createChild({
19301             tag: 'tr',
19302             cn: [
19303                 {
19304                     tag: 'td',
19305                     cn: [
19306                         {
19307                             tag: 'a',
19308                             href: '#',
19309                             cls: 'btn',
19310                             cn: [
19311                                 {
19312                                     tag: 'span',
19313                                     cls: 'hours-up glyphicon glyphicon-chevron-up'
19314                                 }
19315                             ]
19316                         } 
19317                     ]
19318                 },
19319                 {
19320                     tag: 'td',
19321                     cls: 'separator'
19322                 },
19323                 {
19324                     tag: 'td',
19325                     cn: [
19326                         {
19327                             tag: 'a',
19328                             href: '#',
19329                             cls: 'btn',
19330                             cn: [
19331                                 {
19332                                     tag: 'span',
19333                                     cls: 'minutes-up glyphicon glyphicon-chevron-up'
19334                                 }
19335                             ]
19336                         }
19337                     ]
19338                 },
19339                 {
19340                     tag: 'td',
19341                     cls: 'separator'
19342                 }
19343             ]
19344         });
19345         
19346         time.createChild({
19347             tag: 'tr',
19348             cn: [
19349                 {
19350                     tag: 'td',
19351                     cn: [
19352                         {
19353                             tag: 'span',
19354                             cls: 'timepicker-hour',
19355                             html: '00'
19356                         }  
19357                     ]
19358                 },
19359                 {
19360                     tag: 'td',
19361                     cls: 'separator',
19362                     html: ':'
19363                 },
19364                 {
19365                     tag: 'td',
19366                     cn: [
19367                         {
19368                             tag: 'span',
19369                             cls: 'timepicker-minute',
19370                             html: '00'
19371                         }  
19372                     ]
19373                 },
19374                 {
19375                     tag: 'td',
19376                     cls: 'separator'
19377                 },
19378                 {
19379                     tag: 'td',
19380                     cn: [
19381                         {
19382                             tag: 'button',
19383                             type: 'button',
19384                             cls: 'btn btn-primary period',
19385                             html: 'AM'
19386                             
19387                         }
19388                     ]
19389                 }
19390             ]
19391         });
19392         
19393         time.createChild({
19394             tag: 'tr',
19395             cn: [
19396                 {
19397                     tag: 'td',
19398                     cn: [
19399                         {
19400                             tag: 'a',
19401                             href: '#',
19402                             cls: 'btn',
19403                             cn: [
19404                                 {
19405                                     tag: 'span',
19406                                     cls: 'hours-down glyphicon glyphicon-chevron-down'
19407                                 }
19408                             ]
19409                         }
19410                     ]
19411                 },
19412                 {
19413                     tag: 'td',
19414                     cls: 'separator'
19415                 },
19416                 {
19417                     tag: 'td',
19418                     cn: [
19419                         {
19420                             tag: 'a',
19421                             href: '#',
19422                             cls: 'btn',
19423                             cn: [
19424                                 {
19425                                     tag: 'span',
19426                                     cls: 'minutes-down glyphicon glyphicon-chevron-down'
19427                                 }
19428                             ]
19429                         }
19430                     ]
19431                 },
19432                 {
19433                     tag: 'td',
19434                     cls: 'separator'
19435                 }
19436             ]
19437         });
19438         
19439     },
19440     
19441     update: function()
19442     {
19443         
19444         this.time = (typeof(this.time) === 'undefined') ? new Date() : this.time;
19445         
19446         this.fill();
19447     },
19448     
19449     fill: function() 
19450     {
19451         var hours = this.time.getHours();
19452         var minutes = this.time.getMinutes();
19453         var period = 'AM';
19454         
19455         if(hours > 11){
19456             period = 'PM';
19457         }
19458         
19459         if(hours == 0){
19460             hours = 12;
19461         }
19462         
19463         
19464         if(hours > 12){
19465             hours = hours - 12;
19466         }
19467         
19468         if(hours < 10){
19469             hours = '0' + hours;
19470         }
19471         
19472         if(minutes < 10){
19473             minutes = '0' + minutes;
19474         }
19475         
19476         this.pop.select('.timepicker-hour', true).first().dom.innerHTML = hours;
19477         this.pop.select('.timepicker-minute', true).first().dom.innerHTML = minutes;
19478         this.pop.select('button', true).first().dom.innerHTML = period;
19479         
19480     },
19481     
19482     place: function()
19483     {   
19484         this.picker().removeClass(['bottom-left', 'bottom-right', 'top-left', 'top-right']);
19485         
19486         var cls = ['bottom'];
19487         
19488         if((Roo.lib.Dom.getViewHeight() + Roo.get(document.body).getScroll().top) - (this.inputEl().getBottom() + this.picker().getHeight()) < 0){ // top
19489             cls.pop();
19490             cls.push('top');
19491         }
19492         
19493         cls.push('right');
19494         
19495         if((Roo.lib.Dom.getViewWidth() + Roo.get(document.body).getScroll().left) - (this.inputEl().getLeft() + this.picker().getWidth()) < 0){ // left
19496             cls.pop();
19497             cls.push('left');
19498         }
19499         
19500         this.picker().addClass(cls.join('-'));
19501         
19502         var _this = this;
19503         
19504         Roo.each(cls, function(c){
19505             if(c == 'bottom'){
19506                 _this.picker().setTop(_this.inputEl().getHeight());
19507                 return;
19508             }
19509             if(c == 'top'){
19510                 _this.picker().setTop(0 - _this.picker().getHeight());
19511                 return;
19512             }
19513             
19514             if(c == 'left'){
19515                 _this.picker().setLeft(_this.inputEl().getLeft() + _this.inputEl().getWidth() - _this.el.getLeft() - _this.picker().getWidth());
19516                 return;
19517             }
19518             if(c == 'right'){
19519                 _this.picker().setLeft(_this.inputEl().getLeft() - _this.el.getLeft());
19520                 return;
19521             }
19522         });
19523         
19524     },
19525   
19526     onFocus : function()
19527     {
19528         Roo.bootstrap.TimeField.superclass.onFocus.call(this);
19529         this.show();
19530     },
19531     
19532     onBlur : function()
19533     {
19534         Roo.bootstrap.TimeField.superclass.onBlur.call(this);
19535         this.hide();
19536     },
19537     
19538     show : function()
19539     {
19540         this.picker().show();
19541         this.pop.show();
19542         this.update();
19543         this.place();
19544         
19545         this.fireEvent('show', this, this.date);
19546     },
19547     
19548     hide : function()
19549     {
19550         this.picker().hide();
19551         this.pop.hide();
19552         
19553         this.fireEvent('hide', this, this.date);
19554     },
19555     
19556     setTime : function()
19557     {
19558         this.hide();
19559         this.setValue(this.time.format(this.format));
19560         
19561         this.fireEvent('select', this, this.date);
19562         
19563         
19564     },
19565     
19566     onMousedown: function(e){
19567         e.stopPropagation();
19568         e.preventDefault();
19569     },
19570     
19571     onIncrementHours: function()
19572     {
19573         Roo.log('onIncrementHours');
19574         this.time = this.time.add(Date.HOUR, 1);
19575         this.update();
19576         
19577     },
19578     
19579     onDecrementHours: function()
19580     {
19581         Roo.log('onDecrementHours');
19582         this.time = this.time.add(Date.HOUR, -1);
19583         this.update();
19584     },
19585     
19586     onIncrementMinutes: function()
19587     {
19588         Roo.log('onIncrementMinutes');
19589         this.time = this.time.add(Date.MINUTE, 1);
19590         this.update();
19591     },
19592     
19593     onDecrementMinutes: function()
19594     {
19595         Roo.log('onDecrementMinutes');
19596         this.time = this.time.add(Date.MINUTE, -1);
19597         this.update();
19598     },
19599     
19600     onTogglePeriod: function()
19601     {
19602         Roo.log('onTogglePeriod');
19603         this.time = this.time.add(Date.HOUR, 12);
19604         this.update();
19605     }
19606     
19607    
19608 });
19609
19610 Roo.apply(Roo.bootstrap.TimeField,  {
19611     
19612     content : {
19613         tag: 'tbody',
19614         cn: [
19615             {
19616                 tag: 'tr',
19617                 cn: [
19618                 {
19619                     tag: 'td',
19620                     colspan: '7'
19621                 }
19622                 ]
19623             }
19624         ]
19625     },
19626     
19627     footer : {
19628         tag: 'tfoot',
19629         cn: [
19630             {
19631                 tag: 'tr',
19632                 cn: [
19633                 {
19634                     tag: 'th',
19635                     colspan: '7',
19636                     cls: '',
19637                     cn: [
19638                         {
19639                             tag: 'button',
19640                             cls: 'btn btn-info ok',
19641                             html: 'OK'
19642                         }
19643                     ]
19644                 }
19645
19646                 ]
19647             }
19648         ]
19649     }
19650 });
19651
19652 Roo.apply(Roo.bootstrap.TimeField,  {
19653   
19654     template : {
19655         tag: 'div',
19656         cls: 'datepicker dropdown-menu',
19657         cn: [
19658             {
19659                 tag: 'div',
19660                 cls: 'datepicker-time',
19661                 cn: [
19662                 {
19663                     tag: 'table',
19664                     cls: 'table-condensed',
19665                     cn:[
19666                     Roo.bootstrap.TimeField.content,
19667                     Roo.bootstrap.TimeField.footer
19668                     ]
19669                 }
19670                 ]
19671             }
19672         ]
19673     }
19674 });
19675
19676  
19677
19678  /*
19679  * - LGPL
19680  *
19681  * MonthField
19682  * 
19683  */
19684
19685 /**
19686  * @class Roo.bootstrap.MonthField
19687  * @extends Roo.bootstrap.Input
19688  * Bootstrap MonthField class
19689  * 
19690  * @cfg {String} language default en
19691  * 
19692  * @constructor
19693  * Create a new MonthField
19694  * @param {Object} config The config object
19695  */
19696
19697 Roo.bootstrap.MonthField = function(config){
19698     Roo.bootstrap.MonthField.superclass.constructor.call(this, config);
19699     
19700     this.addEvents({
19701         /**
19702          * @event show
19703          * Fires when this field show.
19704          * @param {Roo.bootstrap.MonthField} this
19705          * @param {Mixed} date The date value
19706          */
19707         show : true,
19708         /**
19709          * @event show
19710          * Fires when this field hide.
19711          * @param {Roo.bootstrap.MonthField} this
19712          * @param {Mixed} date The date value
19713          */
19714         hide : true,
19715         /**
19716          * @event select
19717          * Fires when select a date.
19718          * @param {Roo.bootstrap.MonthField} this
19719          * @param {String} oldvalue The old value
19720          * @param {String} newvalue The new value
19721          */
19722         select : true
19723     });
19724 };
19725
19726 Roo.extend(Roo.bootstrap.MonthField, Roo.bootstrap.Input,  {
19727     
19728     onRender: function(ct, position)
19729     {
19730         
19731         Roo.bootstrap.MonthField.superclass.onRender.call(this, ct, position);
19732         
19733         this.language = this.language || 'en';
19734         this.language = this.language in Roo.bootstrap.MonthField.dates ? this.language : this.language.split('-')[0];
19735         this.language = this.language in Roo.bootstrap.MonthField.dates ? this.language : "en";
19736         
19737         this.isRTL = Roo.bootstrap.MonthField.dates[this.language].rtl || false;
19738         this.isInline = false;
19739         this.isInput = true;
19740         this.component = this.el.select('.add-on', true).first() || false;
19741         this.component = (this.component && this.component.length === 0) ? false : this.component;
19742         this.hasInput = this.component && this.inputEL().length;
19743         
19744         this.pickerEl = Roo.get(document.body).createChild(Roo.bootstrap.MonthField.template);
19745         
19746         this.picker().setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
19747         
19748         this.picker().on('mousedown', this.onMousedown, this);
19749         this.picker().on('click', this.onClick, this);
19750         
19751         this.picker().addClass('datepicker-dropdown');
19752         
19753         Roo.each(this.picker().select('tbody > tr > td', true).elements, function(v){
19754             v.setStyle('width', '189px');
19755         });
19756         
19757         this.fillMonths();
19758         
19759         this.update();
19760         
19761         if(this.isInline) {
19762             this.show();
19763         }
19764         
19765     },
19766     
19767     setValue: function(v, suppressEvent)
19768     {   
19769         var o = this.getValue();
19770         
19771         Roo.bootstrap.MonthField.superclass.setValue.call(this, v);
19772         
19773         this.update();
19774
19775         if(suppressEvent !== true){
19776             this.fireEvent('select', this, o, v);
19777         }
19778         
19779     },
19780     
19781     getValue: function()
19782     {
19783         return this.value;
19784     },
19785     
19786     onClick: function(e) 
19787     {
19788         e.stopPropagation();
19789         e.preventDefault();
19790         
19791         var target = e.getTarget();
19792         
19793         if(target.nodeName.toLowerCase() === 'i'){
19794             target = Roo.get(target).dom.parentNode;
19795         }
19796         
19797         var nodeName = target.nodeName;
19798         var className = target.className;
19799         var html = target.innerHTML;
19800         
19801         if(nodeName.toLowerCase() != 'span' || className.indexOf('disabled') > -1 || className.indexOf('month') == -1){
19802             return;
19803         }
19804         
19805         this.vIndex = Roo.bootstrap.MonthField.dates[this.language].monthsShort.indexOf(html);
19806         
19807         this.setValue(Roo.bootstrap.MonthField.dates[this.language].months[this.vIndex]);
19808         
19809         this.hide();
19810                         
19811     },
19812     
19813     picker : function()
19814     {
19815         return this.pickerEl;
19816     },
19817     
19818     fillMonths: function()
19819     {    
19820         var i = 0;
19821         var months = this.picker().select('>.datepicker-months td', true).first();
19822         
19823         months.dom.innerHTML = '';
19824         
19825         while (i < 12) {
19826             var month = {
19827                 tag: 'span',
19828                 cls: 'month',
19829                 html: Roo.bootstrap.MonthField.dates[this.language].monthsShort[i++]
19830             };
19831             
19832             months.createChild(month);
19833         }
19834         
19835     },
19836     
19837     update: function()
19838     {
19839         var _this = this;
19840         
19841         if(typeof(this.vIndex) == 'undefined' && this.value.length){
19842             this.vIndex = Roo.bootstrap.MonthField.dates[this.language].months.indexOf(this.value);
19843         }
19844         
19845         Roo.each(this.pickerEl.select('> .datepicker-months tbody > tr > td > span', true).elements, function(e, k){
19846             e.removeClass('active');
19847             
19848             if(typeof(_this.vIndex) != 'undefined' && k == _this.vIndex){
19849                 e.addClass('active');
19850             }
19851         })
19852     },
19853     
19854     place: function()
19855     {
19856         if(this.isInline) {
19857             return;
19858         }
19859         
19860         this.picker().removeClass(['bottom', 'top']);
19861         
19862         if((Roo.lib.Dom.getViewHeight() + Roo.get(document.body).getScroll().top) - (this.inputEl().getBottom() + this.picker().getHeight()) < 0){
19863             /*
19864              * place to the top of element!
19865              *
19866              */
19867             
19868             this.picker().addClass('top');
19869             this.picker().setTop(this.inputEl().getTop() - this.picker().getHeight()).setLeft(this.inputEl().getLeft());
19870             
19871             return;
19872         }
19873         
19874         this.picker().addClass('bottom');
19875         
19876         this.picker().setTop(this.inputEl().getBottom()).setLeft(this.inputEl().getLeft());
19877     },
19878     
19879     onFocus : function()
19880     {
19881         Roo.bootstrap.MonthField.superclass.onFocus.call(this);
19882         this.show();
19883     },
19884     
19885     onBlur : function()
19886     {
19887         Roo.bootstrap.MonthField.superclass.onBlur.call(this);
19888         
19889         var d = this.inputEl().getValue();
19890         
19891         this.setValue(d);
19892                 
19893         this.hide();
19894     },
19895     
19896     show : function()
19897     {
19898         this.picker().show();
19899         this.picker().select('>.datepicker-months', true).first().show();
19900         this.update();
19901         this.place();
19902         
19903         this.fireEvent('show', this, this.date);
19904     },
19905     
19906     hide : function()
19907     {
19908         if(this.isInline) {
19909             return;
19910         }
19911         this.picker().hide();
19912         this.fireEvent('hide', this, this.date);
19913         
19914     },
19915     
19916     onMousedown: function(e)
19917     {
19918         e.stopPropagation();
19919         e.preventDefault();
19920     },
19921     
19922     keyup: function(e)
19923     {
19924         Roo.bootstrap.MonthField.superclass.keyup.call(this);
19925         this.update();
19926     },
19927
19928     fireKey: function(e)
19929     {
19930         if (!this.picker().isVisible()){
19931             if (e.keyCode == 27)   {// allow escape to hide and re-show picker
19932                 this.show();
19933             }
19934             return;
19935         }
19936         
19937         var dir;
19938         
19939         switch(e.keyCode){
19940             case 27: // escape
19941                 this.hide();
19942                 e.preventDefault();
19943                 break;
19944             case 37: // left
19945             case 39: // right
19946                 dir = e.keyCode == 37 ? -1 : 1;
19947                 
19948                 this.vIndex = this.vIndex + dir;
19949                 
19950                 if(this.vIndex < 0){
19951                     this.vIndex = 0;
19952                 }
19953                 
19954                 if(this.vIndex > 11){
19955                     this.vIndex = 11;
19956                 }
19957                 
19958                 if(isNaN(this.vIndex)){
19959                     this.vIndex = 0;
19960                 }
19961                 
19962                 this.setValue(Roo.bootstrap.MonthField.dates[this.language].months[this.vIndex]);
19963                 
19964                 break;
19965             case 38: // up
19966             case 40: // down
19967                 
19968                 dir = e.keyCode == 38 ? -1 : 1;
19969                 
19970                 this.vIndex = this.vIndex + dir * 4;
19971                 
19972                 if(this.vIndex < 0){
19973                     this.vIndex = 0;
19974                 }
19975                 
19976                 if(this.vIndex > 11){
19977                     this.vIndex = 11;
19978                 }
19979                 
19980                 if(isNaN(this.vIndex)){
19981                     this.vIndex = 0;
19982                 }
19983                 
19984                 this.setValue(Roo.bootstrap.MonthField.dates[this.language].months[this.vIndex]);
19985                 break;
19986                 
19987             case 13: // enter
19988                 
19989                 if(typeof(this.vIndex) != 'undefined' && !isNaN(this.vIndex)){
19990                     this.setValue(Roo.bootstrap.MonthField.dates[this.language].months[this.vIndex]);
19991                 }
19992                 
19993                 this.hide();
19994                 e.preventDefault();
19995                 break;
19996             case 9: // tab
19997                 if(typeof(this.vIndex) != 'undefined' && !isNaN(this.vIndex)){
19998                     this.setValue(Roo.bootstrap.MonthField.dates[this.language].months[this.vIndex]);
19999                 }
20000                 this.hide();
20001                 break;
20002             case 16: // shift
20003             case 17: // ctrl
20004             case 18: // alt
20005                 break;
20006             default :
20007                 this.hide();
20008                 
20009         }
20010     },
20011     
20012     remove: function() 
20013     {
20014         this.picker().remove();
20015     }
20016    
20017 });
20018
20019 Roo.apply(Roo.bootstrap.MonthField,  {
20020     
20021     content : {
20022         tag: 'tbody',
20023         cn: [
20024         {
20025             tag: 'tr',
20026             cn: [
20027             {
20028                 tag: 'td',
20029                 colspan: '7'
20030             }
20031             ]
20032         }
20033         ]
20034     },
20035     
20036     dates:{
20037         en: {
20038             months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
20039             monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
20040         }
20041     }
20042 });
20043
20044 Roo.apply(Roo.bootstrap.MonthField,  {
20045   
20046     template : {
20047         tag: 'div',
20048         cls: 'datepicker dropdown-menu roo-dynamic',
20049         cn: [
20050             {
20051                 tag: 'div',
20052                 cls: 'datepicker-months',
20053                 cn: [
20054                 {
20055                     tag: 'table',
20056                     cls: 'table-condensed',
20057                     cn:[
20058                         Roo.bootstrap.DateField.content
20059                     ]
20060                 }
20061                 ]
20062             }
20063         ]
20064     }
20065 });
20066
20067  
20068
20069  
20070  /*
20071  * - LGPL
20072  *
20073  * CheckBox
20074  * 
20075  */
20076
20077 /**
20078  * @class Roo.bootstrap.CheckBox
20079  * @extends Roo.bootstrap.Input
20080  * Bootstrap CheckBox class
20081  * 
20082  * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
20083  * @cfg {String} inputValue The value that should go into the generated input element's value when checked.
20084  * @cfg {String} boxLabel The text that appears beside the checkbox
20085  * @cfg {String} weight (primary|warning|info|danger|success) The text that appears beside the checkbox
20086  * @cfg {Boolean} checked initnal the element
20087  * @cfg {Boolean} inline inline the element (default false)
20088  * @cfg {String} groupId the checkbox group id // normal just use for checkbox
20089  * 
20090  * @constructor
20091  * Create a new CheckBox
20092  * @param {Object} config The config object
20093  */
20094
20095 Roo.bootstrap.CheckBox = function(config){
20096     Roo.bootstrap.CheckBox.superclass.constructor.call(this, config);
20097    
20098     this.addEvents({
20099         /**
20100         * @event check
20101         * Fires when the element is checked or unchecked.
20102         * @param {Roo.bootstrap.CheckBox} this This input
20103         * @param {Boolean} checked The new checked value
20104         */
20105        check : true
20106     });
20107     
20108 };
20109
20110 Roo.extend(Roo.bootstrap.CheckBox, Roo.bootstrap.Input,  {
20111   
20112     inputType: 'checkbox',
20113     inputValue: 1,
20114     valueOff: 0,
20115     boxLabel: false,
20116     checked: false,
20117     weight : false,
20118     inline: false,
20119     
20120     getAutoCreate : function()
20121     {
20122         var align = (!this.labelAlign) ? this.parentLabelAlign() : this.labelAlign;
20123         
20124         var id = Roo.id();
20125         
20126         var cfg = {};
20127         
20128         cfg.cls = 'form-group ' + this.inputType; //input-group
20129         
20130         if(this.inline){
20131             cfg.cls += ' ' + this.inputType + '-inline';
20132         }
20133         
20134         var input =  {
20135             tag: 'input',
20136             id : id,
20137             type : this.inputType,
20138             value : this.inputValue,
20139             cls : 'roo-' + this.inputType, //'form-box',
20140             placeholder : this.placeholder || ''
20141             
20142         };
20143         
20144         if(this.inputType != 'radio'){
20145             var hidden =  {
20146                 tag: 'input',
20147                 type : 'hidden',
20148                 cls : 'roo-hidden-value',
20149                 value : this.checked ? this.valueOff : this.inputValue
20150             };
20151         }
20152         
20153             
20154         if (this.weight) { // Validity check?
20155             cfg.cls += " " + this.inputType + "-" + this.weight;
20156         }
20157         
20158         if (this.disabled) {
20159             input.disabled=true;
20160         }
20161         
20162         if(this.checked){
20163             input.checked = this.checked;
20164             
20165         }
20166         
20167         
20168         if (this.name) {
20169             
20170             input.name = this.name;
20171             
20172             if(this.inputType != 'radio'){
20173                 hidden.name = this.name;
20174                 input.name = '_hidden_' + this.name;
20175             }
20176         }
20177         
20178         if (this.size) {
20179             input.cls += ' input-' + this.size;
20180         }
20181         
20182         var settings=this;
20183         
20184         ['xs','sm','md','lg'].map(function(size){
20185             if (settings[size]) {
20186                 cfg.cls += ' col-' + size + '-' + settings[size];
20187             }
20188         });
20189         
20190         var inputblock = input;
20191          
20192         if (this.before || this.after) {
20193             
20194             inputblock = {
20195                 cls : 'input-group',
20196                 cn :  [] 
20197             };
20198             
20199             if (this.before) {
20200                 inputblock.cn.push({
20201                     tag :'span',
20202                     cls : 'input-group-addon',
20203                     html : this.before
20204                 });
20205             }
20206             
20207             inputblock.cn.push(input);
20208             
20209             if(this.inputType != 'radio'){
20210                 inputblock.cn.push(hidden);
20211             }
20212             
20213             if (this.after) {
20214                 inputblock.cn.push({
20215                     tag :'span',
20216                     cls : 'input-group-addon',
20217                     html : this.after
20218                 });
20219             }
20220             
20221         }
20222         
20223         if (align ==='left' && this.fieldLabel.length) {
20224 //                Roo.log("left and has label");
20225             cfg.cn = [
20226                 {
20227                     tag: 'label',
20228                     'for' :  id,
20229                     cls : 'control-label',
20230                     html : this.fieldLabel
20231
20232                 },
20233                 {
20234                     cls : "", 
20235                     cn: [
20236                         inputblock
20237                     ]
20238                 }
20239             ];
20240             
20241             if(this.labelWidth > 12){
20242                 cfg.cn[0].style = "width: " + this.labelWidth + 'px';
20243             }
20244             
20245             if(this.labelWidth < 13 && this.labelmd == 0){
20246                 this.labelmd = this.labelWidth;
20247             }
20248             
20249             if(this.labellg > 0){
20250                 cfg.cn[0].cls += ' col-lg-' + this.labellg;
20251                 cfg.cn[1].cls += ' col-lg-' + (12 - this.labellg);
20252             }
20253             
20254             if(this.labelmd > 0){
20255                 cfg.cn[0].cls += ' col-md-' + this.labelmd;
20256                 cfg.cn[1].cls += ' col-md-' + (12 - this.labelmd);
20257             }
20258             
20259             if(this.labelsm > 0){
20260                 cfg.cn[0].cls += ' col-sm-' + this.labelsm;
20261                 cfg.cn[1].cls += ' col-sm-' + (12 - this.labelsm);
20262             }
20263             
20264             if(this.labelxs > 0){
20265                 cfg.cn[0].cls += ' col-xs-' + this.labelxs;
20266                 cfg.cn[1].cls += ' col-xs-' + (12 - this.labelxs);
20267             }
20268             
20269         } else if ( this.fieldLabel.length) {
20270 //                Roo.log(" label");
20271                 cfg.cn = [
20272                    
20273                     {
20274                         tag: this.boxLabel ? 'span' : 'label',
20275                         'for': id,
20276                         cls: 'control-label box-input-label',
20277                         //cls : 'input-group-addon',
20278                         html : this.fieldLabel
20279                         
20280                     },
20281                     
20282                     inputblock
20283                     
20284                 ];
20285
20286         } else {
20287             
20288 //                Roo.log(" no label && no align");
20289                 cfg.cn = [  inputblock ] ;
20290                 
20291                 
20292         }
20293         
20294         if(this.boxLabel){
20295              var boxLabelCfg = {
20296                 tag: 'label',
20297                 //'for': id, // box label is handled by onclick - so no for...
20298                 cls: 'box-label',
20299                 html: this.boxLabel
20300             };
20301             
20302             if(this.tooltip){
20303                 boxLabelCfg.tooltip = this.tooltip;
20304             }
20305              
20306             cfg.cn.push(boxLabelCfg);
20307         }
20308         
20309         if(this.inputType != 'radio'){
20310             cfg.cn.push(hidden);
20311         }
20312         
20313         return cfg;
20314         
20315     },
20316     
20317     /**
20318      * return the real input element.
20319      */
20320     inputEl: function ()
20321     {
20322         return this.el.select('input.roo-' + this.inputType,true).first();
20323     },
20324     hiddenEl: function ()
20325     {
20326         return this.el.select('input.roo-hidden-value',true).first();
20327     },
20328     
20329     labelEl: function()
20330     {
20331         return this.el.select('label.control-label',true).first();
20332     },
20333     /* depricated... */
20334     
20335     label: function()
20336     {
20337         return this.labelEl();
20338     },
20339     
20340     boxLabelEl: function()
20341     {
20342         return this.el.select('label.box-label',true).first();
20343     },
20344     
20345     initEvents : function()
20346     {
20347 //        Roo.bootstrap.CheckBox.superclass.initEvents.call(this);
20348         
20349         this.inputEl().on('click', this.onClick,  this);
20350         
20351         if (this.boxLabel) { 
20352             this.el.select('label.box-label',true).first().on('click', this.onClick,  this);
20353         }
20354         
20355         this.startValue = this.getValue();
20356         
20357         if(this.groupId){
20358             Roo.bootstrap.CheckBox.register(this);
20359         }
20360     },
20361     
20362     onClick : function()
20363     {   
20364         this.setChecked(!this.checked);
20365     },
20366     
20367     setChecked : function(state,suppressEvent)
20368     {
20369         this.startValue = this.getValue();
20370
20371         if(this.inputType == 'radio'){
20372             
20373             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
20374                 e.dom.checked = false;
20375             });
20376             
20377             this.inputEl().dom.checked = true;
20378             
20379             this.inputEl().dom.value = this.inputValue;
20380             
20381             if(suppressEvent !== true){
20382                 this.fireEvent('check', this, true);
20383             }
20384             
20385             this.validate();
20386             
20387             return;
20388         }
20389         
20390         this.checked = state;
20391         
20392         this.inputEl().dom.checked = state;
20393         
20394         
20395         this.hiddenEl().dom.value = state ? this.inputValue : this.valueOff;
20396         
20397         if(suppressEvent !== true){
20398             this.fireEvent('check', this, state);
20399         }
20400         
20401         this.validate();
20402     },
20403     
20404     getValue : function()
20405     {
20406         if(this.inputType == 'radio'){
20407             return this.getGroupValue();
20408         }
20409         
20410         return this.hiddenEl().dom.value;
20411         
20412     },
20413     
20414     getGroupValue : function()
20415     {
20416         if(typeof(this.el.up('form').child('input[name='+this.name+']:checked', true)) == 'undefined'){
20417             return '';
20418         }
20419         
20420         return this.el.up('form').child('input[name='+this.name+']:checked', true).value;
20421     },
20422     
20423     setValue : function(v,suppressEvent)
20424     {
20425         if(this.inputType == 'radio'){
20426             this.setGroupValue(v, suppressEvent);
20427             return;
20428         }
20429         
20430         this.setChecked(((typeof(v) == 'undefined') ? this.checked : (String(v) === String(this.inputValue))), suppressEvent);
20431         
20432         this.validate();
20433     },
20434     
20435     setGroupValue : function(v, suppressEvent)
20436     {
20437         this.startValue = this.getValue();
20438         
20439         Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
20440             e.dom.checked = false;
20441             
20442             if(e.dom.value == v){
20443                 e.dom.checked = true;
20444             }
20445         });
20446         
20447         if(suppressEvent !== true){
20448             this.fireEvent('check', this, true);
20449         }
20450
20451         this.validate();
20452         
20453         return;
20454     },
20455     
20456     validate : function()
20457     {
20458         if(
20459                 this.disabled || 
20460                 (this.inputType == 'radio' && this.validateRadio()) ||
20461                 (this.inputType == 'checkbox' && this.validateCheckbox())
20462         ){
20463             this.markValid();
20464             return true;
20465         }
20466         
20467         this.markInvalid();
20468         return false;
20469     },
20470     
20471     validateRadio : function()
20472     {
20473         if(this.allowBlank){
20474             return true;
20475         }
20476         
20477         var valid = false;
20478         
20479         Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
20480             if(!e.dom.checked){
20481                 return;
20482             }
20483             
20484             valid = true;
20485             
20486             return false;
20487         });
20488         
20489         return valid;
20490     },
20491     
20492     validateCheckbox : function()
20493     {
20494         if(!this.groupId){
20495             return (this.getValue() == this.inputValue || this.allowBlank) ? true : false;
20496             //return (this.getValue() == this.inputValue) ? true : false;
20497         }
20498         
20499         var group = Roo.bootstrap.CheckBox.get(this.groupId);
20500         
20501         if(!group){
20502             return false;
20503         }
20504         
20505         var r = false;
20506         
20507         for(var i in group){
20508             if(r){
20509                 break;
20510             }
20511             
20512             r = (group[i].getValue() == group[i].inputValue) ? true : false;
20513         }
20514         
20515         return r;
20516     },
20517     
20518     /**
20519      * Mark this field as valid
20520      */
20521     markValid : function()
20522     {
20523         var _this = this;
20524         
20525         this.fireEvent('valid', this);
20526         
20527         var label = Roo.bootstrap.FieldLabel.get(this.name + '-group');
20528         
20529         if(this.groupId){
20530             label = Roo.bootstrap.FieldLabel.get(this.groupId + '-group');
20531         }
20532         
20533         if(label){
20534             label.markValid();
20535         }
20536
20537         if(this.inputType == 'radio'){
20538             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
20539                 e.findParent('.form-group', false, true).removeClass([_this.invalidClass, _this.validClass]);
20540                 e.findParent('.form-group', false, true).addClass(_this.validClass);
20541             });
20542             
20543             return;
20544         }
20545
20546         if(!this.groupId){
20547             this.el.findParent('.form-group', false, true).removeClass([this.invalidClass, this.validClass]);
20548             this.el.findParent('.form-group', false, true).addClass(this.validClass);
20549             return;
20550         }
20551         
20552         var group = Roo.bootstrap.CheckBox.get(this.groupId);
20553         
20554         if(!group){
20555             return;
20556         }
20557         
20558         for(var i in group){
20559             group[i].el.findParent('.form-group', false, true).removeClass([this.invalidClass, this.validClass]);
20560             group[i].el.findParent('.form-group', false, true).addClass(this.validClass);
20561         }
20562     },
20563     
20564      /**
20565      * Mark this field as invalid
20566      * @param {String} msg The validation message
20567      */
20568     markInvalid : function(msg)
20569     {
20570         if(this.allowBlank){
20571             return;
20572         }
20573         
20574         var _this = this;
20575         
20576         this.fireEvent('invalid', this, msg);
20577         
20578         var label = Roo.bootstrap.FieldLabel.get(this.name + '-group');
20579         
20580         if(this.groupId){
20581             label = Roo.bootstrap.FieldLabel.get(this.groupId + '-group');
20582         }
20583         
20584         if(label){
20585             label.markInvalid();
20586         }
20587             
20588         if(this.inputType == 'radio'){
20589             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
20590                 e.findParent('.form-group', false, true).removeClass([_this.invalidClass, _this.validClass]);
20591                 e.findParent('.form-group', false, true).addClass(_this.invalidClass);
20592             });
20593             
20594             return;
20595         }
20596         
20597         if(!this.groupId){
20598             this.el.findParent('.form-group', false, true).removeClass([this.invalidClass, this.validClass]);
20599             this.el.findParent('.form-group', false, true).addClass(this.invalidClass);
20600             return;
20601         }
20602         
20603         var group = Roo.bootstrap.CheckBox.get(this.groupId);
20604         
20605         if(!group){
20606             return;
20607         }
20608         
20609         for(var i in group){
20610             group[i].el.findParent('.form-group', false, true).removeClass([this.invalidClass, this.validClass]);
20611             group[i].el.findParent('.form-group', false, true).addClass(this.invalidClass);
20612         }
20613         
20614     },
20615     
20616     clearInvalid : function()
20617     {
20618         Roo.bootstrap.Input.prototype.clearInvalid.call(this);
20619         
20620         // this.el.findParent('.form-group', false, true).removeClass([this.invalidClass, this.validClass]);
20621         
20622         var label = Roo.bootstrap.FieldLabel.get(this.name + '-group');
20623         
20624         if (label) {
20625             label.iconEl.removeClass(label.validClass);
20626             label.iconEl.removeClass(label.invalidClass);
20627         }
20628     },
20629     
20630     disable : function()
20631     {
20632         if(this.inputType != 'radio'){
20633             Roo.bootstrap.CheckBox.superclass.disable.call(this);
20634             return;
20635         }
20636         
20637         var _this = this;
20638         
20639         if(this.rendered){
20640             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
20641                 _this.getActionEl().addClass(this.disabledClass);
20642                 e.dom.disabled = true;
20643             });
20644         }
20645         
20646         this.disabled = true;
20647         this.fireEvent("disable", this);
20648         return this;
20649     },
20650
20651     enable : function()
20652     {
20653         if(this.inputType != 'radio'){
20654             Roo.bootstrap.CheckBox.superclass.enable.call(this);
20655             return;
20656         }
20657         
20658         var _this = this;
20659         
20660         if(this.rendered){
20661             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
20662                 _this.getActionEl().removeClass(this.disabledClass);
20663                 e.dom.disabled = false;
20664             });
20665         }
20666         
20667         this.disabled = false;
20668         this.fireEvent("enable", this);
20669         return this;
20670     }
20671
20672 });
20673
20674 Roo.apply(Roo.bootstrap.CheckBox, {
20675     
20676     groups: {},
20677     
20678      /**
20679     * register a CheckBox Group
20680     * @param {Roo.bootstrap.CheckBox} the CheckBox to add
20681     */
20682     register : function(checkbox)
20683     {
20684         if(typeof(this.groups[checkbox.groupId]) == 'undefined'){
20685             this.groups[checkbox.groupId] = {};
20686         }
20687         
20688         if(this.groups[checkbox.groupId].hasOwnProperty(checkbox.name)){
20689             return;
20690         }
20691         
20692         this.groups[checkbox.groupId][checkbox.name] = checkbox;
20693         
20694     },
20695     /**
20696     * fetch a CheckBox Group based on the group ID
20697     * @param {string} the group ID
20698     * @returns {Roo.bootstrap.CheckBox} the CheckBox group
20699     */
20700     get: function(groupId) {
20701         if (typeof(this.groups[groupId]) == 'undefined') {
20702             return false;
20703         }
20704         
20705         return this.groups[groupId] ;
20706     }
20707     
20708     
20709 });
20710 /*
20711  * - LGPL
20712  *
20713  * RadioItem
20714  * 
20715  */
20716
20717 /**
20718  * @class Roo.bootstrap.Radio
20719  * @extends Roo.bootstrap.Component
20720  * Bootstrap Radio class
20721  * @cfg {String} boxLabel - the label associated
20722  * @cfg {String} value - the value of radio
20723  * 
20724  * @constructor
20725  * Create a new Radio
20726  * @param {Object} config The config object
20727  */
20728 Roo.bootstrap.Radio = function(config){
20729     Roo.bootstrap.Radio.superclass.constructor.call(this, config);
20730     
20731 };
20732
20733 Roo.extend(Roo.bootstrap.Radio, Roo.bootstrap.Component, {
20734     
20735     boxLabel : '',
20736     
20737     value : '',
20738     
20739     getAutoCreate : function()
20740     {
20741         var cfg = {
20742             tag : 'div',
20743             cls : 'form-group radio',
20744             cn : [
20745                 {
20746                     tag : 'label',
20747                     cls : 'box-label',
20748                     html : this.boxLabel
20749                 }
20750             ]
20751         };
20752         
20753         return cfg;
20754     },
20755     
20756     initEvents : function() 
20757     {
20758         this.parent().register(this);
20759         
20760         this.el.on('click', this.onClick, this);
20761         
20762     },
20763     
20764     onClick : function()
20765     {
20766         this.setChecked(true);
20767     },
20768     
20769     setChecked : function(state, suppressEvent)
20770     {
20771         this.parent().setValue(this.value, suppressEvent);
20772         
20773     }
20774     
20775 });
20776  
20777
20778  /*
20779  * - LGPL
20780  *
20781  * Input
20782  * 
20783  */
20784
20785 /**
20786  * @class Roo.bootstrap.SecurePass
20787  * @extends Roo.bootstrap.Input
20788  * Bootstrap SecurePass class
20789  *
20790  * 
20791  * @constructor
20792  * Create a new SecurePass
20793  * @param {Object} config The config object
20794  */
20795  
20796 Roo.bootstrap.SecurePass = function (config) {
20797     // these go here, so the translation tool can replace them..
20798     this.errors = {
20799         PwdEmpty: "Please type a password, and then retype it to confirm.",
20800         PwdShort: "Your password must be at least 6 characters long. Please type a different password.",
20801         PwdLong: "Your password can't contain more than 16 characters. Please type a different password.",
20802         PwdBadChar: "The password contains characters that aren't allowed. Please type a different password.",
20803         IDInPwd: "Your password can't include the part of your ID. Please type a different password.",
20804         FNInPwd: "Your password can't contain your first name. Please type a different password.",
20805         LNInPwd: "Your password can't contain your last name. Please type a different password.",
20806         TooWeak: "Your password is Too Weak."
20807     },
20808     this.meterLabel = "Password strength:";
20809     this.pwdStrengths = ["Too Weak", "Weak", "Medium", "Strong"];
20810     this.meterClass = [
20811         "roo-password-meter-tooweak", 
20812         "roo-password-meter-weak", 
20813         "roo-password-meter-medium", 
20814         "roo-password-meter-strong", 
20815         "roo-password-meter-grey"
20816     ];
20817     
20818     this.errors = {};
20819     
20820     Roo.bootstrap.SecurePass.superclass.constructor.call(this, config);
20821 }
20822
20823 Roo.extend(Roo.bootstrap.SecurePass, Roo.bootstrap.Input, {
20824     /**
20825      * @cfg {String/Object} errors A Error spec, or true for a default spec (defaults to
20826      * {
20827      *  PwdEmpty: "Please type a password, and then retype it to confirm.",
20828      *  PwdShort: "Your password must be at least 6 characters long. Please type a different password.",
20829      *  PwdLong: "Your password can't contain more than 16 characters. Please type a different password.",
20830      *  PwdBadChar: "The password contains characters that aren't allowed. Please type a different password.",
20831      *  IDInPwd: "Your password can't include the part of your ID. Please type a different password.",
20832      *  FNInPwd: "Your password can't contain your first name. Please type a different password.",
20833      *  LNInPwd: "Your password can't contain your last name. Please type a different password."
20834      * })
20835      */
20836     // private
20837     
20838     meterWidth: 300,
20839     errorMsg :'',    
20840     errors: false,
20841     imageRoot: '/',
20842     /**
20843      * @cfg {String/Object} Label for the strength meter (defaults to
20844      * 'Password strength:')
20845      */
20846     // private
20847     meterLabel: '',
20848     /**
20849      * @cfg {String/Object} pwdStrengths A pwdStrengths spec, or true for a default spec (defaults to
20850      * ['Weak', 'Medium', 'Strong'])
20851      */
20852     // private    
20853     pwdStrengths: false,    
20854     // private
20855     strength: 0,
20856     // private
20857     _lastPwd: null,
20858     // private
20859     kCapitalLetter: 0,
20860     kSmallLetter: 1,
20861     kDigit: 2,
20862     kPunctuation: 3,
20863     
20864     insecure: false,
20865     // private
20866     initEvents: function ()
20867     {
20868         Roo.bootstrap.SecurePass.superclass.initEvents.call(this);
20869
20870         if (this.el.is('input[type=password]') && Roo.isSafari) {
20871             this.el.on('keydown', this.SafariOnKeyDown, this);
20872         }
20873
20874         this.el.on('keyup', this.checkStrength, this, {buffer: 50});
20875     },
20876     // private
20877     onRender: function (ct, position)
20878     {
20879         Roo.bootstrap.SecurePass.superclass.onRender.call(this, ct, position);
20880         this.wrap = this.el.wrap({cls: 'x-form-field-wrap'});
20881         this.trigger = this.wrap.createChild({tag: 'div', cls: 'StrengthMeter ' + this.triggerClass});
20882
20883         this.trigger.createChild({
20884                    cn: [
20885                     {
20886                     //id: 'PwdMeter',
20887                     tag: 'div',
20888                     cls: 'roo-password-meter-grey col-xs-12',
20889                     style: {
20890                         //width: 0,
20891                         //width: this.meterWidth + 'px'                                                
20892                         }
20893                     },
20894                     {                            
20895                          cls: 'roo-password-meter-text'                          
20896                     }
20897                 ]            
20898         });
20899
20900          
20901         if (this.hideTrigger) {
20902             this.trigger.setDisplayed(false);
20903         }
20904         this.setSize(this.width || '', this.height || '');
20905     },
20906     // private
20907     onDestroy: function ()
20908     {
20909         if (this.trigger) {
20910             this.trigger.removeAllListeners();
20911             this.trigger.remove();
20912         }
20913         if (this.wrap) {
20914             this.wrap.remove();
20915         }
20916         Roo.bootstrap.TriggerField.superclass.onDestroy.call(this);
20917     },
20918     // private
20919     checkStrength: function ()
20920     {
20921         var pwd = this.inputEl().getValue();
20922         if (pwd == this._lastPwd) {
20923             return;
20924         }
20925
20926         var strength;
20927         if (this.ClientSideStrongPassword(pwd)) {
20928             strength = 3;
20929         } else if (this.ClientSideMediumPassword(pwd)) {
20930             strength = 2;
20931         } else if (this.ClientSideWeakPassword(pwd)) {
20932             strength = 1;
20933         } else {
20934             strength = 0;
20935         }
20936         
20937         Roo.log('strength1: ' + strength);
20938         
20939         //var pm = this.trigger.child('div/div/div').dom;
20940         var pm = this.trigger.child('div/div');
20941         pm.removeClass(this.meterClass);
20942         pm.addClass(this.meterClass[strength]);
20943                 
20944         
20945         var pt = this.trigger.child('/div').child('>*[class=roo-password-meter-text]').dom;        
20946                 
20947         pt.innerHTML = this.meterLabel + '&nbsp;' + this.pwdStrengths[strength];
20948         
20949         this._lastPwd = pwd;
20950     },
20951     reset: function ()
20952     {
20953         Roo.bootstrap.SecurePass.superclass.reset.call(this);
20954         
20955         this._lastPwd = '';
20956         
20957         var pm = this.trigger.child('div/div');
20958         pm.removeClass(this.meterClass);
20959         pm.addClass('roo-password-meter-grey');        
20960         
20961         
20962         var pt = this.trigger.child('/div').child('>*[class=roo-password-meter-text]').dom;        
20963         
20964         pt.innerHTML = '';
20965         this.inputEl().dom.type='password';
20966     },
20967     // private
20968     validateValue: function (value)
20969     {
20970         
20971         if (!Roo.bootstrap.SecurePass.superclass.validateValue.call(this, value)) {
20972             return false;
20973         }
20974         if (value.length == 0) {
20975             if (this.allowBlank) {
20976                 this.clearInvalid();
20977                 return true;
20978             }
20979
20980             this.markInvalid(this.errors.PwdEmpty);
20981             this.errorMsg = this.errors.PwdEmpty;
20982             return false;
20983         }
20984         
20985         if(this.insecure){
20986             return true;
20987         }
20988         
20989         if ('[\x21-\x7e]*'.match(value)) {
20990             this.markInvalid(this.errors.PwdBadChar);
20991             this.errorMsg = this.errors.PwdBadChar;
20992             return false;
20993         }
20994         if (value.length < 6) {
20995             this.markInvalid(this.errors.PwdShort);
20996             this.errorMsg = this.errors.PwdShort;
20997             return false;
20998         }
20999         if (value.length > 16) {
21000             this.markInvalid(this.errors.PwdLong);
21001             this.errorMsg = this.errors.PwdLong;
21002             return false;
21003         }
21004         var strength;
21005         if (this.ClientSideStrongPassword(value)) {
21006             strength = 3;
21007         } else if (this.ClientSideMediumPassword(value)) {
21008             strength = 2;
21009         } else if (this.ClientSideWeakPassword(value)) {
21010             strength = 1;
21011         } else {
21012             strength = 0;
21013         }
21014
21015         
21016         if (strength < 2) {
21017             //this.markInvalid(this.errors.TooWeak);
21018             this.errorMsg = this.errors.TooWeak;
21019             //return false;
21020         }
21021         
21022         
21023         console.log('strength2: ' + strength);
21024         
21025         //var pm = this.trigger.child('div/div/div').dom;
21026         
21027         var pm = this.trigger.child('div/div');
21028         pm.removeClass(this.meterClass);
21029         pm.addClass(this.meterClass[strength]);
21030                 
21031         var pt = this.trigger.child('/div').child('>*[class=roo-password-meter-text]').dom;        
21032                 
21033         pt.innerHTML = this.meterLabel + '&nbsp;' + this.pwdStrengths[strength];
21034         
21035         this.errorMsg = ''; 
21036         return true;
21037     },
21038     // private
21039     CharacterSetChecks: function (type)
21040     {
21041         this.type = type;
21042         this.fResult = false;
21043     },
21044     // private
21045     isctype: function (character, type)
21046     {
21047         switch (type) {  
21048             case this.kCapitalLetter:
21049                 if (character >= 'A' && character <= 'Z') {
21050                     return true;
21051                 }
21052                 break;
21053             
21054             case this.kSmallLetter:
21055                 if (character >= 'a' && character <= 'z') {
21056                     return true;
21057                 }
21058                 break;
21059             
21060             case this.kDigit:
21061                 if (character >= '0' && character <= '9') {
21062                     return true;
21063                 }
21064                 break;
21065             
21066             case this.kPunctuation:
21067                 if ('!@#$%^&*()_+-=\'";:[{]}|.>,</?`~'.indexOf(character) >= 0) {
21068                     return true;
21069                 }
21070                 break;
21071             
21072             default:
21073                 return false;
21074         }
21075
21076     },
21077     // private
21078     IsLongEnough: function (pwd, size)
21079     {
21080         return !(pwd == null || isNaN(size) || pwd.length < size);
21081     },
21082     // private
21083     SpansEnoughCharacterSets: function (word, nb)
21084     {
21085         if (!this.IsLongEnough(word, nb))
21086         {
21087             return false;
21088         }
21089
21090         var characterSetChecks = new Array(
21091             new this.CharacterSetChecks(this.kCapitalLetter), new this.CharacterSetChecks(this.kSmallLetter),
21092             new this.CharacterSetChecks(this.kDigit), new this.CharacterSetChecks(this.kPunctuation)
21093         );
21094         
21095         for (var index = 0; index < word.length; ++index) {
21096             for (var nCharSet = 0; nCharSet < characterSetChecks.length; ++nCharSet) {
21097                 if (!characterSetChecks[nCharSet].fResult && this.isctype(word.charAt(index), characterSetChecks[nCharSet].type)) {
21098                     characterSetChecks[nCharSet].fResult = true;
21099                     break;
21100                 }
21101             }
21102         }
21103
21104         var nCharSets = 0;
21105         for (var nCharSet = 0; nCharSet < characterSetChecks.length; ++nCharSet) {
21106             if (characterSetChecks[nCharSet].fResult) {
21107                 ++nCharSets;
21108             }
21109         }
21110
21111         if (nCharSets < nb) {
21112             return false;
21113         }
21114         return true;
21115     },
21116     // private
21117     ClientSideStrongPassword: function (pwd)
21118     {
21119         return this.IsLongEnough(pwd, 8) && this.SpansEnoughCharacterSets(pwd, 3);
21120     },
21121     // private
21122     ClientSideMediumPassword: function (pwd)
21123     {
21124         return this.IsLongEnough(pwd, 7) && this.SpansEnoughCharacterSets(pwd, 2);
21125     },
21126     // private
21127     ClientSideWeakPassword: function (pwd)
21128     {
21129         return this.IsLongEnough(pwd, 6) || !this.IsLongEnough(pwd, 0);
21130     }
21131           
21132 })//<script type="text/javascript">
21133
21134 /*
21135  * Based  Ext JS Library 1.1.1
21136  * Copyright(c) 2006-2007, Ext JS, LLC.
21137  * LGPL
21138  *
21139  */
21140  
21141 /**
21142  * @class Roo.HtmlEditorCore
21143  * @extends Roo.Component
21144  * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
21145  *
21146  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
21147  */
21148
21149 Roo.HtmlEditorCore = function(config){
21150     
21151     
21152     Roo.HtmlEditorCore.superclass.constructor.call(this, config);
21153     
21154     
21155     this.addEvents({
21156         /**
21157          * @event initialize
21158          * Fires when the editor is fully initialized (including the iframe)
21159          * @param {Roo.HtmlEditorCore} this
21160          */
21161         initialize: true,
21162         /**
21163          * @event activate
21164          * Fires when the editor is first receives the focus. Any insertion must wait
21165          * until after this event.
21166          * @param {Roo.HtmlEditorCore} this
21167          */
21168         activate: true,
21169          /**
21170          * @event beforesync
21171          * Fires before the textarea is updated with content from the editor iframe. Return false
21172          * to cancel the sync.
21173          * @param {Roo.HtmlEditorCore} this
21174          * @param {String} html
21175          */
21176         beforesync: true,
21177          /**
21178          * @event beforepush
21179          * Fires before the iframe editor is updated with content from the textarea. Return false
21180          * to cancel the push.
21181          * @param {Roo.HtmlEditorCore} this
21182          * @param {String} html
21183          */
21184         beforepush: true,
21185          /**
21186          * @event sync
21187          * Fires when the textarea is updated with content from the editor iframe.
21188          * @param {Roo.HtmlEditorCore} this
21189          * @param {String} html
21190          */
21191         sync: true,
21192          /**
21193          * @event push
21194          * Fires when the iframe editor is updated with content from the textarea.
21195          * @param {Roo.HtmlEditorCore} this
21196          * @param {String} html
21197          */
21198         push: true,
21199         
21200         /**
21201          * @event editorevent
21202          * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
21203          * @param {Roo.HtmlEditorCore} this
21204          */
21205         editorevent: true
21206         
21207     });
21208     
21209     // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
21210     
21211     // defaults : white / black...
21212     this.applyBlacklists();
21213     
21214     
21215     
21216 };
21217
21218
21219 Roo.extend(Roo.HtmlEditorCore, Roo.Component,  {
21220
21221
21222      /**
21223      * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field 
21224      */
21225     
21226     owner : false,
21227     
21228      /**
21229      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
21230      *                        Roo.resizable.
21231      */
21232     resizable : false,
21233      /**
21234      * @cfg {Number} height (in pixels)
21235      */   
21236     height: 300,
21237    /**
21238      * @cfg {Number} width (in pixels)
21239      */   
21240     width: 500,
21241     
21242     /**
21243      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
21244      * 
21245      */
21246     stylesheets: false,
21247     
21248     // id of frame..
21249     frameId: false,
21250     
21251     // private properties
21252     validationEvent : false,
21253     deferHeight: true,
21254     initialized : false,
21255     activated : false,
21256     sourceEditMode : false,
21257     onFocus : Roo.emptyFn,
21258     iframePad:3,
21259     hideMode:'offsets',
21260     
21261     clearUp: true,
21262     
21263     // blacklist + whitelisted elements..
21264     black: false,
21265     white: false,
21266      
21267     
21268
21269     /**
21270      * Protected method that will not generally be called directly. It
21271      * is called when the editor initializes the iframe with HTML contents. Override this method if you
21272      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
21273      */
21274     getDocMarkup : function(){
21275         // body styles..
21276         var st = '';
21277         
21278         // inherit styels from page...?? 
21279         if (this.stylesheets === false) {
21280             
21281             Roo.get(document.head).select('style').each(function(node) {
21282                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
21283             });
21284             
21285             Roo.get(document.head).select('link').each(function(node) { 
21286                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
21287             });
21288             
21289         } else if (!this.stylesheets.length) {
21290                 // simple..
21291                 st = '<style type="text/css">' +
21292                     'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
21293                    '</style>';
21294         } else { 
21295             
21296         }
21297         
21298         st +=  '<style type="text/css">' +
21299             'IMG { cursor: pointer } ' +
21300         '</style>';
21301
21302         
21303         return '<html><head>' + st  +
21304             //<style type="text/css">' +
21305             //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
21306             //'</style>' +
21307             ' </head><body class="roo-htmleditor-body"></body></html>';
21308     },
21309
21310     // private
21311     onRender : function(ct, position)
21312     {
21313         var _t = this;
21314         //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
21315         this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
21316         
21317         
21318         this.el.dom.style.border = '0 none';
21319         this.el.dom.setAttribute('tabIndex', -1);
21320         this.el.addClass('x-hidden hide');
21321         
21322         
21323         
21324         if(Roo.isIE){ // fix IE 1px bogus margin
21325             this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
21326         }
21327        
21328         
21329         this.frameId = Roo.id();
21330         
21331          
21332         
21333         var iframe = this.owner.wrap.createChild({
21334             tag: 'iframe',
21335             cls: 'form-control', // bootstrap..
21336             id: this.frameId,
21337             name: this.frameId,
21338             frameBorder : 'no',
21339             'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL  :  "javascript:false"
21340         }, this.el
21341         );
21342         
21343         
21344         this.iframe = iframe.dom;
21345
21346          this.assignDocWin();
21347         
21348         this.doc.designMode = 'on';
21349        
21350         this.doc.open();
21351         this.doc.write(this.getDocMarkup());
21352         this.doc.close();
21353
21354         
21355         var task = { // must defer to wait for browser to be ready
21356             run : function(){
21357                 //console.log("run task?" + this.doc.readyState);
21358                 this.assignDocWin();
21359                 if(this.doc.body || this.doc.readyState == 'complete'){
21360                     try {
21361                         this.doc.designMode="on";
21362                     } catch (e) {
21363                         return;
21364                     }
21365                     Roo.TaskMgr.stop(task);
21366                     this.initEditor.defer(10, this);
21367                 }
21368             },
21369             interval : 10,
21370             duration: 10000,
21371             scope: this
21372         };
21373         Roo.TaskMgr.start(task);
21374
21375     },
21376
21377     // private
21378     onResize : function(w, h)
21379     {
21380          Roo.log('resize: ' +w + ',' + h );
21381         //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
21382         if(!this.iframe){
21383             return;
21384         }
21385         if(typeof w == 'number'){
21386             
21387             this.iframe.style.width = w + 'px';
21388         }
21389         if(typeof h == 'number'){
21390             
21391             this.iframe.style.height = h + 'px';
21392             if(this.doc){
21393                 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
21394             }
21395         }
21396         
21397     },
21398
21399     /**
21400      * Toggles the editor between standard and source edit mode.
21401      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
21402      */
21403     toggleSourceEdit : function(sourceEditMode){
21404         
21405         this.sourceEditMode = sourceEditMode === true;
21406         
21407         if(this.sourceEditMode){
21408  
21409             Roo.get(this.iframe).addClass(['x-hidden','hide']);     //FIXME - what's the BS styles for these
21410             
21411         }else{
21412             Roo.get(this.iframe).removeClass(['x-hidden','hide']);
21413             //this.iframe.className = '';
21414             this.deferFocus();
21415         }
21416         //this.setSize(this.owner.wrap.getSize());
21417         //this.fireEvent('editmodechange', this, this.sourceEditMode);
21418     },
21419
21420     
21421   
21422
21423     /**
21424      * Protected method that will not generally be called directly. If you need/want
21425      * custom HTML cleanup, this is the method you should override.
21426      * @param {String} html The HTML to be cleaned
21427      * return {String} The cleaned HTML
21428      */
21429     cleanHtml : function(html){
21430         html = String(html);
21431         if(html.length > 5){
21432             if(Roo.isSafari){ // strip safari nonsense
21433                 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
21434             }
21435         }
21436         if(html == '&nbsp;'){
21437             html = '';
21438         }
21439         return html;
21440     },
21441
21442     /**
21443      * HTML Editor -> Textarea
21444      * Protected method that will not generally be called directly. Syncs the contents
21445      * of the editor iframe with the textarea.
21446      */
21447     syncValue : function(){
21448         if(this.initialized){
21449             var bd = (this.doc.body || this.doc.documentElement);
21450             //this.cleanUpPaste(); -- this is done else where and causes havoc..
21451             var html = bd.innerHTML;
21452             if(Roo.isSafari){
21453                 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
21454                 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
21455                 if(m && m[1]){
21456                     html = '<div style="'+m[0]+'">' + html + '</div>';
21457                 }
21458             }
21459             html = this.cleanHtml(html);
21460             // fix up the special chars.. normaly like back quotes in word...
21461             // however we do not want to do this with chinese..
21462             html = html.replace(/([\x80-\uffff])/g, function (a, b) {
21463                 var cc = b.charCodeAt();
21464                 if (
21465                     (cc >= 0x4E00 && cc < 0xA000 ) ||
21466                     (cc >= 0x3400 && cc < 0x4E00 ) ||
21467                     (cc >= 0xf900 && cc < 0xfb00 )
21468                 ) {
21469                         return b;
21470                 }
21471                 return "&#"+cc+";" 
21472             });
21473             if(this.owner.fireEvent('beforesync', this, html) !== false){
21474                 this.el.dom.value = html;
21475                 this.owner.fireEvent('sync', this, html);
21476             }
21477         }
21478     },
21479
21480     /**
21481      * Protected method that will not generally be called directly. Pushes the value of the textarea
21482      * into the iframe editor.
21483      */
21484     pushValue : function(){
21485         if(this.initialized){
21486             var v = this.el.dom.value.trim();
21487             
21488 //            if(v.length < 1){
21489 //                v = '&#160;';
21490 //            }
21491             
21492             if(this.owner.fireEvent('beforepush', this, v) !== false){
21493                 var d = (this.doc.body || this.doc.documentElement);
21494                 d.innerHTML = v;
21495                 this.cleanUpPaste();
21496                 this.el.dom.value = d.innerHTML;
21497                 this.owner.fireEvent('push', this, v);
21498             }
21499         }
21500     },
21501
21502     // private
21503     deferFocus : function(){
21504         this.focus.defer(10, this);
21505     },
21506
21507     // doc'ed in Field
21508     focus : function(){
21509         if(this.win && !this.sourceEditMode){
21510             this.win.focus();
21511         }else{
21512             this.el.focus();
21513         }
21514     },
21515     
21516     assignDocWin: function()
21517     {
21518         var iframe = this.iframe;
21519         
21520          if(Roo.isIE){
21521             this.doc = iframe.contentWindow.document;
21522             this.win = iframe.contentWindow;
21523         } else {
21524 //            if (!Roo.get(this.frameId)) {
21525 //                return;
21526 //            }
21527 //            this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
21528 //            this.win = Roo.get(this.frameId).dom.contentWindow;
21529             
21530             if (!Roo.get(this.frameId) && !iframe.contentDocument) {
21531                 return;
21532             }
21533             
21534             this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
21535             this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
21536         }
21537     },
21538     
21539     // private
21540     initEditor : function(){
21541         //console.log("INIT EDITOR");
21542         this.assignDocWin();
21543         
21544         
21545         
21546         this.doc.designMode="on";
21547         this.doc.open();
21548         this.doc.write(this.getDocMarkup());
21549         this.doc.close();
21550         
21551         var dbody = (this.doc.body || this.doc.documentElement);
21552         //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
21553         // this copies styles from the containing element into thsi one..
21554         // not sure why we need all of this..
21555         //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
21556         
21557         //var ss = this.el.getStyles( 'background-image', 'background-repeat');
21558         //ss['background-attachment'] = 'fixed'; // w3c
21559         dbody.bgProperties = 'fixed'; // ie
21560         //Roo.DomHelper.applyStyles(dbody, ss);
21561         Roo.EventManager.on(this.doc, {
21562             //'mousedown': this.onEditorEvent,
21563             'mouseup': this.onEditorEvent,
21564             'dblclick': this.onEditorEvent,
21565             'click': this.onEditorEvent,
21566             'keyup': this.onEditorEvent,
21567             buffer:100,
21568             scope: this
21569         });
21570         if(Roo.isGecko){
21571             Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
21572         }
21573         if(Roo.isIE || Roo.isSafari || Roo.isOpera){
21574             Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
21575         }
21576         this.initialized = true;
21577
21578         this.owner.fireEvent('initialize', this);
21579         this.pushValue();
21580     },
21581
21582     // private
21583     onDestroy : function(){
21584         
21585         
21586         
21587         if(this.rendered){
21588             
21589             //for (var i =0; i < this.toolbars.length;i++) {
21590             //    // fixme - ask toolbars for heights?
21591             //    this.toolbars[i].onDestroy();
21592            // }
21593             
21594             //this.wrap.dom.innerHTML = '';
21595             //this.wrap.remove();
21596         }
21597     },
21598
21599     // private
21600     onFirstFocus : function(){
21601         
21602         this.assignDocWin();
21603         
21604         
21605         this.activated = true;
21606          
21607     
21608         if(Roo.isGecko){ // prevent silly gecko errors
21609             this.win.focus();
21610             var s = this.win.getSelection();
21611             if(!s.focusNode || s.focusNode.nodeType != 3){
21612                 var r = s.getRangeAt(0);
21613                 r.selectNodeContents((this.doc.body || this.doc.documentElement));
21614                 r.collapse(true);
21615                 this.deferFocus();
21616             }
21617             try{
21618                 this.execCmd('useCSS', true);
21619                 this.execCmd('styleWithCSS', false);
21620             }catch(e){}
21621         }
21622         this.owner.fireEvent('activate', this);
21623     },
21624
21625     // private
21626     adjustFont: function(btn){
21627         var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
21628         //if(Roo.isSafari){ // safari
21629         //    adjust *= 2;
21630        // }
21631         var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
21632         if(Roo.isSafari){ // safari
21633             var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
21634             v =  (v < 10) ? 10 : v;
21635             v =  (v > 48) ? 48 : v;
21636             v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
21637             
21638         }
21639         
21640         
21641         v = Math.max(1, v+adjust);
21642         
21643         this.execCmd('FontSize', v  );
21644     },
21645
21646     onEditorEvent : function(e)
21647     {
21648         this.owner.fireEvent('editorevent', this, e);
21649       //  this.updateToolbar();
21650         this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
21651     },
21652
21653     insertTag : function(tg)
21654     {
21655         // could be a bit smarter... -> wrap the current selected tRoo..
21656         if (tg.toLowerCase() == 'span' || tg.toLowerCase() == 'code') {
21657             
21658             range = this.createRange(this.getSelection());
21659             var wrappingNode = this.doc.createElement(tg.toLowerCase());
21660             wrappingNode.appendChild(range.extractContents());
21661             range.insertNode(wrappingNode);
21662
21663             return;
21664             
21665             
21666             
21667         }
21668         this.execCmd("formatblock",   tg);
21669         
21670     },
21671     
21672     insertText : function(txt)
21673     {
21674         
21675         
21676         var range = this.createRange();
21677         range.deleteContents();
21678                //alert(Sender.getAttribute('label'));
21679                
21680         range.insertNode(this.doc.createTextNode(txt));
21681     } ,
21682     
21683      
21684
21685     /**
21686      * Executes a Midas editor command on the editor document and performs necessary focus and
21687      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
21688      * @param {String} cmd The Midas command
21689      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
21690      */
21691     relayCmd : function(cmd, value){
21692         this.win.focus();
21693         this.execCmd(cmd, value);
21694         this.owner.fireEvent('editorevent', this);
21695         //this.updateToolbar();
21696         this.owner.deferFocus();
21697     },
21698
21699     /**
21700      * Executes a Midas editor command directly on the editor document.
21701      * For visual commands, you should use {@link #relayCmd} instead.
21702      * <b>This should only be called after the editor is initialized.</b>
21703      * @param {String} cmd The Midas command
21704      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
21705      */
21706     execCmd : function(cmd, value){
21707         this.doc.execCommand(cmd, false, value === undefined ? null : value);
21708         this.syncValue();
21709     },
21710  
21711  
21712    
21713     /**
21714      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
21715      * to insert tRoo.
21716      * @param {String} text | dom node.. 
21717      */
21718     insertAtCursor : function(text)
21719     {
21720         
21721         if(!this.activated){
21722             return;
21723         }
21724         /*
21725         if(Roo.isIE){
21726             this.win.focus();
21727             var r = this.doc.selection.createRange();
21728             if(r){
21729                 r.collapse(true);
21730                 r.pasteHTML(text);
21731                 this.syncValue();
21732                 this.deferFocus();
21733             
21734             }
21735             return;
21736         }
21737         */
21738         if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
21739             this.win.focus();
21740             
21741             
21742             // from jquery ui (MIT licenced)
21743             var range, node;
21744             var win = this.win;
21745             
21746             if (win.getSelection && win.getSelection().getRangeAt) {
21747                 range = win.getSelection().getRangeAt(0);
21748                 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
21749                 range.insertNode(node);
21750             } else if (win.document.selection && win.document.selection.createRange) {
21751                 // no firefox support
21752                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
21753                 win.document.selection.createRange().pasteHTML(txt);
21754             } else {
21755                 // no firefox support
21756                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
21757                 this.execCmd('InsertHTML', txt);
21758             } 
21759             
21760             this.syncValue();
21761             
21762             this.deferFocus();
21763         }
21764     },
21765  // private
21766     mozKeyPress : function(e){
21767         if(e.ctrlKey){
21768             var c = e.getCharCode(), cmd;
21769           
21770             if(c > 0){
21771                 c = String.fromCharCode(c).toLowerCase();
21772                 switch(c){
21773                     case 'b':
21774                         cmd = 'bold';
21775                         break;
21776                     case 'i':
21777                         cmd = 'italic';
21778                         break;
21779                     
21780                     case 'u':
21781                         cmd = 'underline';
21782                         break;
21783                     
21784                     case 'v':
21785                         this.cleanUpPaste.defer(100, this);
21786                         return;
21787                         
21788                 }
21789                 if(cmd){
21790                     this.win.focus();
21791                     this.execCmd(cmd);
21792                     this.deferFocus();
21793                     e.preventDefault();
21794                 }
21795                 
21796             }
21797         }
21798     },
21799
21800     // private
21801     fixKeys : function(){ // load time branching for fastest keydown performance
21802         if(Roo.isIE){
21803             return function(e){
21804                 var k = e.getKey(), r;
21805                 if(k == e.TAB){
21806                     e.stopEvent();
21807                     r = this.doc.selection.createRange();
21808                     if(r){
21809                         r.collapse(true);
21810                         r.pasteHTML('&#160;&#160;&#160;&#160;');
21811                         this.deferFocus();
21812                     }
21813                     return;
21814                 }
21815                 
21816                 if(k == e.ENTER){
21817                     r = this.doc.selection.createRange();
21818                     if(r){
21819                         var target = r.parentElement();
21820                         if(!target || target.tagName.toLowerCase() != 'li'){
21821                             e.stopEvent();
21822                             r.pasteHTML('<br />');
21823                             r.collapse(false);
21824                             r.select();
21825                         }
21826                     }
21827                 }
21828                 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
21829                     this.cleanUpPaste.defer(100, this);
21830                     return;
21831                 }
21832                 
21833                 
21834             };
21835         }else if(Roo.isOpera){
21836             return function(e){
21837                 var k = e.getKey();
21838                 if(k == e.TAB){
21839                     e.stopEvent();
21840                     this.win.focus();
21841                     this.execCmd('InsertHTML','&#160;&#160;&#160;&#160;');
21842                     this.deferFocus();
21843                 }
21844                 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
21845                     this.cleanUpPaste.defer(100, this);
21846                     return;
21847                 }
21848                 
21849             };
21850         }else if(Roo.isSafari){
21851             return function(e){
21852                 var k = e.getKey();
21853                 
21854                 if(k == e.TAB){
21855                     e.stopEvent();
21856                     this.execCmd('InsertText','\t');
21857                     this.deferFocus();
21858                     return;
21859                 }
21860                if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
21861                     this.cleanUpPaste.defer(100, this);
21862                     return;
21863                 }
21864                 
21865              };
21866         }
21867     }(),
21868     
21869     getAllAncestors: function()
21870     {
21871         var p = this.getSelectedNode();
21872         var a = [];
21873         if (!p) {
21874             a.push(p); // push blank onto stack..
21875             p = this.getParentElement();
21876         }
21877         
21878         
21879         while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
21880             a.push(p);
21881             p = p.parentNode;
21882         }
21883         a.push(this.doc.body);
21884         return a;
21885     },
21886     lastSel : false,
21887     lastSelNode : false,
21888     
21889     
21890     getSelection : function() 
21891     {
21892         this.assignDocWin();
21893         return Roo.isIE ? this.doc.selection : this.win.getSelection();
21894     },
21895     
21896     getSelectedNode: function() 
21897     {
21898         // this may only work on Gecko!!!
21899         
21900         // should we cache this!!!!
21901         
21902         
21903         
21904          
21905         var range = this.createRange(this.getSelection()).cloneRange();
21906         
21907         if (Roo.isIE) {
21908             var parent = range.parentElement();
21909             while (true) {
21910                 var testRange = range.duplicate();
21911                 testRange.moveToElementText(parent);
21912                 if (testRange.inRange(range)) {
21913                     break;
21914                 }
21915                 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
21916                     break;
21917                 }
21918                 parent = parent.parentElement;
21919             }
21920             return parent;
21921         }
21922         
21923         // is ancestor a text element.
21924         var ac =  range.commonAncestorContainer;
21925         if (ac.nodeType == 3) {
21926             ac = ac.parentNode;
21927         }
21928         
21929         var ar = ac.childNodes;
21930          
21931         var nodes = [];
21932         var other_nodes = [];
21933         var has_other_nodes = false;
21934         for (var i=0;i<ar.length;i++) {
21935             if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ? 
21936                 continue;
21937             }
21938             // fullly contained node.
21939             
21940             if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
21941                 nodes.push(ar[i]);
21942                 continue;
21943             }
21944             
21945             // probably selected..
21946             if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
21947                 other_nodes.push(ar[i]);
21948                 continue;
21949             }
21950             // outer..
21951             if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0))  {
21952                 continue;
21953             }
21954             
21955             
21956             has_other_nodes = true;
21957         }
21958         if (!nodes.length && other_nodes.length) {
21959             nodes= other_nodes;
21960         }
21961         if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
21962             return false;
21963         }
21964         
21965         return nodes[0];
21966     },
21967     createRange: function(sel)
21968     {
21969         // this has strange effects when using with 
21970         // top toolbar - not sure if it's a great idea.
21971         //this.editor.contentWindow.focus();
21972         if (typeof sel != "undefined") {
21973             try {
21974                 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
21975             } catch(e) {
21976                 return this.doc.createRange();
21977             }
21978         } else {
21979             return this.doc.createRange();
21980         }
21981     },
21982     getParentElement: function()
21983     {
21984         
21985         this.assignDocWin();
21986         var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
21987         
21988         var range = this.createRange(sel);
21989          
21990         try {
21991             var p = range.commonAncestorContainer;
21992             while (p.nodeType == 3) { // text node
21993                 p = p.parentNode;
21994             }
21995             return p;
21996         } catch (e) {
21997             return null;
21998         }
21999     
22000     },
22001     /***
22002      *
22003      * Range intersection.. the hard stuff...
22004      *  '-1' = before
22005      *  '0' = hits..
22006      *  '1' = after.
22007      *         [ -- selected range --- ]
22008      *   [fail]                        [fail]
22009      *
22010      *    basically..
22011      *      if end is before start or  hits it. fail.
22012      *      if start is after end or hits it fail.
22013      *
22014      *   if either hits (but other is outside. - then it's not 
22015      *   
22016      *    
22017      **/
22018     
22019     
22020     // @see http://www.thismuchiknow.co.uk/?p=64.
22021     rangeIntersectsNode : function(range, node)
22022     {
22023         var nodeRange = node.ownerDocument.createRange();
22024         try {
22025             nodeRange.selectNode(node);
22026         } catch (e) {
22027             nodeRange.selectNodeContents(node);
22028         }
22029     
22030         var rangeStartRange = range.cloneRange();
22031         rangeStartRange.collapse(true);
22032     
22033         var rangeEndRange = range.cloneRange();
22034         rangeEndRange.collapse(false);
22035     
22036         var nodeStartRange = nodeRange.cloneRange();
22037         nodeStartRange.collapse(true);
22038     
22039         var nodeEndRange = nodeRange.cloneRange();
22040         nodeEndRange.collapse(false);
22041     
22042         return rangeStartRange.compareBoundaryPoints(
22043                  Range.START_TO_START, nodeEndRange) == -1 &&
22044                rangeEndRange.compareBoundaryPoints(
22045                  Range.START_TO_START, nodeStartRange) == 1;
22046         
22047          
22048     },
22049     rangeCompareNode : function(range, node)
22050     {
22051         var nodeRange = node.ownerDocument.createRange();
22052         try {
22053             nodeRange.selectNode(node);
22054         } catch (e) {
22055             nodeRange.selectNodeContents(node);
22056         }
22057         
22058         
22059         range.collapse(true);
22060     
22061         nodeRange.collapse(true);
22062      
22063         var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
22064         var ee = range.compareBoundaryPoints(  Range.END_TO_END, nodeRange);
22065          
22066         //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
22067         
22068         var nodeIsBefore   =  ss == 1;
22069         var nodeIsAfter    = ee == -1;
22070         
22071         if (nodeIsBefore && nodeIsAfter) {
22072             return 0; // outer
22073         }
22074         if (!nodeIsBefore && nodeIsAfter) {
22075             return 1; //right trailed.
22076         }
22077         
22078         if (nodeIsBefore && !nodeIsAfter) {
22079             return 2;  // left trailed.
22080         }
22081         // fully contined.
22082         return 3;
22083     },
22084
22085     // private? - in a new class?
22086     cleanUpPaste :  function()
22087     {
22088         // cleans up the whole document..
22089         Roo.log('cleanuppaste');
22090         
22091         this.cleanUpChildren(this.doc.body);
22092         var clean = this.cleanWordChars(this.doc.body.innerHTML);
22093         if (clean != this.doc.body.innerHTML) {
22094             this.doc.body.innerHTML = clean;
22095         }
22096         
22097     },
22098     
22099     cleanWordChars : function(input) {// change the chars to hex code
22100         var he = Roo.HtmlEditorCore;
22101         
22102         var output = input;
22103         Roo.each(he.swapCodes, function(sw) { 
22104             var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
22105             
22106             output = output.replace(swapper, sw[1]);
22107         });
22108         
22109         return output;
22110     },
22111     
22112     
22113     cleanUpChildren : function (n)
22114     {
22115         if (!n.childNodes.length) {
22116             return;
22117         }
22118         for (var i = n.childNodes.length-1; i > -1 ; i--) {
22119            this.cleanUpChild(n.childNodes[i]);
22120         }
22121     },
22122     
22123     
22124         
22125     
22126     cleanUpChild : function (node)
22127     {
22128         var ed = this;
22129         //console.log(node);
22130         if (node.nodeName == "#text") {
22131             // clean up silly Windows -- stuff?
22132             return; 
22133         }
22134         if (node.nodeName == "#comment") {
22135             node.parentNode.removeChild(node);
22136             // clean up silly Windows -- stuff?
22137             return; 
22138         }
22139         var lcname = node.tagName.toLowerCase();
22140         // we ignore whitelists... ?? = not really the way to go, but we probably have not got a full
22141         // whitelist of tags..
22142         
22143         if (this.black.indexOf(lcname) > -1 && this.clearUp ) {
22144             // remove node.
22145             node.parentNode.removeChild(node);
22146             return;
22147             
22148         }
22149         
22150         var remove_keep_children= Roo.HtmlEditorCore.remove.indexOf(node.tagName.toLowerCase()) > -1;
22151         
22152         // remove <a name=....> as rendering on yahoo mailer is borked with this.
22153         // this will have to be flaged elsewhere - perhaps ablack=name... on the mailer..
22154         
22155         //if (node.tagName.toLowerCase() == 'a' && !node.hasAttribute('href')) {
22156         //    remove_keep_children = true;
22157         //}
22158         
22159         if (remove_keep_children) {
22160             this.cleanUpChildren(node);
22161             // inserts everything just before this node...
22162             while (node.childNodes.length) {
22163                 var cn = node.childNodes[0];
22164                 node.removeChild(cn);
22165                 node.parentNode.insertBefore(cn, node);
22166             }
22167             node.parentNode.removeChild(node);
22168             return;
22169         }
22170         
22171         if (!node.attributes || !node.attributes.length) {
22172             this.cleanUpChildren(node);
22173             return;
22174         }
22175         
22176         function cleanAttr(n,v)
22177         {
22178             
22179             if (v.match(/^\./) || v.match(/^\//)) {
22180                 return;
22181             }
22182             if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/)) {
22183                 return;
22184             }
22185             if (v.match(/^#/)) {
22186                 return;
22187             }
22188 //            Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
22189             node.removeAttribute(n);
22190             
22191         }
22192         
22193         var cwhite = this.cwhite;
22194         var cblack = this.cblack;
22195             
22196         function cleanStyle(n,v)
22197         {
22198             if (v.match(/expression/)) { //XSS?? should we even bother..
22199                 node.removeAttribute(n);
22200                 return;
22201             }
22202             
22203             var parts = v.split(/;/);
22204             var clean = [];
22205             
22206             Roo.each(parts, function(p) {
22207                 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
22208                 if (!p.length) {
22209                     return true;
22210                 }
22211                 var l = p.split(':').shift().replace(/\s+/g,'');
22212                 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
22213                 
22214                 if ( cwhite.length && cblack.indexOf(l) > -1) {
22215 //                    Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
22216                     //node.removeAttribute(n);
22217                     return true;
22218                 }
22219                 //Roo.log()
22220                 // only allow 'c whitelisted system attributes'
22221                 if ( cwhite.length &&  cwhite.indexOf(l) < 0) {
22222 //                    Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
22223                     //node.removeAttribute(n);
22224                     return true;
22225                 }
22226                 
22227                 
22228                  
22229                 
22230                 clean.push(p);
22231                 return true;
22232             });
22233             if (clean.length) { 
22234                 node.setAttribute(n, clean.join(';'));
22235             } else {
22236                 node.removeAttribute(n);
22237             }
22238             
22239         }
22240         
22241         
22242         for (var i = node.attributes.length-1; i > -1 ; i--) {
22243             var a = node.attributes[i];
22244             //console.log(a);
22245             
22246             if (a.name.toLowerCase().substr(0,2)=='on')  {
22247                 node.removeAttribute(a.name);
22248                 continue;
22249             }
22250             if (Roo.HtmlEditorCore.ablack.indexOf(a.name.toLowerCase()) > -1) {
22251                 node.removeAttribute(a.name);
22252                 continue;
22253             }
22254             if (Roo.HtmlEditorCore.aclean.indexOf(a.name.toLowerCase()) > -1) {
22255                 cleanAttr(a.name,a.value); // fixme..
22256                 continue;
22257             }
22258             if (a.name == 'style') {
22259                 cleanStyle(a.name,a.value);
22260                 continue;
22261             }
22262             /// clean up MS crap..
22263             // tecnically this should be a list of valid class'es..
22264             
22265             
22266             if (a.name == 'class') {
22267                 if (a.value.match(/^Mso/)) {
22268                     node.className = '';
22269                 }
22270                 
22271                 if (a.value.match(/^body$/)) {
22272                     node.className = '';
22273                 }
22274                 continue;
22275             }
22276             
22277             // style cleanup!?
22278             // class cleanup?
22279             
22280         }
22281         
22282         
22283         this.cleanUpChildren(node);
22284         
22285         
22286     },
22287     
22288     /**
22289      * Clean up MS wordisms...
22290      */
22291     cleanWord : function(node)
22292     {
22293         
22294         
22295         if (!node) {
22296             this.cleanWord(this.doc.body);
22297             return;
22298         }
22299         if (node.nodeName == "#text") {
22300             // clean up silly Windows -- stuff?
22301             return; 
22302         }
22303         if (node.nodeName == "#comment") {
22304             node.parentNode.removeChild(node);
22305             // clean up silly Windows -- stuff?
22306             return; 
22307         }
22308         
22309         if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
22310             node.parentNode.removeChild(node);
22311             return;
22312         }
22313         
22314         // remove - but keep children..
22315         if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|font)/)) {
22316             while (node.childNodes.length) {
22317                 var cn = node.childNodes[0];
22318                 node.removeChild(cn);
22319                 node.parentNode.insertBefore(cn, node);
22320             }
22321             node.parentNode.removeChild(node);
22322             this.iterateChildren(node, this.cleanWord);
22323             return;
22324         }
22325         // clean styles
22326         if (node.className.length) {
22327             
22328             var cn = node.className.split(/\W+/);
22329             var cna = [];
22330             Roo.each(cn, function(cls) {
22331                 if (cls.match(/Mso[a-zA-Z]+/)) {
22332                     return;
22333                 }
22334                 cna.push(cls);
22335             });
22336             node.className = cna.length ? cna.join(' ') : '';
22337             if (!cna.length) {
22338                 node.removeAttribute("class");
22339             }
22340         }
22341         
22342         if (node.hasAttribute("lang")) {
22343             node.removeAttribute("lang");
22344         }
22345         
22346         if (node.hasAttribute("style")) {
22347             
22348             var styles = node.getAttribute("style").split(";");
22349             var nstyle = [];
22350             Roo.each(styles, function(s) {
22351                 if (!s.match(/:/)) {
22352                     return;
22353                 }
22354                 var kv = s.split(":");
22355                 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
22356                     return;
22357                 }
22358                 // what ever is left... we allow.
22359                 nstyle.push(s);
22360             });
22361             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
22362             if (!nstyle.length) {
22363                 node.removeAttribute('style');
22364             }
22365         }
22366         this.iterateChildren(node, this.cleanWord);
22367         
22368         
22369         
22370     },
22371     /**
22372      * iterateChildren of a Node, calling fn each time, using this as the scole..
22373      * @param {DomNode} node node to iterate children of.
22374      * @param {Function} fn method of this class to call on each item.
22375      */
22376     iterateChildren : function(node, fn)
22377     {
22378         if (!node.childNodes.length) {
22379                 return;
22380         }
22381         for (var i = node.childNodes.length-1; i > -1 ; i--) {
22382            fn.call(this, node.childNodes[i])
22383         }
22384     },
22385     
22386     
22387     /**
22388      * cleanTableWidths.
22389      *
22390      * Quite often pasting from word etc.. results in tables with column and widths.
22391      * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
22392      *
22393      */
22394     cleanTableWidths : function(node)
22395     {
22396          
22397          
22398         if (!node) {
22399             this.cleanTableWidths(this.doc.body);
22400             return;
22401         }
22402         
22403         // ignore list...
22404         if (node.nodeName == "#text" || node.nodeName == "#comment") {
22405             return; 
22406         }
22407         Roo.log(node.tagName);
22408         if (!node.tagName.toLowerCase().match(/^(table|td|tr)$/)) {
22409             this.iterateChildren(node, this.cleanTableWidths);
22410             return;
22411         }
22412         if (node.hasAttribute('width')) {
22413             node.removeAttribute('width');
22414         }
22415         
22416          
22417         if (node.hasAttribute("style")) {
22418             // pretty basic...
22419             
22420             var styles = node.getAttribute("style").split(";");
22421             var nstyle = [];
22422             Roo.each(styles, function(s) {
22423                 if (!s.match(/:/)) {
22424                     return;
22425                 }
22426                 var kv = s.split(":");
22427                 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
22428                     return;
22429                 }
22430                 // what ever is left... we allow.
22431                 nstyle.push(s);
22432             });
22433             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
22434             if (!nstyle.length) {
22435                 node.removeAttribute('style');
22436             }
22437         }
22438         
22439         this.iterateChildren(node, this.cleanTableWidths);
22440         
22441         
22442     },
22443     
22444     
22445     
22446     
22447     domToHTML : function(currentElement, depth, nopadtext) {
22448         
22449         depth = depth || 0;
22450         nopadtext = nopadtext || false;
22451     
22452         if (!currentElement) {
22453             return this.domToHTML(this.doc.body);
22454         }
22455         
22456         //Roo.log(currentElement);
22457         var j;
22458         var allText = false;
22459         var nodeName = currentElement.nodeName;
22460         var tagName = Roo.util.Format.htmlEncode(currentElement.tagName);
22461         
22462         if  (nodeName == '#text') {
22463             
22464             return nopadtext ? currentElement.nodeValue : currentElement.nodeValue.trim();
22465         }
22466         
22467         
22468         var ret = '';
22469         if (nodeName != 'BODY') {
22470              
22471             var i = 0;
22472             // Prints the node tagName, such as <A>, <IMG>, etc
22473             if (tagName) {
22474                 var attr = [];
22475                 for(i = 0; i < currentElement.attributes.length;i++) {
22476                     // quoting?
22477                     var aname = currentElement.attributes.item(i).name;
22478                     if (!currentElement.attributes.item(i).value.length) {
22479                         continue;
22480                     }
22481                     attr.push(aname + '="' + Roo.util.Format.htmlEncode(currentElement.attributes.item(i).value) + '"' );
22482                 }
22483                 
22484                 ret = "<"+currentElement.tagName+ ( attr.length ? (' ' + attr.join(' ') ) : '') + ">";
22485             } 
22486             else {
22487                 
22488                 // eack
22489             }
22490         } else {
22491             tagName = false;
22492         }
22493         if (['IMG', 'BR', 'HR', 'INPUT'].indexOf(tagName) > -1) {
22494             return ret;
22495         }
22496         if (['PRE', 'TEXTAREA', 'TD', 'A', 'SPAN'].indexOf(tagName) > -1) { // or code?
22497             nopadtext = true;
22498         }
22499         
22500         
22501         // Traverse the tree
22502         i = 0;
22503         var currentElementChild = currentElement.childNodes.item(i);
22504         var allText = true;
22505         var innerHTML  = '';
22506         lastnode = '';
22507         while (currentElementChild) {
22508             // Formatting code (indent the tree so it looks nice on the screen)
22509             var nopad = nopadtext;
22510             if (lastnode == 'SPAN') {
22511                 nopad  = true;
22512             }
22513             // text
22514             if  (currentElementChild.nodeName == '#text') {
22515                 var toadd = Roo.util.Format.htmlEncode(currentElementChild.nodeValue);
22516                 toadd = nopadtext ? toadd : toadd.trim();
22517                 if (!nopad && toadd.length > 80) {
22518                     innerHTML  += "\n" + (new Array( depth + 1 )).join( "  "  );
22519                 }
22520                 innerHTML  += toadd;
22521                 
22522                 i++;
22523                 currentElementChild = currentElement.childNodes.item(i);
22524                 lastNode = '';
22525                 continue;
22526             }
22527             allText = false;
22528             
22529             innerHTML  += nopad ? '' : "\n" + (new Array( depth + 1 )).join( "  "  );
22530                 
22531             // Recursively traverse the tree structure of the child node
22532             innerHTML   += this.domToHTML(currentElementChild, depth+1, nopadtext);
22533             lastnode = currentElementChild.nodeName;
22534             i++;
22535             currentElementChild=currentElement.childNodes.item(i);
22536         }
22537         
22538         ret += innerHTML;
22539         
22540         if (!allText) {
22541                 // The remaining code is mostly for formatting the tree
22542             ret+= nopadtext ? '' : "\n" + (new Array( depth  )).join( "  "  );
22543         }
22544         
22545         
22546         if (tagName) {
22547             ret+= "</"+tagName+">";
22548         }
22549         return ret;
22550         
22551     },
22552         
22553     applyBlacklists : function()
22554     {
22555         var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white  : [];
22556         var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black :  [];
22557         
22558         this.white = [];
22559         this.black = [];
22560         Roo.each(Roo.HtmlEditorCore.white, function(tag) {
22561             if (b.indexOf(tag) > -1) {
22562                 return;
22563             }
22564             this.white.push(tag);
22565             
22566         }, this);
22567         
22568         Roo.each(w, function(tag) {
22569             if (b.indexOf(tag) > -1) {
22570                 return;
22571             }
22572             if (this.white.indexOf(tag) > -1) {
22573                 return;
22574             }
22575             this.white.push(tag);
22576             
22577         }, this);
22578         
22579         
22580         Roo.each(Roo.HtmlEditorCore.black, function(tag) {
22581             if (w.indexOf(tag) > -1) {
22582                 return;
22583             }
22584             this.black.push(tag);
22585             
22586         }, this);
22587         
22588         Roo.each(b, function(tag) {
22589             if (w.indexOf(tag) > -1) {
22590                 return;
22591             }
22592             if (this.black.indexOf(tag) > -1) {
22593                 return;
22594             }
22595             this.black.push(tag);
22596             
22597         }, this);
22598         
22599         
22600         w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite  : [];
22601         b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack :  [];
22602         
22603         this.cwhite = [];
22604         this.cblack = [];
22605         Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
22606             if (b.indexOf(tag) > -1) {
22607                 return;
22608             }
22609             this.cwhite.push(tag);
22610             
22611         }, this);
22612         
22613         Roo.each(w, function(tag) {
22614             if (b.indexOf(tag) > -1) {
22615                 return;
22616             }
22617             if (this.cwhite.indexOf(tag) > -1) {
22618                 return;
22619             }
22620             this.cwhite.push(tag);
22621             
22622         }, this);
22623         
22624         
22625         Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
22626             if (w.indexOf(tag) > -1) {
22627                 return;
22628             }
22629             this.cblack.push(tag);
22630             
22631         }, this);
22632         
22633         Roo.each(b, function(tag) {
22634             if (w.indexOf(tag) > -1) {
22635                 return;
22636             }
22637             if (this.cblack.indexOf(tag) > -1) {
22638                 return;
22639             }
22640             this.cblack.push(tag);
22641             
22642         }, this);
22643     },
22644     
22645     setStylesheets : function(stylesheets)
22646     {
22647         if(typeof(stylesheets) == 'string'){
22648             Roo.get(this.iframe.contentDocument.head).createChild({
22649                 tag : 'link',
22650                 rel : 'stylesheet',
22651                 type : 'text/css',
22652                 href : stylesheets
22653             });
22654             
22655             return;
22656         }
22657         var _this = this;
22658      
22659         Roo.each(stylesheets, function(s) {
22660             if(!s.length){
22661                 return;
22662             }
22663             
22664             Roo.get(_this.iframe.contentDocument.head).createChild({
22665                 tag : 'link',
22666                 rel : 'stylesheet',
22667                 type : 'text/css',
22668                 href : s
22669             });
22670         });
22671
22672         
22673     },
22674     
22675     removeStylesheets : function()
22676     {
22677         var _this = this;
22678         
22679         Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
22680             s.remove();
22681         });
22682     }
22683     
22684     // hide stuff that is not compatible
22685     /**
22686      * @event blur
22687      * @hide
22688      */
22689     /**
22690      * @event change
22691      * @hide
22692      */
22693     /**
22694      * @event focus
22695      * @hide
22696      */
22697     /**
22698      * @event specialkey
22699      * @hide
22700      */
22701     /**
22702      * @cfg {String} fieldClass @hide
22703      */
22704     /**
22705      * @cfg {String} focusClass @hide
22706      */
22707     /**
22708      * @cfg {String} autoCreate @hide
22709      */
22710     /**
22711      * @cfg {String} inputType @hide
22712      */
22713     /**
22714      * @cfg {String} invalidClass @hide
22715      */
22716     /**
22717      * @cfg {String} invalidText @hide
22718      */
22719     /**
22720      * @cfg {String} msgFx @hide
22721      */
22722     /**
22723      * @cfg {String} validateOnBlur @hide
22724      */
22725 });
22726
22727 Roo.HtmlEditorCore.white = [
22728         'area', 'br', 'img', 'input', 'hr', 'wbr',
22729         
22730        'address', 'blockquote', 'center', 'dd',      'dir',       'div', 
22731        'dl',      'dt',         'h1',     'h2',      'h3',        'h4', 
22732        'h5',      'h6',         'hr',     'isindex', 'listing',   'marquee', 
22733        'menu',    'multicol',   'ol',     'p',       'plaintext', 'pre', 
22734        'table',   'ul',         'xmp', 
22735        
22736        'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th', 
22737       'thead',   'tr', 
22738      
22739       'dir', 'menu', 'ol', 'ul', 'dl',
22740        
22741       'embed',  'object'
22742 ];
22743
22744
22745 Roo.HtmlEditorCore.black = [
22746     //    'embed',  'object', // enable - backend responsiblity to clean thiese
22747         'applet', // 
22748         'base',   'basefont', 'bgsound', 'blink',  'body', 
22749         'frame',  'frameset', 'head',    'html',   'ilayer', 
22750         'iframe', 'layer',  'link',     'meta',    'object',   
22751         'script', 'style' ,'title',  'xml' // clean later..
22752 ];
22753 Roo.HtmlEditorCore.clean = [
22754     'script', 'style', 'title', 'xml'
22755 ];
22756 Roo.HtmlEditorCore.remove = [
22757     'font'
22758 ];
22759 // attributes..
22760
22761 Roo.HtmlEditorCore.ablack = [
22762     'on'
22763 ];
22764     
22765 Roo.HtmlEditorCore.aclean = [ 
22766     'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc' 
22767 ];
22768
22769 // protocols..
22770 Roo.HtmlEditorCore.pwhite= [
22771         'http',  'https',  'mailto'
22772 ];
22773
22774 // white listed style attributes.
22775 Roo.HtmlEditorCore.cwhite= [
22776       //  'text-align', /// default is to allow most things..
22777       
22778          
22779 //        'font-size'//??
22780 ];
22781
22782 // black listed style attributes.
22783 Roo.HtmlEditorCore.cblack= [
22784       //  'font-size' -- this can be set by the project 
22785 ];
22786
22787
22788 Roo.HtmlEditorCore.swapCodes   =[ 
22789     [    8211, "--" ], 
22790     [    8212, "--" ], 
22791     [    8216,  "'" ],  
22792     [    8217, "'" ],  
22793     [    8220, '"' ],  
22794     [    8221, '"' ],  
22795     [    8226, "*" ],  
22796     [    8230, "..." ]
22797 ]; 
22798
22799     /*
22800  * - LGPL
22801  *
22802  * HtmlEditor
22803  * 
22804  */
22805
22806 /**
22807  * @class Roo.bootstrap.HtmlEditor
22808  * @extends Roo.bootstrap.TextArea
22809  * Bootstrap HtmlEditor class
22810
22811  * @constructor
22812  * Create a new HtmlEditor
22813  * @param {Object} config The config object
22814  */
22815
22816 Roo.bootstrap.HtmlEditor = function(config){
22817     Roo.bootstrap.HtmlEditor.superclass.constructor.call(this, config);
22818     if (!this.toolbars) {
22819         this.toolbars = [];
22820     }
22821     
22822     this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
22823     this.addEvents({
22824             /**
22825              * @event initialize
22826              * Fires when the editor is fully initialized (including the iframe)
22827              * @param {HtmlEditor} this
22828              */
22829             initialize: true,
22830             /**
22831              * @event activate
22832              * Fires when the editor is first receives the focus. Any insertion must wait
22833              * until after this event.
22834              * @param {HtmlEditor} this
22835              */
22836             activate: true,
22837              /**
22838              * @event beforesync
22839              * Fires before the textarea is updated with content from the editor iframe. Return false
22840              * to cancel the sync.
22841              * @param {HtmlEditor} this
22842              * @param {String} html
22843              */
22844             beforesync: true,
22845              /**
22846              * @event beforepush
22847              * Fires before the iframe editor is updated with content from the textarea. Return false
22848              * to cancel the push.
22849              * @param {HtmlEditor} this
22850              * @param {String} html
22851              */
22852             beforepush: true,
22853              /**
22854              * @event sync
22855              * Fires when the textarea is updated with content from the editor iframe.
22856              * @param {HtmlEditor} this
22857              * @param {String} html
22858              */
22859             sync: true,
22860              /**
22861              * @event push
22862              * Fires when the iframe editor is updated with content from the textarea.
22863              * @param {HtmlEditor} this
22864              * @param {String} html
22865              */
22866             push: true,
22867              /**
22868              * @event editmodechange
22869              * Fires when the editor switches edit modes
22870              * @param {HtmlEditor} this
22871              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
22872              */
22873             editmodechange: true,
22874             /**
22875              * @event editorevent
22876              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
22877              * @param {HtmlEditor} this
22878              */
22879             editorevent: true,
22880             /**
22881              * @event firstfocus
22882              * Fires when on first focus - needed by toolbars..
22883              * @param {HtmlEditor} this
22884              */
22885             firstfocus: true,
22886             /**
22887              * @event autosave
22888              * Auto save the htmlEditor value as a file into Events
22889              * @param {HtmlEditor} this
22890              */
22891             autosave: true,
22892             /**
22893              * @event savedpreview
22894              * preview the saved version of htmlEditor
22895              * @param {HtmlEditor} this
22896              */
22897             savedpreview: true
22898         });
22899 };
22900
22901
22902 Roo.extend(Roo.bootstrap.HtmlEditor, Roo.bootstrap.TextArea,  {
22903     
22904     
22905       /**
22906      * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
22907      */
22908     toolbars : false,
22909     
22910      /**
22911     * @cfg {Array} buttons Array of toolbar's buttons. - defaults to empty
22912     */
22913     btns : [],
22914    
22915      /**
22916      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
22917      *                        Roo.resizable.
22918      */
22919     resizable : false,
22920      /**
22921      * @cfg {Number} height (in pixels)
22922      */   
22923     height: 300,
22924    /**
22925      * @cfg {Number} width (in pixels)
22926      */   
22927     width: false,
22928     
22929     /**
22930      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
22931      * 
22932      */
22933     stylesheets: false,
22934     
22935     // id of frame..
22936     frameId: false,
22937     
22938     // private properties
22939     validationEvent : false,
22940     deferHeight: true,
22941     initialized : false,
22942     activated : false,
22943     
22944     onFocus : Roo.emptyFn,
22945     iframePad:3,
22946     hideMode:'offsets',
22947     
22948     tbContainer : false,
22949     
22950     toolbarContainer :function() {
22951         return this.wrap.select('.x-html-editor-tb',true).first();
22952     },
22953
22954     /**
22955      * Protected method that will not generally be called directly. It
22956      * is called when the editor creates its toolbar. Override this method if you need to
22957      * add custom toolbar buttons.
22958      * @param {HtmlEditor} editor
22959      */
22960     createToolbar : function(){
22961         Roo.log('renewing');
22962         Roo.log("create toolbars");
22963         
22964         this.toolbars = [ new Roo.bootstrap.htmleditor.ToolbarStandard({editor: this} ) ];
22965         this.toolbars[0].render(this.toolbarContainer());
22966         
22967         return;
22968         
22969 //        if (!editor.toolbars || !editor.toolbars.length) {
22970 //            editor.toolbars = [ new Roo.bootstrap.HtmlEditor.ToolbarStandard() ]; // can be empty?
22971 //        }
22972 //        
22973 //        for (var i =0 ; i < editor.toolbars.length;i++) {
22974 //            editor.toolbars[i] = Roo.factory(
22975 //                    typeof(editor.toolbars[i]) == 'string' ?
22976 //                        { xtype: editor.toolbars[i]} : editor.toolbars[i],
22977 //                Roo.bootstrap.HtmlEditor);
22978 //            editor.toolbars[i].init(editor);
22979 //        }
22980     },
22981
22982      
22983     // private
22984     onRender : function(ct, position)
22985     {
22986        // Roo.log("Call onRender: " + this.xtype);
22987         var _t = this;
22988         Roo.bootstrap.HtmlEditor.superclass.onRender.call(this, ct, position);
22989       
22990         this.wrap = this.inputEl().wrap({
22991             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
22992         });
22993         
22994         this.editorcore.onRender(ct, position);
22995          
22996         if (this.resizable) {
22997             this.resizeEl = new Roo.Resizable(this.wrap, {
22998                 pinned : true,
22999                 wrap: true,
23000                 dynamic : true,
23001                 minHeight : this.height,
23002                 height: this.height,
23003                 handles : this.resizable,
23004                 width: this.width,
23005                 listeners : {
23006                     resize : function(r, w, h) {
23007                         _t.onResize(w,h); // -something
23008                     }
23009                 }
23010             });
23011             
23012         }
23013         this.createToolbar(this);
23014        
23015         
23016         if(!this.width && this.resizable){
23017             this.setSize(this.wrap.getSize());
23018         }
23019         if (this.resizeEl) {
23020             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
23021             // should trigger onReize..
23022         }
23023         
23024     },
23025
23026     // private
23027     onResize : function(w, h)
23028     {
23029         Roo.log('resize: ' +w + ',' + h );
23030         Roo.bootstrap.HtmlEditor.superclass.onResize.apply(this, arguments);
23031         var ew = false;
23032         var eh = false;
23033         
23034         if(this.inputEl() ){
23035             if(typeof w == 'number'){
23036                 var aw = w - this.wrap.getFrameWidth('lr');
23037                 this.inputEl().setWidth(this.adjustWidth('textarea', aw));
23038                 ew = aw;
23039             }
23040             if(typeof h == 'number'){
23041                  var tbh = -11;  // fixme it needs to tool bar size!
23042                 for (var i =0; i < this.toolbars.length;i++) {
23043                     // fixme - ask toolbars for heights?
23044                     tbh += this.toolbars[i].el.getHeight();
23045                     //if (this.toolbars[i].footer) {
23046                     //    tbh += this.toolbars[i].footer.el.getHeight();
23047                     //}
23048                 }
23049               
23050                 
23051                 
23052                 
23053                 
23054                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
23055                 ah -= 5; // knock a few pixes off for look..
23056                 this.inputEl().setHeight(this.adjustWidth('textarea', ah));
23057                 var eh = ah;
23058             }
23059         }
23060         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
23061         this.editorcore.onResize(ew,eh);
23062         
23063     },
23064
23065     /**
23066      * Toggles the editor between standard and source edit mode.
23067      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
23068      */
23069     toggleSourceEdit : function(sourceEditMode)
23070     {
23071         this.editorcore.toggleSourceEdit(sourceEditMode);
23072         
23073         if(this.editorcore.sourceEditMode){
23074             Roo.log('editor - showing textarea');
23075             
23076 //            Roo.log('in');
23077 //            Roo.log(this.syncValue());
23078             this.syncValue();
23079             this.inputEl().removeClass(['hide', 'x-hidden']);
23080             this.inputEl().dom.removeAttribute('tabIndex');
23081             this.inputEl().focus();
23082         }else{
23083             Roo.log('editor - hiding textarea');
23084 //            Roo.log('out')
23085 //            Roo.log(this.pushValue()); 
23086             this.pushValue();
23087             
23088             this.inputEl().addClass(['hide', 'x-hidden']);
23089             this.inputEl().dom.setAttribute('tabIndex', -1);
23090             //this.deferFocus();
23091         }
23092          
23093         if(this.resizable){
23094             this.setSize(this.wrap.getSize());
23095         }
23096         
23097         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
23098     },
23099  
23100     // private (for BoxComponent)
23101     adjustSize : Roo.BoxComponent.prototype.adjustSize,
23102
23103     // private (for BoxComponent)
23104     getResizeEl : function(){
23105         return this.wrap;
23106     },
23107
23108     // private (for BoxComponent)
23109     getPositionEl : function(){
23110         return this.wrap;
23111     },
23112
23113     // private
23114     initEvents : function(){
23115         this.originalValue = this.getValue();
23116     },
23117
23118 //    /**
23119 //     * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
23120 //     * @method
23121 //     */
23122 //    markInvalid : Roo.emptyFn,
23123 //    /**
23124 //     * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
23125 //     * @method
23126 //     */
23127 //    clearInvalid : Roo.emptyFn,
23128
23129     setValue : function(v){
23130         Roo.bootstrap.HtmlEditor.superclass.setValue.call(this, v);
23131         this.editorcore.pushValue();
23132     },
23133
23134      
23135     // private
23136     deferFocus : function(){
23137         this.focus.defer(10, this);
23138     },
23139
23140     // doc'ed in Field
23141     focus : function(){
23142         this.editorcore.focus();
23143         
23144     },
23145       
23146
23147     // private
23148     onDestroy : function(){
23149         
23150         
23151         
23152         if(this.rendered){
23153             
23154             for (var i =0; i < this.toolbars.length;i++) {
23155                 // fixme - ask toolbars for heights?
23156                 this.toolbars[i].onDestroy();
23157             }
23158             
23159             this.wrap.dom.innerHTML = '';
23160             this.wrap.remove();
23161         }
23162     },
23163
23164     // private
23165     onFirstFocus : function(){
23166         //Roo.log("onFirstFocus");
23167         this.editorcore.onFirstFocus();
23168          for (var i =0; i < this.toolbars.length;i++) {
23169             this.toolbars[i].onFirstFocus();
23170         }
23171         
23172     },
23173     
23174     // private
23175     syncValue : function()
23176     {   
23177         this.editorcore.syncValue();
23178     },
23179     
23180     pushValue : function()
23181     {   
23182         this.editorcore.pushValue();
23183     }
23184      
23185     
23186     // hide stuff that is not compatible
23187     /**
23188      * @event blur
23189      * @hide
23190      */
23191     /**
23192      * @event change
23193      * @hide
23194      */
23195     /**
23196      * @event focus
23197      * @hide
23198      */
23199     /**
23200      * @event specialkey
23201      * @hide
23202      */
23203     /**
23204      * @cfg {String} fieldClass @hide
23205      */
23206     /**
23207      * @cfg {String} focusClass @hide
23208      */
23209     /**
23210      * @cfg {String} autoCreate @hide
23211      */
23212     /**
23213      * @cfg {String} inputType @hide
23214      */
23215     /**
23216      * @cfg {String} invalidClass @hide
23217      */
23218     /**
23219      * @cfg {String} invalidText @hide
23220      */
23221     /**
23222      * @cfg {String} msgFx @hide
23223      */
23224     /**
23225      * @cfg {String} validateOnBlur @hide
23226      */
23227 });
23228  
23229     
23230    
23231    
23232    
23233       
23234 Roo.namespace('Roo.bootstrap.htmleditor');
23235 /**
23236  * @class Roo.bootstrap.HtmlEditorToolbar1
23237  * Basic Toolbar
23238  * 
23239  * Usage:
23240  *
23241  new Roo.bootstrap.HtmlEditor({
23242     ....
23243     toolbars : [
23244         new Roo.bootstrap.HtmlEditorToolbar1({
23245             disable : { fonts: 1 , format: 1, ..., ... , ...],
23246             btns : [ .... ]
23247         })
23248     }
23249      
23250  * 
23251  * @cfg {Object} disable List of elements to disable..
23252  * @cfg {Array} btns List of additional buttons.
23253  * 
23254  * 
23255  * NEEDS Extra CSS? 
23256  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
23257  */
23258  
23259 Roo.bootstrap.htmleditor.ToolbarStandard = function(config)
23260 {
23261     
23262     Roo.apply(this, config);
23263     
23264     // default disabled, based on 'good practice'..
23265     this.disable = this.disable || {};
23266     Roo.applyIf(this.disable, {
23267         fontSize : true,
23268         colors : true,
23269         specialElements : true
23270     });
23271     Roo.bootstrap.htmleditor.ToolbarStandard.superclass.constructor.call(this, config);
23272     
23273     this.editor = config.editor;
23274     this.editorcore = config.editor.editorcore;
23275     
23276     this.buttons   = new Roo.util.MixedCollection(false, function(o) { return o.cmd; });
23277     
23278     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
23279     // dont call parent... till later.
23280 }
23281 Roo.extend(Roo.bootstrap.htmleditor.ToolbarStandard, Roo.bootstrap.NavSimplebar,  {
23282      
23283     bar : true,
23284     
23285     editor : false,
23286     editorcore : false,
23287     
23288     
23289     formats : [
23290         "p" ,  
23291         "h1","h2","h3","h4","h5","h6", 
23292         "pre", "code", 
23293         "abbr", "acronym", "address", "cite", "samp", "var",
23294         'div','span'
23295     ],
23296     
23297     onRender : function(ct, position)
23298     {
23299        // Roo.log("Call onRender: " + this.xtype);
23300         
23301        Roo.bootstrap.htmleditor.ToolbarStandard.superclass.onRender.call(this, ct, position);
23302        Roo.log(this.el);
23303        this.el.dom.style.marginBottom = '0';
23304        var _this = this;
23305        var editorcore = this.editorcore;
23306        var editor= this.editor;
23307        
23308        var children = [];
23309        var btn = function(id,cmd , toggle, handler, html){
23310        
23311             var  event = toggle ? 'toggle' : 'click';
23312        
23313             var a = {
23314                 size : 'sm',
23315                 xtype: 'Button',
23316                 xns: Roo.bootstrap,
23317                 glyphicon : id,
23318                 cmd : id || cmd,
23319                 enableToggle:toggle !== false,
23320                 html : html || '',
23321                 pressed : toggle ? false : null,
23322                 listeners : {}
23323             };
23324             a.listeners[toggle ? 'toggle' : 'click'] = function() {
23325                 handler ? handler.call(_this,this) :_this.onBtnClick.call(_this, cmd ||  id);
23326             };
23327             children.push(a);
23328             return a;
23329        }
23330        
23331     //    var cb_box = function...
23332         
23333         var style = {
23334                 xtype: 'Button',
23335                 size : 'sm',
23336                 xns: Roo.bootstrap,
23337                 glyphicon : 'font',
23338                 //html : 'submit'
23339                 menu : {
23340                     xtype: 'Menu',
23341                     xns: Roo.bootstrap,
23342                     items:  []
23343                 }
23344         };
23345         Roo.each(this.formats, function(f) {
23346             style.menu.items.push({
23347                 xtype :'MenuItem',
23348                 xns: Roo.bootstrap,
23349                 html : '<'+ f+' style="margin:2px">'+f +'</'+ f+'>',
23350                 tagname : f,
23351                 listeners : {
23352                     click : function()
23353                     {
23354                         editorcore.insertTag(this.tagname);
23355                         editor.focus();
23356                     }
23357                 }
23358                 
23359             });
23360         });
23361         children.push(style);   
23362         
23363         btn('bold',false,true);
23364         btn('italic',false,true);
23365         btn('align-left', 'justifyleft',true);
23366         btn('align-center', 'justifycenter',true);
23367         btn('align-right' , 'justifyright',true);
23368         btn('link', false, false, function(btn) {
23369             //Roo.log("create link?");
23370             var url = prompt(this.createLinkText, this.defaultLinkValue);
23371             if(url && url != 'http:/'+'/'){
23372                 this.editorcore.relayCmd('createlink', url);
23373             }
23374         }),
23375         btn('list','insertunorderedlist',true);
23376         btn('pencil', false,true, function(btn){
23377                 Roo.log(this);
23378                 this.toggleSourceEdit(btn.pressed);
23379         });
23380         
23381         if (this.editor.btns.length > 0) {
23382             for (var i = 0; i<this.editor.btns.length; i++) {
23383                 children.push(this.editor.btns[i]);
23384             }
23385         }
23386         
23387         /*
23388         var cog = {
23389                 xtype: 'Button',
23390                 size : 'sm',
23391                 xns: Roo.bootstrap,
23392                 glyphicon : 'cog',
23393                 //html : 'submit'
23394                 menu : {
23395                     xtype: 'Menu',
23396                     xns: Roo.bootstrap,
23397                     items:  []
23398                 }
23399         };
23400         
23401         cog.menu.items.push({
23402             xtype :'MenuItem',
23403             xns: Roo.bootstrap,
23404             html : Clean styles,
23405             tagname : f,
23406             listeners : {
23407                 click : function()
23408                 {
23409                     editorcore.insertTag(this.tagname);
23410                     editor.focus();
23411                 }
23412             }
23413             
23414         });
23415        */
23416         
23417          
23418        this.xtype = 'NavSimplebar';
23419         
23420         for(var i=0;i< children.length;i++) {
23421             
23422             this.buttons.add(this.addxtypeChild(children[i]));
23423             
23424         }
23425         
23426         editor.on('editorevent', this.updateToolbar, this);
23427     },
23428     onBtnClick : function(id)
23429     {
23430        this.editorcore.relayCmd(id);
23431        this.editorcore.focus();
23432     },
23433     
23434     /**
23435      * Protected method that will not generally be called directly. It triggers
23436      * a toolbar update by reading the markup state of the current selection in the editor.
23437      */
23438     updateToolbar: function(){
23439
23440         if(!this.editorcore.activated){
23441             this.editor.onFirstFocus(); // is this neeed?
23442             return;
23443         }
23444
23445         var btns = this.buttons; 
23446         var doc = this.editorcore.doc;
23447         btns.get('bold').setActive(doc.queryCommandState('bold'));
23448         btns.get('italic').setActive(doc.queryCommandState('italic'));
23449         //btns.get('underline').setActive(doc.queryCommandState('underline'));
23450         
23451         btns.get('align-left').setActive(doc.queryCommandState('justifyleft'));
23452         btns.get('align-center').setActive(doc.queryCommandState('justifycenter'));
23453         btns.get('align-right').setActive(doc.queryCommandState('justifyright'));
23454         
23455         //btns[frameId + '-insertorderedlist').setActive(doc.queryCommandState('insertorderedlist'));
23456         btns.get('list').setActive(doc.queryCommandState('insertunorderedlist'));
23457          /*
23458         
23459         var ans = this.editorcore.getAllAncestors();
23460         if (this.formatCombo) {
23461             
23462             
23463             var store = this.formatCombo.store;
23464             this.formatCombo.setValue("");
23465             for (var i =0; i < ans.length;i++) {
23466                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
23467                     // select it..
23468                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
23469                     break;
23470                 }
23471             }
23472         }
23473         
23474         
23475         
23476         // hides menus... - so this cant be on a menu...
23477         Roo.bootstrap.MenuMgr.hideAll();
23478         */
23479         Roo.bootstrap.MenuMgr.hideAll();
23480         //this.editorsyncValue();
23481     },
23482     onFirstFocus: function() {
23483         this.buttons.each(function(item){
23484            item.enable();
23485         });
23486     },
23487     toggleSourceEdit : function(sourceEditMode){
23488         
23489           
23490         if(sourceEditMode){
23491             Roo.log("disabling buttons");
23492            this.buttons.each( function(item){
23493                 if(item.cmd != 'pencil'){
23494                     item.disable();
23495                 }
23496             });
23497           
23498         }else{
23499             Roo.log("enabling buttons");
23500             if(this.editorcore.initialized){
23501                 this.buttons.each( function(item){
23502                     item.enable();
23503                 });
23504             }
23505             
23506         }
23507         Roo.log("calling toggole on editor");
23508         // tell the editor that it's been pressed..
23509         this.editor.toggleSourceEdit(sourceEditMode);
23510        
23511     }
23512 });
23513
23514
23515
23516
23517
23518 /**
23519  * @class Roo.bootstrap.Table.AbstractSelectionModel
23520  * @extends Roo.util.Observable
23521  * Abstract base class for grid SelectionModels.  It provides the interface that should be
23522  * implemented by descendant classes.  This class should not be directly instantiated.
23523  * @constructor
23524  */
23525 Roo.bootstrap.Table.AbstractSelectionModel = function(){
23526     this.locked = false;
23527     Roo.bootstrap.Table.AbstractSelectionModel.superclass.constructor.call(this);
23528 };
23529
23530
23531 Roo.extend(Roo.bootstrap.Table.AbstractSelectionModel, Roo.util.Observable,  {
23532     /** @ignore Called by the grid automatically. Do not call directly. */
23533     init : function(grid){
23534         this.grid = grid;
23535         this.initEvents();
23536     },
23537
23538     /**
23539      * Locks the selections.
23540      */
23541     lock : function(){
23542         this.locked = true;
23543     },
23544
23545     /**
23546      * Unlocks the selections.
23547      */
23548     unlock : function(){
23549         this.locked = false;
23550     },
23551
23552     /**
23553      * Returns true if the selections are locked.
23554      * @return {Boolean}
23555      */
23556     isLocked : function(){
23557         return this.locked;
23558     }
23559 });
23560 /**
23561  * @extends Roo.bootstrap.Table.AbstractSelectionModel
23562  * @class Roo.bootstrap.Table.RowSelectionModel
23563  * The default SelectionModel used by {@link Roo.bootstrap.Table}.
23564  * It supports multiple selections and keyboard selection/navigation. 
23565  * @constructor
23566  * @param {Object} config
23567  */
23568
23569 Roo.bootstrap.Table.RowSelectionModel = function(config){
23570     Roo.apply(this, config);
23571     this.selections = new Roo.util.MixedCollection(false, function(o){
23572         return o.id;
23573     });
23574
23575     this.last = false;
23576     this.lastActive = false;
23577
23578     this.addEvents({
23579         /**
23580              * @event selectionchange
23581              * Fires when the selection changes
23582              * @param {SelectionModel} this
23583              */
23584             "selectionchange" : true,
23585         /**
23586              * @event afterselectionchange
23587              * Fires after the selection changes (eg. by key press or clicking)
23588              * @param {SelectionModel} this
23589              */
23590             "afterselectionchange" : true,
23591         /**
23592              * @event beforerowselect
23593              * Fires when a row is selected being selected, return false to cancel.
23594              * @param {SelectionModel} this
23595              * @param {Number} rowIndex The selected index
23596              * @param {Boolean} keepExisting False if other selections will be cleared
23597              */
23598             "beforerowselect" : true,
23599         /**
23600              * @event rowselect
23601              * Fires when a row is selected.
23602              * @param {SelectionModel} this
23603              * @param {Number} rowIndex The selected index
23604              * @param {Roo.data.Record} r The record
23605              */
23606             "rowselect" : true,
23607         /**
23608              * @event rowdeselect
23609              * Fires when a row is deselected.
23610              * @param {SelectionModel} this
23611              * @param {Number} rowIndex The selected index
23612              */
23613         "rowdeselect" : true
23614     });
23615     Roo.bootstrap.Table.RowSelectionModel.superclass.constructor.call(this);
23616     this.locked = false;
23617  };
23618
23619 Roo.extend(Roo.bootstrap.Table.RowSelectionModel, Roo.bootstrap.Table.AbstractSelectionModel,  {
23620     /**
23621      * @cfg {Boolean} singleSelect
23622      * True to allow selection of only one row at a time (defaults to false)
23623      */
23624     singleSelect : false,
23625
23626     // private
23627     initEvents : function()
23628     {
23629
23630         //if(!this.grid.enableDragDrop && !this.grid.enableDrag){
23631         //    this.growclickrid.on("mousedown", this.handleMouseDown, this);
23632         //}else{ // allow click to work like normal
23633          //   this.grid.on("rowclick", this.handleDragableRowClick, this);
23634         //}
23635         //this.grid.on("rowdblclick", this.handleMouseDBClick, this);
23636         this.grid.on("rowclick", this.handleMouseDown, this);
23637         
23638         this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
23639             "up" : function(e){
23640                 if(!e.shiftKey){
23641                     this.selectPrevious(e.shiftKey);
23642                 }else if(this.last !== false && this.lastActive !== false){
23643                     var last = this.last;
23644                     this.selectRange(this.last,  this.lastActive-1);
23645                     this.grid.getView().focusRow(this.lastActive);
23646                     if(last !== false){
23647                         this.last = last;
23648                     }
23649                 }else{
23650                     this.selectFirstRow();
23651                 }
23652                 this.fireEvent("afterselectionchange", this);
23653             },
23654             "down" : function(e){
23655                 if(!e.shiftKey){
23656                     this.selectNext(e.shiftKey);
23657                 }else if(this.last !== false && this.lastActive !== false){
23658                     var last = this.last;
23659                     this.selectRange(this.last,  this.lastActive+1);
23660                     this.grid.getView().focusRow(this.lastActive);
23661                     if(last !== false){
23662                         this.last = last;
23663                     }
23664                 }else{
23665                     this.selectFirstRow();
23666                 }
23667                 this.fireEvent("afterselectionchange", this);
23668             },
23669             scope: this
23670         });
23671         this.grid.store.on('load', function(){
23672             this.selections.clear();
23673         },this);
23674         /*
23675         var view = this.grid.view;
23676         view.on("refresh", this.onRefresh, this);
23677         view.on("rowupdated", this.onRowUpdated, this);
23678         view.on("rowremoved", this.onRemove, this);
23679         */
23680     },
23681
23682     // private
23683     onRefresh : function()
23684     {
23685         var ds = this.grid.store, i, v = this.grid.view;
23686         var s = this.selections;
23687         s.each(function(r){
23688             if((i = ds.indexOfId(r.id)) != -1){
23689                 v.onRowSelect(i);
23690             }else{
23691                 s.remove(r);
23692             }
23693         });
23694     },
23695
23696     // private
23697     onRemove : function(v, index, r){
23698         this.selections.remove(r);
23699     },
23700
23701     // private
23702     onRowUpdated : function(v, index, r){
23703         if(this.isSelected(r)){
23704             v.onRowSelect(index);
23705         }
23706     },
23707
23708     /**
23709      * Select records.
23710      * @param {Array} records The records to select
23711      * @param {Boolean} keepExisting (optional) True to keep existing selections
23712      */
23713     selectRecords : function(records, keepExisting)
23714     {
23715         if(!keepExisting){
23716             this.clearSelections();
23717         }
23718             var ds = this.grid.store;
23719         for(var i = 0, len = records.length; i < len; i++){
23720             this.selectRow(ds.indexOf(records[i]), true);
23721         }
23722     },
23723
23724     /**
23725      * Gets the number of selected rows.
23726      * @return {Number}
23727      */
23728     getCount : function(){
23729         return this.selections.length;
23730     },
23731
23732     /**
23733      * Selects the first row in the grid.
23734      */
23735     selectFirstRow : function(){
23736         this.selectRow(0);
23737     },
23738
23739     /**
23740      * Select the last row.
23741      * @param {Boolean} keepExisting (optional) True to keep existing selections
23742      */
23743     selectLastRow : function(keepExisting){
23744         //this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting);
23745         this.selectRow(this.grid.store.getCount() - 1, keepExisting);
23746     },
23747
23748     /**
23749      * Selects the row immediately following the last selected row.
23750      * @param {Boolean} keepExisting (optional) True to keep existing selections
23751      */
23752     selectNext : function(keepExisting)
23753     {
23754             if(this.last !== false && (this.last+1) < this.grid.store.getCount()){
23755             this.selectRow(this.last+1, keepExisting);
23756             this.grid.getView().focusRow(this.last);
23757         }
23758     },
23759
23760     /**
23761      * Selects the row that precedes the last selected row.
23762      * @param {Boolean} keepExisting (optional) True to keep existing selections
23763      */
23764     selectPrevious : function(keepExisting){
23765         if(this.last){
23766             this.selectRow(this.last-1, keepExisting);
23767             this.grid.getView().focusRow(this.last);
23768         }
23769     },
23770
23771     /**
23772      * Returns the selected records
23773      * @return {Array} Array of selected records
23774      */
23775     getSelections : function(){
23776         return [].concat(this.selections.items);
23777     },
23778
23779     /**
23780      * Returns the first selected record.
23781      * @return {Record}
23782      */
23783     getSelected : function(){
23784         return this.selections.itemAt(0);
23785     },
23786
23787
23788     /**
23789      * Clears all selections.
23790      */
23791     clearSelections : function(fast)
23792     {
23793         if(this.locked) {
23794             return;
23795         }
23796         if(fast !== true){
23797                 var ds = this.grid.store;
23798             var s = this.selections;
23799             s.each(function(r){
23800                 this.deselectRow(ds.indexOfId(r.id));
23801             }, this);
23802             s.clear();
23803         }else{
23804             this.selections.clear();
23805         }
23806         this.last = false;
23807     },
23808
23809
23810     /**
23811      * Selects all rows.
23812      */
23813     selectAll : function(){
23814         if(this.locked) {
23815             return;
23816         }
23817         this.selections.clear();
23818         for(var i = 0, len = this.grid.store.getCount(); i < len; i++){
23819             this.selectRow(i, true);
23820         }
23821     },
23822
23823     /**
23824      * Returns True if there is a selection.
23825      * @return {Boolean}
23826      */
23827     hasSelection : function(){
23828         return this.selections.length > 0;
23829     },
23830
23831     /**
23832      * Returns True if the specified row is selected.
23833      * @param {Number/Record} record The record or index of the record to check
23834      * @return {Boolean}
23835      */
23836     isSelected : function(index){
23837             var r = typeof index == "number" ? this.grid.store.getAt(index) : index;
23838         return (r && this.selections.key(r.id) ? true : false);
23839     },
23840
23841     /**
23842      * Returns True if the specified record id is selected.
23843      * @param {String} id The id of record to check
23844      * @return {Boolean}
23845      */
23846     isIdSelected : function(id){
23847         return (this.selections.key(id) ? true : false);
23848     },
23849
23850
23851     // private
23852     handleMouseDBClick : function(e, t){
23853         
23854     },
23855     // private
23856     handleMouseDown : function(e, t)
23857     {
23858             var rowIndex = this.grid.headerShow  ? t.dom.rowIndex - 1 : t.dom.rowIndex ; // first row is header???
23859         if(this.isLocked() || rowIndex < 0 ){
23860             return;
23861         };
23862         if(e.shiftKey && this.last !== false){
23863             var last = this.last;
23864             this.selectRange(last, rowIndex, e.ctrlKey);
23865             this.last = last; // reset the last
23866             t.focus();
23867     
23868         }else{
23869             var isSelected = this.isSelected(rowIndex);
23870             //Roo.log("select row:" + rowIndex);
23871             if(isSelected){
23872                 this.deselectRow(rowIndex);
23873             } else {
23874                         this.selectRow(rowIndex, true);
23875             }
23876     
23877             /*
23878                 if(e.button !== 0 && isSelected){
23879                 alert('rowIndex 2: ' + rowIndex);
23880                     view.focusRow(rowIndex);
23881                 }else if(e.ctrlKey && isSelected){
23882                     this.deselectRow(rowIndex);
23883                 }else if(!isSelected){
23884                     this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
23885                     view.focusRow(rowIndex);
23886                 }
23887             */
23888         }
23889         this.fireEvent("afterselectionchange", this);
23890     },
23891     // private
23892     handleDragableRowClick :  function(grid, rowIndex, e) 
23893     {
23894         if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
23895             this.selectRow(rowIndex, false);
23896             grid.view.focusRow(rowIndex);
23897              this.fireEvent("afterselectionchange", this);
23898         }
23899     },
23900     
23901     /**
23902      * Selects multiple rows.
23903      * @param {Array} rows Array of the indexes of the row to select
23904      * @param {Boolean} keepExisting (optional) True to keep existing selections
23905      */
23906     selectRows : function(rows, keepExisting){
23907         if(!keepExisting){
23908             this.clearSelections();
23909         }
23910         for(var i = 0, len = rows.length; i < len; i++){
23911             this.selectRow(rows[i], true);
23912         }
23913     },
23914
23915     /**
23916      * Selects a range of rows. All rows in between startRow and endRow are also selected.
23917      * @param {Number} startRow The index of the first row in the range
23918      * @param {Number} endRow The index of the last row in the range
23919      * @param {Boolean} keepExisting (optional) True to retain existing selections
23920      */
23921     selectRange : function(startRow, endRow, keepExisting){
23922         if(this.locked) {
23923             return;
23924         }
23925         if(!keepExisting){
23926             this.clearSelections();
23927         }
23928         if(startRow <= endRow){
23929             for(var i = startRow; i <= endRow; i++){
23930                 this.selectRow(i, true);
23931             }
23932         }else{
23933             for(var i = startRow; i >= endRow; i--){
23934                 this.selectRow(i, true);
23935             }
23936         }
23937     },
23938
23939     /**
23940      * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
23941      * @param {Number} startRow The index of the first row in the range
23942      * @param {Number} endRow The index of the last row in the range
23943      */
23944     deselectRange : function(startRow, endRow, preventViewNotify){
23945         if(this.locked) {
23946             return;
23947         }
23948         for(var i = startRow; i <= endRow; i++){
23949             this.deselectRow(i, preventViewNotify);
23950         }
23951     },
23952
23953     /**
23954      * Selects a row.
23955      * @param {Number} row The index of the row to select
23956      * @param {Boolean} keepExisting (optional) True to keep existing selections
23957      */
23958     selectRow : function(index, keepExisting, preventViewNotify)
23959     {
23960             if(this.locked || (index < 0 || index > this.grid.store.getCount())) {
23961             return;
23962         }
23963         if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
23964             if(!keepExisting || this.singleSelect){
23965                 this.clearSelections();
23966             }
23967             
23968             var r = this.grid.store.getAt(index);
23969             //console.log('selectRow - record id :' + r.id);
23970             
23971             this.selections.add(r);
23972             this.last = this.lastActive = index;
23973             if(!preventViewNotify){
23974                 var proxy = new Roo.Element(
23975                                 this.grid.getRowDom(index)
23976                 );
23977                 proxy.addClass('bg-info info');
23978             }
23979             this.fireEvent("rowselect", this, index, r);
23980             this.fireEvent("selectionchange", this);
23981         }
23982     },
23983
23984     /**
23985      * Deselects a row.
23986      * @param {Number} row The index of the row to deselect
23987      */
23988     deselectRow : function(index, preventViewNotify)
23989     {
23990         if(this.locked) {
23991             return;
23992         }
23993         if(this.last == index){
23994             this.last = false;
23995         }
23996         if(this.lastActive == index){
23997             this.lastActive = false;
23998         }
23999         
24000         var r = this.grid.store.getAt(index);
24001         if (!r) {
24002             return;
24003         }
24004         
24005         this.selections.remove(r);
24006         //.console.log('deselectRow - record id :' + r.id);
24007         if(!preventViewNotify){
24008         
24009             var proxy = new Roo.Element(
24010                 this.grid.getRowDom(index)
24011             );
24012             proxy.removeClass('bg-info info');
24013         }
24014         this.fireEvent("rowdeselect", this, index);
24015         this.fireEvent("selectionchange", this);
24016     },
24017
24018     // private
24019     restoreLast : function(){
24020         if(this._last){
24021             this.last = this._last;
24022         }
24023     },
24024
24025     // private
24026     acceptsNav : function(row, col, cm){
24027         return !cm.isHidden(col) && cm.isCellEditable(col, row);
24028     },
24029
24030     // private
24031     onEditorKey : function(field, e){
24032         var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
24033         if(k == e.TAB){
24034             e.stopEvent();
24035             ed.completeEdit();
24036             if(e.shiftKey){
24037                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
24038             }else{
24039                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
24040             }
24041         }else if(k == e.ENTER && !e.ctrlKey){
24042             e.stopEvent();
24043             ed.completeEdit();
24044             if(e.shiftKey){
24045                 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
24046             }else{
24047                 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
24048             }
24049         }else if(k == e.ESC){
24050             ed.cancelEdit();
24051         }
24052         if(newCell){
24053             g.startEditing(newCell[0], newCell[1]);
24054         }
24055     }
24056 });
24057 /*
24058  * Based on:
24059  * Ext JS Library 1.1.1
24060  * Copyright(c) 2006-2007, Ext JS, LLC.
24061  *
24062  * Originally Released Under LGPL - original licence link has changed is not relivant.
24063  *
24064  * Fork - LGPL
24065  * <script type="text/javascript">
24066  */
24067  
24068 /**
24069  * @class Roo.bootstrap.PagingToolbar
24070  * @extends Roo.bootstrap.NavSimplebar
24071  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
24072  * @constructor
24073  * Create a new PagingToolbar
24074  * @param {Object} config The config object
24075  * @param {Roo.data.Store} store
24076  */
24077 Roo.bootstrap.PagingToolbar = function(config)
24078 {
24079     // old args format still supported... - xtype is prefered..
24080         // created from xtype...
24081     
24082     this.ds = config.dataSource;
24083     
24084     if (config.store && !this.ds) {
24085         this.store= Roo.factory(config.store, Roo.data);
24086         this.ds = this.store;
24087         this.ds.xmodule = this.xmodule || false;
24088     }
24089     
24090     this.toolbarItems = [];
24091     if (config.items) {
24092         this.toolbarItems = config.items;
24093     }
24094     
24095     Roo.bootstrap.PagingToolbar.superclass.constructor.call(this, config);
24096     
24097     this.cursor = 0;
24098     
24099     if (this.ds) { 
24100         this.bind(this.ds);
24101     }
24102     
24103     this.navgroup = new Roo.bootstrap.NavGroup({ cls: 'pagination' });
24104     
24105 };
24106
24107 Roo.extend(Roo.bootstrap.PagingToolbar, Roo.bootstrap.NavSimplebar, {
24108     /**
24109      * @cfg {Roo.data.Store} dataSource
24110      * The underlying data store providing the paged data
24111      */
24112     /**
24113      * @cfg {String/HTMLElement/Element} container
24114      * container The id or element that will contain the toolbar
24115      */
24116     /**
24117      * @cfg {Boolean} displayInfo
24118      * True to display the displayMsg (defaults to false)
24119      */
24120     /**
24121      * @cfg {Number} pageSize
24122      * The number of records to display per page (defaults to 20)
24123      */
24124     pageSize: 20,
24125     /**
24126      * @cfg {String} displayMsg
24127      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
24128      */
24129     displayMsg : 'Displaying {0} - {1} of {2}',
24130     /**
24131      * @cfg {String} emptyMsg
24132      * The message to display when no records are found (defaults to "No data to display")
24133      */
24134     emptyMsg : 'No data to display',
24135     /**
24136      * Customizable piece of the default paging text (defaults to "Page")
24137      * @type String
24138      */
24139     beforePageText : "Page",
24140     /**
24141      * Customizable piece of the default paging text (defaults to "of %0")
24142      * @type String
24143      */
24144     afterPageText : "of {0}",
24145     /**
24146      * Customizable piece of the default paging text (defaults to "First Page")
24147      * @type String
24148      */
24149     firstText : "First Page",
24150     /**
24151      * Customizable piece of the default paging text (defaults to "Previous Page")
24152      * @type String
24153      */
24154     prevText : "Previous Page",
24155     /**
24156      * Customizable piece of the default paging text (defaults to "Next Page")
24157      * @type String
24158      */
24159     nextText : "Next Page",
24160     /**
24161      * Customizable piece of the default paging text (defaults to "Last Page")
24162      * @type String
24163      */
24164     lastText : "Last Page",
24165     /**
24166      * Customizable piece of the default paging text (defaults to "Refresh")
24167      * @type String
24168      */
24169     refreshText : "Refresh",
24170
24171     buttons : false,
24172     // private
24173     onRender : function(ct, position) 
24174     {
24175         Roo.bootstrap.PagingToolbar.superclass.onRender.call(this, ct, position);
24176         this.navgroup.parentId = this.id;
24177         this.navgroup.onRender(this.el, null);
24178         // add the buttons to the navgroup
24179         
24180         if(this.displayInfo){
24181             this.el.select('ul.navbar-nav',true).first().createChild({cls:'x-paging-info'});
24182             this.displayEl = this.el.select('.x-paging-info', true).first();
24183 //            var navel = this.navgroup.addItem( { tagtype : 'span', html : '', cls : 'x-paging-info', preventDefault : true } );
24184 //            this.displayEl = navel.el.select('span',true).first();
24185         }
24186         
24187         var _this = this;
24188         
24189         if(this.buttons){
24190             Roo.each(_this.buttons, function(e){ // this might need to use render????
24191                Roo.factory(e).onRender(_this.el, null);
24192             });
24193         }
24194             
24195         Roo.each(_this.toolbarItems, function(e) {
24196             _this.navgroup.addItem(e);
24197         });
24198         
24199         
24200         this.first = this.navgroup.addItem({
24201             tooltip: this.firstText,
24202             cls: "prev",
24203             icon : 'fa fa-backward',
24204             disabled: true,
24205             preventDefault: true,
24206             listeners : { click : this.onClick.createDelegate(this, ["first"]) }
24207         });
24208         
24209         this.prev =  this.navgroup.addItem({
24210             tooltip: this.prevText,
24211             cls: "prev",
24212             icon : 'fa fa-step-backward',
24213             disabled: true,
24214             preventDefault: true,
24215             listeners : { click :  this.onClick.createDelegate(this, ["prev"]) }
24216         });
24217     //this.addSeparator();
24218         
24219         
24220         var field = this.navgroup.addItem( {
24221             tagtype : 'span',
24222             cls : 'x-paging-position',
24223             
24224             html : this.beforePageText  +
24225                 '<input type="text" size="3" value="1" class="x-grid-page-number">' +
24226                 '<span class="x-paging-after">' +  String.format(this.afterPageText, 1) + '</span>'
24227          } ); //?? escaped?
24228         
24229         this.field = field.el.select('input', true).first();
24230         this.field.on("keydown", this.onPagingKeydown, this);
24231         this.field.on("focus", function(){this.dom.select();});
24232     
24233     
24234         this.afterTextEl =  field.el.select('.x-paging-after',true).first();
24235         //this.field.setHeight(18);
24236         //this.addSeparator();
24237         this.next = this.navgroup.addItem({
24238             tooltip: this.nextText,
24239             cls: "next",
24240             html : ' <i class="fa fa-step-forward">',
24241             disabled: true,
24242             preventDefault: true,
24243             listeners : { click :  this.onClick.createDelegate(this, ["next"]) }
24244         });
24245         this.last = this.navgroup.addItem({
24246             tooltip: this.lastText,
24247             icon : 'fa fa-forward',
24248             cls: "next",
24249             disabled: true,
24250             preventDefault: true,
24251             listeners : { click :  this.onClick.createDelegate(this, ["last"]) }
24252         });
24253     //this.addSeparator();
24254         this.loading = this.navgroup.addItem({
24255             tooltip: this.refreshText,
24256             icon: 'fa fa-refresh',
24257             preventDefault: true,
24258             listeners : { click : this.onClick.createDelegate(this, ["refresh"]) }
24259         });
24260         
24261     },
24262
24263     // private
24264     updateInfo : function(){
24265         if(this.displayEl){
24266             var count = (typeof(this.getCount) == 'undefined') ? this.ds.getCount() : this.getCount();
24267             var msg = count == 0 ?
24268                 this.emptyMsg :
24269                 String.format(
24270                     this.displayMsg,
24271                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
24272                 );
24273             this.displayEl.update(msg);
24274         }
24275     },
24276
24277     // private
24278     onLoad : function(ds, r, o)
24279     {
24280         this.cursor = o.params ? o.params.start : 0;
24281         var d = this.getPageData(),
24282             ap = d.activePage,
24283             ps = d.pages;
24284         
24285         
24286         this.afterTextEl.dom.innerHTML = String.format(this.afterPageText, d.pages);
24287         this.field.dom.value = ap;
24288         this.first.setDisabled(ap == 1);
24289         this.prev.setDisabled(ap == 1);
24290         this.next.setDisabled(ap == ps);
24291         this.last.setDisabled(ap == ps);
24292         this.loading.enable();
24293         this.updateInfo();
24294     },
24295
24296     // private
24297     getPageData : function(){
24298         var total = this.ds.getTotalCount();
24299         return {
24300             total : total,
24301             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
24302             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
24303         };
24304     },
24305
24306     // private
24307     onLoadError : function(){
24308         this.loading.enable();
24309     },
24310
24311     // private
24312     onPagingKeydown : function(e){
24313         var k = e.getKey();
24314         var d = this.getPageData();
24315         if(k == e.RETURN){
24316             var v = this.field.dom.value, pageNum;
24317             if(!v || isNaN(pageNum = parseInt(v, 10))){
24318                 this.field.dom.value = d.activePage;
24319                 return;
24320             }
24321             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
24322             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
24323             e.stopEvent();
24324         }
24325         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))
24326         {
24327           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
24328           this.field.dom.value = pageNum;
24329           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
24330           e.stopEvent();
24331         }
24332         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
24333         {
24334           var v = this.field.dom.value, pageNum; 
24335           var increment = (e.shiftKey) ? 10 : 1;
24336           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
24337                 increment *= -1;
24338           }
24339           if(!v || isNaN(pageNum = parseInt(v, 10))) {
24340             this.field.dom.value = d.activePage;
24341             return;
24342           }
24343           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
24344           {
24345             this.field.dom.value = parseInt(v, 10) + increment;
24346             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
24347             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
24348           }
24349           e.stopEvent();
24350         }
24351     },
24352
24353     // private
24354     beforeLoad : function(){
24355         if(this.loading){
24356             this.loading.disable();
24357         }
24358     },
24359
24360     // private
24361     onClick : function(which){
24362         
24363         var ds = this.ds;
24364         if (!ds) {
24365             return;
24366         }
24367         
24368         switch(which){
24369             case "first":
24370                 ds.load({params:{start: 0, limit: this.pageSize}});
24371             break;
24372             case "prev":
24373                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
24374             break;
24375             case "next":
24376                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
24377             break;
24378             case "last":
24379                 var total = ds.getTotalCount();
24380                 var extra = total % this.pageSize;
24381                 var lastStart = extra ? (total - extra) : total-this.pageSize;
24382                 ds.load({params:{start: lastStart, limit: this.pageSize}});
24383             break;
24384             case "refresh":
24385                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
24386             break;
24387         }
24388     },
24389
24390     /**
24391      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
24392      * @param {Roo.data.Store} store The data store to unbind
24393      */
24394     unbind : function(ds){
24395         ds.un("beforeload", this.beforeLoad, this);
24396         ds.un("load", this.onLoad, this);
24397         ds.un("loadexception", this.onLoadError, this);
24398         ds.un("remove", this.updateInfo, this);
24399         ds.un("add", this.updateInfo, this);
24400         this.ds = undefined;
24401     },
24402
24403     /**
24404      * Binds the paging toolbar to the specified {@link Roo.data.Store}
24405      * @param {Roo.data.Store} store The data store to bind
24406      */
24407     bind : function(ds){
24408         ds.on("beforeload", this.beforeLoad, this);
24409         ds.on("load", this.onLoad, this);
24410         ds.on("loadexception", this.onLoadError, this);
24411         ds.on("remove", this.updateInfo, this);
24412         ds.on("add", this.updateInfo, this);
24413         this.ds = ds;
24414     }
24415 });/*
24416  * - LGPL
24417  *
24418  * element
24419  * 
24420  */
24421
24422 /**
24423  * @class Roo.bootstrap.MessageBar
24424  * @extends Roo.bootstrap.Component
24425  * Bootstrap MessageBar class
24426  * @cfg {String} html contents of the MessageBar
24427  * @cfg {String} weight (info | success | warning | danger) default info
24428  * @cfg {String} beforeClass insert the bar before the given class
24429  * @cfg {Boolean} closable (true | false) default false
24430  * @cfg {Boolean} fixed (true | false) default false, fix the bar at the top
24431  * 
24432  * @constructor
24433  * Create a new Element
24434  * @param {Object} config The config object
24435  */
24436
24437 Roo.bootstrap.MessageBar = function(config){
24438     Roo.bootstrap.MessageBar.superclass.constructor.call(this, config);
24439 };
24440
24441 Roo.extend(Roo.bootstrap.MessageBar, Roo.bootstrap.Component,  {
24442     
24443     html: '',
24444     weight: 'info',
24445     closable: false,
24446     fixed: false,
24447     beforeClass: 'bootstrap-sticky-wrap',
24448     
24449     getAutoCreate : function(){
24450         
24451         var cfg = {
24452             tag: 'div',
24453             cls: 'alert alert-dismissable alert-' + this.weight,
24454             cn: [
24455                 {
24456                     tag: 'span',
24457                     cls: 'message',
24458                     html: this.html || ''
24459                 }
24460             ]
24461         };
24462         
24463         if(this.fixed){
24464             cfg.cls += ' alert-messages-fixed';
24465         }
24466         
24467         if(this.closable){
24468             cfg.cn.push({
24469                 tag: 'button',
24470                 cls: 'close',
24471                 html: 'x'
24472             });
24473         }
24474         
24475         return cfg;
24476     },
24477     
24478     onRender : function(ct, position)
24479     {
24480         Roo.bootstrap.Component.superclass.onRender.call(this, ct, position);
24481         
24482         if(!this.el){
24483             var cfg = Roo.apply({},  this.getAutoCreate());
24484             cfg.id = Roo.id();
24485             
24486             if (this.cls) {
24487                 cfg.cls += ' ' + this.cls;
24488             }
24489             if (this.style) {
24490                 cfg.style = this.style;
24491             }
24492             this.el = Roo.get(document.body).createChild(cfg, Roo.select('.'+this.beforeClass, true).first());
24493             
24494             this.el.setVisibilityMode(Roo.Element.DISPLAY);
24495         }
24496         
24497         this.el.select('>button.close').on('click', this.hide, this);
24498         
24499     },
24500     
24501     show : function()
24502     {
24503         if (!this.rendered) {
24504             this.render();
24505         }
24506         
24507         this.el.show();
24508         
24509         this.fireEvent('show', this);
24510         
24511     },
24512     
24513     hide : function()
24514     {
24515         if (!this.rendered) {
24516             this.render();
24517         }
24518         
24519         this.el.hide();
24520         
24521         this.fireEvent('hide', this);
24522     },
24523     
24524     update : function()
24525     {
24526 //        var e = this.el.dom.firstChild;
24527 //        
24528 //        if(this.closable){
24529 //            e = e.nextSibling;
24530 //        }
24531 //        
24532 //        e.data = this.html || '';
24533
24534         this.el.select('>.message', true).first().dom.innerHTML = this.html || '';
24535     }
24536    
24537 });
24538
24539  
24540
24541      /*
24542  * - LGPL
24543  *
24544  * Graph
24545  * 
24546  */
24547
24548
24549 /**
24550  * @class Roo.bootstrap.Graph
24551  * @extends Roo.bootstrap.Component
24552  * Bootstrap Graph class
24553 > Prameters
24554  -sm {number} sm 4
24555  -md {number} md 5
24556  @cfg {String} graphtype  bar | vbar | pie
24557  @cfg {number} g_x coodinator | centre x (pie)
24558  @cfg {number} g_y coodinator | centre y (pie)
24559  @cfg {number} g_r radius (pie)
24560  @cfg {number} g_height height of the chart (respected by all elements in the set)
24561  @cfg {number} g_width width of the chart (respected by all elements in the set)
24562  @cfg {Object} title The title of the chart
24563     
24564  -{Array}  values
24565  -opts (object) options for the chart 
24566      o {
24567      o type (string) type of endings of the bar. Default: 'square'. Other options are: 'round', 'sharp', 'soft'.
24568      o gutter (number)(string) default '20%' (WHAT DOES IT DO?)
24569      o vgutter (number)
24570      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.
24571      o stacked (boolean) whether or not to tread values as in a stacked bar chart
24572      o to
24573      o stretch (boolean)
24574      o }
24575  -opts (object) options for the pie
24576      o{
24577      o cut
24578      o startAngle (number)
24579      o endAngle (number)
24580      } 
24581  *
24582  * @constructor
24583  * Create a new Input
24584  * @param {Object} config The config object
24585  */
24586
24587 Roo.bootstrap.Graph = function(config){
24588     Roo.bootstrap.Graph.superclass.constructor.call(this, config);
24589     
24590     this.addEvents({
24591         // img events
24592         /**
24593          * @event click
24594          * The img click event for the img.
24595          * @param {Roo.EventObject} e
24596          */
24597         "click" : true
24598     });
24599 };
24600
24601 Roo.extend(Roo.bootstrap.Graph, Roo.bootstrap.Component,  {
24602     
24603     sm: 4,
24604     md: 5,
24605     graphtype: 'bar',
24606     g_height: 250,
24607     g_width: 400,
24608     g_x: 50,
24609     g_y: 50,
24610     g_r: 30,
24611     opts:{
24612         //g_colors: this.colors,
24613         g_type: 'soft',
24614         g_gutter: '20%'
24615
24616     },
24617     title : false,
24618
24619     getAutoCreate : function(){
24620         
24621         var cfg = {
24622             tag: 'div',
24623             html : null
24624         };
24625         
24626         
24627         return  cfg;
24628     },
24629
24630     onRender : function(ct,position){
24631         
24632         
24633         Roo.bootstrap.Graph.superclass.onRender.call(this,ct,position);
24634         
24635         if (typeof(Raphael) == 'undefined') {
24636             Roo.bootstrap.MessageBox.alert("Error","Raphael is not availabe");
24637             return;
24638         }
24639         
24640         this.raphael = Raphael(this.el.dom);
24641         
24642                     // data1 = [[55, 20, 13, 32, 5, 1, 2, 10], [10, 2, 1, 5, 32, 13, 20, 55], [12, 20, 30]],
24643                     // data2 = [[55, 20, 13, 32, 5, 1, 2, 10], [10, 2, 1, 5, 32, 13, 20, 55], [12, 20, 30]],
24644                     // data3 = [[55, 20, 13, 32, 5, 1, 2, 10], [10, 2, 1, 5, 32, 13, 20, 55], [12, 20, 30]],
24645                     // txtattr = { font: "12px 'Fontin Sans', Fontin-Sans, sans-serif" };
24646                 /*
24647                 r.text(160, 10, "Single Series Chart").attr(txtattr);
24648                 r.text(480, 10, "Multiline Series Chart").attr(txtattr);
24649                 r.text(160, 250, "Multiple Series Stacked Chart").attr(txtattr);
24650                 r.text(480, 250, 'Multiline Series Stacked Vertical Chart. Type "round"').attr(txtattr);
24651                 
24652                 r.barchart(10, 10, 300, 220, [[55, 20, 13, 32, 5, 1, 2, 10]], 0, {type: "sharp"});
24653                 r.barchart(330, 10, 300, 220, data1);
24654                 r.barchart(10, 250, 300, 220, data2, {stacked: true});
24655                 r.barchart(330, 250, 300, 220, data3, {stacked: true, type: "round"});
24656                 */
24657                 
24658                 // var xdata = [55, 20, 13, 32, 5, 1, 2, 10,5 , 10];
24659                 // r.barchart(30, 30, 560, 250,  xdata, {
24660                 //    labels : [55, 20, 13, 32, 5, 1, 2, 10,5 , 10],
24661                 //     axis : "0 0 1 1",
24662                 //     axisxlabels :  xdata
24663                 //     //yvalues : cols,
24664                    
24665                 // });
24666 //        var xdata = [55, 20, 13, 32, 5, 1, 2, 10,5 , 10];
24667 //        
24668 //        this.load(null,xdata,{
24669 //                axis : "0 0 1 1",
24670 //                axisxlabels :  xdata
24671 //                });
24672
24673     },
24674
24675     load : function(graphtype,xdata,opts)
24676     {
24677         this.raphael.clear();
24678         if(!graphtype) {
24679             graphtype = this.graphtype;
24680         }
24681         if(!opts){
24682             opts = this.opts;
24683         }
24684         var r = this.raphael,
24685             fin = function () {
24686                 this.flag = r.popup(this.bar.x, this.bar.y, this.bar.value || "0").insertBefore(this);
24687             },
24688             fout = function () {
24689                 this.flag.animate({opacity: 0}, 300, function () {this.remove();});
24690             },
24691             pfin = function() {
24692                 this.sector.stop();
24693                 this.sector.scale(1.1, 1.1, this.cx, this.cy);
24694
24695                 if (this.label) {
24696                     this.label[0].stop();
24697                     this.label[0].attr({ r: 7.5 });
24698                     this.label[1].attr({ "font-weight": 800 });
24699                 }
24700             },
24701             pfout = function() {
24702                 this.sector.animate({ transform: 's1 1 ' + this.cx + ' ' + this.cy }, 500, "bounce");
24703
24704                 if (this.label) {
24705                     this.label[0].animate({ r: 5 }, 500, "bounce");
24706                     this.label[1].attr({ "font-weight": 400 });
24707                 }
24708             };
24709
24710         switch(graphtype){
24711             case 'bar':
24712                 this.raphael.barchart(this.g_x,this.g_y,this.g_width,this.g_height,xdata,opts).hover(fin,fout);
24713                 break;
24714             case 'hbar':
24715                 this.raphael.hbarchart(this.g_x,this.g_y,this.g_width,this.g_height,xdata,opts).hover(fin,fout);
24716                 break;
24717             case 'pie':
24718 //                opts = { legend: ["%% - Enterprise Users", "% - ddd","Chrome Users"], legendpos: "west", 
24719 //                href: ["http://raphaeljs.com", "http://g.raphaeljs.com"]};
24720 //            
24721                 this.raphael.piechart(this.g_x,this.g_y,this.g_r,xdata,opts).hover(pfin, pfout);
24722                 
24723                 break;
24724
24725         }
24726         
24727         if(this.title){
24728             this.raphael.text(this.title.x, this.title.y, this.title.text).attr(this.title.attr);
24729         }
24730         
24731     },
24732     
24733     setTitle: function(o)
24734     {
24735         this.title = o;
24736     },
24737     
24738     initEvents: function() {
24739         
24740         if(!this.href){
24741             this.el.on('click', this.onClick, this);
24742         }
24743     },
24744     
24745     onClick : function(e)
24746     {
24747         Roo.log('img onclick');
24748         this.fireEvent('click', this, e);
24749     }
24750    
24751 });
24752
24753  
24754 /*
24755  * - LGPL
24756  *
24757  * numberBox
24758  * 
24759  */
24760 Roo.bootstrap.dash = Roo.bootstrap.dash || {};
24761
24762 /**
24763  * @class Roo.bootstrap.dash.NumberBox
24764  * @extends Roo.bootstrap.Component
24765  * Bootstrap NumberBox class
24766  * @cfg {String} headline Box headline
24767  * @cfg {String} content Box content
24768  * @cfg {String} icon Box icon
24769  * @cfg {String} footer Footer text
24770  * @cfg {String} fhref Footer href
24771  * 
24772  * @constructor
24773  * Create a new NumberBox
24774  * @param {Object} config The config object
24775  */
24776
24777
24778 Roo.bootstrap.dash.NumberBox = function(config){
24779     Roo.bootstrap.dash.NumberBox.superclass.constructor.call(this, config);
24780     
24781 };
24782
24783 Roo.extend(Roo.bootstrap.dash.NumberBox, Roo.bootstrap.Component,  {
24784     
24785     headline : '',
24786     content : '',
24787     icon : '',
24788     footer : '',
24789     fhref : '',
24790     ficon : '',
24791     
24792     getAutoCreate : function(){
24793         
24794         var cfg = {
24795             tag : 'div',
24796             cls : 'small-box ',
24797             cn : [
24798                 {
24799                     tag : 'div',
24800                     cls : 'inner',
24801                     cn :[
24802                         {
24803                             tag : 'h3',
24804                             cls : 'roo-headline',
24805                             html : this.headline
24806                         },
24807                         {
24808                             tag : 'p',
24809                             cls : 'roo-content',
24810                             html : this.content
24811                         }
24812                     ]
24813                 }
24814             ]
24815         };
24816         
24817         if(this.icon){
24818             cfg.cn.push({
24819                 tag : 'div',
24820                 cls : 'icon',
24821                 cn :[
24822                     {
24823                         tag : 'i',
24824                         cls : 'ion ' + this.icon
24825                     }
24826                 ]
24827             });
24828         }
24829         
24830         if(this.footer){
24831             var footer = {
24832                 tag : 'a',
24833                 cls : 'small-box-footer',
24834                 href : this.fhref || '#',
24835                 html : this.footer
24836             };
24837             
24838             cfg.cn.push(footer);
24839             
24840         }
24841         
24842         return  cfg;
24843     },
24844
24845     onRender : function(ct,position){
24846         Roo.bootstrap.dash.NumberBox.superclass.onRender.call(this,ct,position);
24847
24848
24849        
24850                 
24851     },
24852
24853     setHeadline: function (value)
24854     {
24855         this.el.select('.roo-headline',true).first().dom.innerHTML = value;
24856     },
24857     
24858     setFooter: function (value, href)
24859     {
24860         this.el.select('a.small-box-footer',true).first().dom.innerHTML = value;
24861         
24862         if(href){
24863             this.el.select('a.small-box-footer',true).first().attr('href', href);
24864         }
24865         
24866     },
24867
24868     setContent: function (value)
24869     {
24870         this.el.select('.roo-content',true).first().dom.innerHTML = value;
24871     },
24872
24873     initEvents: function() 
24874     {   
24875         
24876     }
24877     
24878 });
24879
24880  
24881 /*
24882  * - LGPL
24883  *
24884  * TabBox
24885  * 
24886  */
24887 Roo.bootstrap.dash = Roo.bootstrap.dash || {};
24888
24889 /**
24890  * @class Roo.bootstrap.dash.TabBox
24891  * @extends Roo.bootstrap.Component
24892  * Bootstrap TabBox class
24893  * @cfg {String} title Title of the TabBox
24894  * @cfg {String} icon Icon of the TabBox
24895  * @cfg {Boolean} showtabs (true|false) show the tabs default true
24896  * @cfg {Boolean} tabScrollable (true|false) tab scrollable when mobile view default false
24897  * 
24898  * @constructor
24899  * Create a new TabBox
24900  * @param {Object} config The config object
24901  */
24902
24903
24904 Roo.bootstrap.dash.TabBox = function(config){
24905     Roo.bootstrap.dash.TabBox.superclass.constructor.call(this, config);
24906     this.addEvents({
24907         // raw events
24908         /**
24909          * @event addpane
24910          * When a pane is added
24911          * @param {Roo.bootstrap.dash.TabPane} pane
24912          */
24913         "addpane" : true,
24914         /**
24915          * @event activatepane
24916          * When a pane is activated
24917          * @param {Roo.bootstrap.dash.TabPane} pane
24918          */
24919         "activatepane" : true
24920         
24921          
24922     });
24923     
24924     this.panes = [];
24925 };
24926
24927 Roo.extend(Roo.bootstrap.dash.TabBox, Roo.bootstrap.Component,  {
24928
24929     title : '',
24930     icon : false,
24931     showtabs : true,
24932     tabScrollable : false,
24933     
24934     getChildContainer : function()
24935     {
24936         return this.el.select('.tab-content', true).first();
24937     },
24938     
24939     getAutoCreate : function(){
24940         
24941         var header = {
24942             tag: 'li',
24943             cls: 'pull-left header',
24944             html: this.title,
24945             cn : []
24946         };
24947         
24948         if(this.icon){
24949             header.cn.push({
24950                 tag: 'i',
24951                 cls: 'fa ' + this.icon
24952             });
24953         }
24954         
24955         var h = {
24956             tag: 'ul',
24957             cls: 'nav nav-tabs pull-right',
24958             cn: [
24959                 header
24960             ]
24961         };
24962         
24963         if(this.tabScrollable){
24964             h = {
24965                 tag: 'div',
24966                 cls: 'tab-header',
24967                 cn: [
24968                     {
24969                         tag: 'ul',
24970                         cls: 'nav nav-tabs pull-right',
24971                         cn: [
24972                             header
24973                         ]
24974                     }
24975                 ]
24976             };
24977         }
24978         
24979         var cfg = {
24980             tag: 'div',
24981             cls: 'nav-tabs-custom',
24982             cn: [
24983                 h,
24984                 {
24985                     tag: 'div',
24986                     cls: 'tab-content no-padding',
24987                     cn: []
24988                 }
24989             ]
24990         };
24991
24992         return  cfg;
24993     },
24994     initEvents : function()
24995     {
24996         //Roo.log('add add pane handler');
24997         this.on('addpane', this.onAddPane, this);
24998     },
24999      /**
25000      * Updates the box title
25001      * @param {String} html to set the title to.
25002      */
25003     setTitle : function(value)
25004     {
25005         this.el.select('.nav-tabs .header', true).first().dom.innerHTML = value;
25006     },
25007     onAddPane : function(pane)
25008     {
25009         this.panes.push(pane);
25010         //Roo.log('addpane');
25011         //Roo.log(pane);
25012         // tabs are rendere left to right..
25013         if(!this.showtabs){
25014             return;
25015         }
25016         
25017         var ctr = this.el.select('.nav-tabs', true).first();
25018          
25019          
25020         var existing = ctr.select('.nav-tab',true);
25021         var qty = existing.getCount();;
25022         
25023         
25024         var tab = ctr.createChild({
25025             tag : 'li',
25026             cls : 'nav-tab' + (qty ? '' : ' active'),
25027             cn : [
25028                 {
25029                     tag : 'a',
25030                     href:'#',
25031                     html : pane.title
25032                 }
25033             ]
25034         }, qty ? existing.first().dom : ctr.select('.header', true).first().dom );
25035         pane.tab = tab;
25036         
25037         tab.on('click', this.onTabClick.createDelegate(this, [pane], true));
25038         if (!qty) {
25039             pane.el.addClass('active');
25040         }
25041         
25042                 
25043     },
25044     onTabClick : function(ev,un,ob,pane)
25045     {
25046         //Roo.log('tab - prev default');
25047         ev.preventDefault();
25048         
25049         
25050         this.el.select('.nav-tabs li.nav-tab', true).removeClass('active');
25051         pane.tab.addClass('active');
25052         //Roo.log(pane.title);
25053         this.getChildContainer().select('.tab-pane',true).removeClass('active');
25054         // technically we should have a deactivate event.. but maybe add later.
25055         // and it should not de-activate the selected tab...
25056         this.fireEvent('activatepane', pane);
25057         pane.el.addClass('active');
25058         pane.fireEvent('activate');
25059         
25060         
25061     },
25062     
25063     getActivePane : function()
25064     {
25065         var r = false;
25066         Roo.each(this.panes, function(p) {
25067             if(p.el.hasClass('active')){
25068                 r = p;
25069                 return false;
25070             }
25071             
25072             return;
25073         });
25074         
25075         return r;
25076     }
25077     
25078     
25079 });
25080
25081  
25082 /*
25083  * - LGPL
25084  *
25085  * Tab pane
25086  * 
25087  */
25088 Roo.bootstrap.dash = Roo.bootstrap.dash || {};
25089 /**
25090  * @class Roo.bootstrap.TabPane
25091  * @extends Roo.bootstrap.Component
25092  * Bootstrap TabPane class
25093  * @cfg {Boolean} active (false | true) Default false
25094  * @cfg {String} title title of panel
25095
25096  * 
25097  * @constructor
25098  * Create a new TabPane
25099  * @param {Object} config The config object
25100  */
25101
25102 Roo.bootstrap.dash.TabPane = function(config){
25103     Roo.bootstrap.dash.TabPane.superclass.constructor.call(this, config);
25104     
25105     this.addEvents({
25106         // raw events
25107         /**
25108          * @event activate
25109          * When a pane is activated
25110          * @param {Roo.bootstrap.dash.TabPane} pane
25111          */
25112         "activate" : true
25113          
25114     });
25115 };
25116
25117 Roo.extend(Roo.bootstrap.dash.TabPane, Roo.bootstrap.Component,  {
25118     
25119     active : false,
25120     title : '',
25121     
25122     // the tabBox that this is attached to.
25123     tab : false,
25124      
25125     getAutoCreate : function() 
25126     {
25127         var cfg = {
25128             tag: 'div',
25129             cls: 'tab-pane'
25130         };
25131         
25132         if(this.active){
25133             cfg.cls += ' active';
25134         }
25135         
25136         return cfg;
25137     },
25138     initEvents  : function()
25139     {
25140         //Roo.log('trigger add pane handler');
25141         this.parent().fireEvent('addpane', this)
25142     },
25143     
25144      /**
25145      * Updates the tab title 
25146      * @param {String} html to set the title to.
25147      */
25148     setTitle: function(str)
25149     {
25150         if (!this.tab) {
25151             return;
25152         }
25153         this.title = str;
25154         this.tab.select('a', true).first().dom.innerHTML = str;
25155         
25156     }
25157     
25158     
25159     
25160 });
25161
25162  
25163
25164
25165  /*
25166  * - LGPL
25167  *
25168  * menu
25169  * 
25170  */
25171 Roo.bootstrap.menu = Roo.bootstrap.menu || {};
25172
25173 /**
25174  * @class Roo.bootstrap.menu.Menu
25175  * @extends Roo.bootstrap.Component
25176  * Bootstrap Menu class - container for Menu
25177  * @cfg {String} html Text of the menu
25178  * @cfg {String} weight (default | primary | success | info | warning | danger | inverse)
25179  * @cfg {String} icon Font awesome icon
25180  * @cfg {String} pos Menu align to (top | bottom) default bottom
25181  * 
25182  * 
25183  * @constructor
25184  * Create a new Menu
25185  * @param {Object} config The config object
25186  */
25187
25188
25189 Roo.bootstrap.menu.Menu = function(config){
25190     Roo.bootstrap.menu.Menu.superclass.constructor.call(this, config);
25191     
25192     this.addEvents({
25193         /**
25194          * @event beforeshow
25195          * Fires before this menu is displayed
25196          * @param {Roo.bootstrap.menu.Menu} this
25197          */
25198         beforeshow : true,
25199         /**
25200          * @event beforehide
25201          * Fires before this menu is hidden
25202          * @param {Roo.bootstrap.menu.Menu} this
25203          */
25204         beforehide : true,
25205         /**
25206          * @event show
25207          * Fires after this menu is displayed
25208          * @param {Roo.bootstrap.menu.Menu} this
25209          */
25210         show : true,
25211         /**
25212          * @event hide
25213          * Fires after this menu is hidden
25214          * @param {Roo.bootstrap.menu.Menu} this
25215          */
25216         hide : true,
25217         /**
25218          * @event click
25219          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
25220          * @param {Roo.bootstrap.menu.Menu} this
25221          * @param {Roo.EventObject} e
25222          */
25223         click : true
25224     });
25225     
25226 };
25227
25228 Roo.extend(Roo.bootstrap.menu.Menu, Roo.bootstrap.Component,  {
25229     
25230     submenu : false,
25231     html : '',
25232     weight : 'default',
25233     icon : false,
25234     pos : 'bottom',
25235     
25236     
25237     getChildContainer : function() {
25238         if(this.isSubMenu){
25239             return this.el;
25240         }
25241         
25242         return this.el.select('ul.dropdown-menu', true).first();  
25243     },
25244     
25245     getAutoCreate : function()
25246     {
25247         var text = [
25248             {
25249                 tag : 'span',
25250                 cls : 'roo-menu-text',
25251                 html : this.html
25252             }
25253         ];
25254         
25255         if(this.icon){
25256             text.unshift({
25257                 tag : 'i',
25258                 cls : 'fa ' + this.icon
25259             })
25260         }
25261         
25262         
25263         var cfg = {
25264             tag : 'div',
25265             cls : 'btn-group',
25266             cn : [
25267                 {
25268                     tag : 'button',
25269                     cls : 'dropdown-button btn btn-' + this.weight,
25270                     cn : text
25271                 },
25272                 {
25273                     tag : 'button',
25274                     cls : 'dropdown-toggle btn btn-' + this.weight,
25275                     cn : [
25276                         {
25277                             tag : 'span',
25278                             cls : 'caret'
25279                         }
25280                     ]
25281                 },
25282                 {
25283                     tag : 'ul',
25284                     cls : 'dropdown-menu'
25285                 }
25286             ]
25287             
25288         };
25289         
25290         if(this.pos == 'top'){
25291             cfg.cls += ' dropup';
25292         }
25293         
25294         if(this.isSubMenu){
25295             cfg = {
25296                 tag : 'ul',
25297                 cls : 'dropdown-menu'
25298             }
25299         }
25300         
25301         return cfg;
25302     },
25303     
25304     onRender : function(ct, position)
25305     {
25306         this.isSubMenu = ct.hasClass('dropdown-submenu');
25307         
25308         Roo.bootstrap.menu.Menu.superclass.onRender.call(this, ct, position);
25309     },
25310     
25311     initEvents : function() 
25312     {
25313         if(this.isSubMenu){
25314             return;
25315         }
25316         
25317         this.hidden = true;
25318         
25319         this.triggerEl = this.el.select('button.dropdown-toggle', true).first();
25320         this.triggerEl.on('click', this.onTriggerPress, this);
25321         
25322         this.buttonEl = this.el.select('button.dropdown-button', true).first();
25323         this.buttonEl.on('click', this.onClick, this);
25324         
25325     },
25326     
25327     list : function()
25328     {
25329         if(this.isSubMenu){
25330             return this.el;
25331         }
25332         
25333         return this.el.select('ul.dropdown-menu', true).first();
25334     },
25335     
25336     onClick : function(e)
25337     {
25338         this.fireEvent("click", this, e);
25339     },
25340     
25341     onTriggerPress  : function(e)
25342     {   
25343         if (this.isVisible()) {
25344             this.hide();
25345         } else {
25346             this.show();
25347         }
25348     },
25349     
25350     isVisible : function(){
25351         return !this.hidden;
25352     },
25353     
25354     show : function()
25355     {
25356         this.fireEvent("beforeshow", this);
25357         
25358         this.hidden = false;
25359         this.el.addClass('open');
25360         
25361         Roo.get(document).on("mouseup", this.onMouseUp, this);
25362         
25363         this.fireEvent("show", this);
25364         
25365         
25366     },
25367     
25368     hide : function()
25369     {
25370         this.fireEvent("beforehide", this);
25371         
25372         this.hidden = true;
25373         this.el.removeClass('open');
25374         
25375         Roo.get(document).un("mouseup", this.onMouseUp);
25376         
25377         this.fireEvent("hide", this);
25378     },
25379     
25380     onMouseUp : function()
25381     {
25382         this.hide();
25383     }
25384     
25385 });
25386
25387  
25388  /*
25389  * - LGPL
25390  *
25391  * menu item
25392  * 
25393  */
25394 Roo.bootstrap.menu = Roo.bootstrap.menu || {};
25395
25396 /**
25397  * @class Roo.bootstrap.menu.Item
25398  * @extends Roo.bootstrap.Component
25399  * Bootstrap MenuItem class
25400  * @cfg {Boolean} submenu (true | false) default false
25401  * @cfg {String} html text of the item
25402  * @cfg {String} href the link
25403  * @cfg {Boolean} disable (true | false) default false
25404  * @cfg {Boolean} preventDefault (true | false) default true
25405  * @cfg {String} icon Font awesome icon
25406  * @cfg {String} pos Submenu align to (left | right) default right 
25407  * 
25408  * 
25409  * @constructor
25410  * Create a new Item
25411  * @param {Object} config The config object
25412  */
25413
25414
25415 Roo.bootstrap.menu.Item = function(config){
25416     Roo.bootstrap.menu.Item.superclass.constructor.call(this, config);
25417     this.addEvents({
25418         /**
25419          * @event mouseover
25420          * Fires when the mouse is hovering over this menu
25421          * @param {Roo.bootstrap.menu.Item} this
25422          * @param {Roo.EventObject} e
25423          */
25424         mouseover : true,
25425         /**
25426          * @event mouseout
25427          * Fires when the mouse exits this menu
25428          * @param {Roo.bootstrap.menu.Item} this
25429          * @param {Roo.EventObject} e
25430          */
25431         mouseout : true,
25432         // raw events
25433         /**
25434          * @event click
25435          * The raw click event for the entire grid.
25436          * @param {Roo.EventObject} e
25437          */
25438         click : true
25439     });
25440 };
25441
25442 Roo.extend(Roo.bootstrap.menu.Item, Roo.bootstrap.Component,  {
25443     
25444     submenu : false,
25445     href : '',
25446     html : '',
25447     preventDefault: true,
25448     disable : false,
25449     icon : false,
25450     pos : 'right',
25451     
25452     getAutoCreate : function()
25453     {
25454         var text = [
25455             {
25456                 tag : 'span',
25457                 cls : 'roo-menu-item-text',
25458                 html : this.html
25459             }
25460         ];
25461         
25462         if(this.icon){
25463             text.unshift({
25464                 tag : 'i',
25465                 cls : 'fa ' + this.icon
25466             })
25467         }
25468         
25469         var cfg = {
25470             tag : 'li',
25471             cn : [
25472                 {
25473                     tag : 'a',
25474                     href : this.href || '#',
25475                     cn : text
25476                 }
25477             ]
25478         };
25479         
25480         if(this.disable){
25481             cfg.cls = (typeof(cfg.cls) == 'undefined') ? 'disabled' : (cfg.cls + ' disabled');
25482         }
25483         
25484         if(this.submenu){
25485             cfg.cls = (typeof(cfg.cls) == 'undefined') ? 'dropdown-submenu' : (cfg.cls + ' dropdown-submenu');
25486             
25487             if(this.pos == 'left'){
25488                 cfg.cls = (typeof(cfg.cls) == 'undefined') ? 'pull-left' : (cfg.cls + ' pull-left');
25489             }
25490         }
25491         
25492         return cfg;
25493     },
25494     
25495     initEvents : function() 
25496     {
25497         this.el.on('mouseover', this.onMouseOver, this);
25498         this.el.on('mouseout', this.onMouseOut, this);
25499         
25500         this.el.select('a', true).first().on('click', this.onClick, this);
25501         
25502     },
25503     
25504     onClick : function(e)
25505     {
25506         if(this.preventDefault){
25507             e.preventDefault();
25508         }
25509         
25510         this.fireEvent("click", this, e);
25511     },
25512     
25513     onMouseOver : function(e)
25514     {
25515         if(this.submenu && this.pos == 'left'){
25516             this.el.select('ul.dropdown-menu', true).first().setLeft(this.el.select('ul.dropdown-menu', true).first().getWidth() * -1);
25517         }
25518         
25519         this.fireEvent("mouseover", this, e);
25520     },
25521     
25522     onMouseOut : function(e)
25523     {
25524         this.fireEvent("mouseout", this, e);
25525     }
25526 });
25527
25528  
25529
25530  /*
25531  * - LGPL
25532  *
25533  * menu separator
25534  * 
25535  */
25536 Roo.bootstrap.menu = Roo.bootstrap.menu || {};
25537
25538 /**
25539  * @class Roo.bootstrap.menu.Separator
25540  * @extends Roo.bootstrap.Component
25541  * Bootstrap Separator class
25542  * 
25543  * @constructor
25544  * Create a new Separator
25545  * @param {Object} config The config object
25546  */
25547
25548
25549 Roo.bootstrap.menu.Separator = function(config){
25550     Roo.bootstrap.menu.Separator.superclass.constructor.call(this, config);
25551 };
25552
25553 Roo.extend(Roo.bootstrap.menu.Separator, Roo.bootstrap.Component,  {
25554     
25555     getAutoCreate : function(){
25556         var cfg = {
25557             tag : 'li',
25558             cls: 'divider'
25559         };
25560         
25561         return cfg;
25562     }
25563    
25564 });
25565
25566  
25567
25568  /*
25569  * - LGPL
25570  *
25571  * Tooltip
25572  * 
25573  */
25574
25575 /**
25576  * @class Roo.bootstrap.Tooltip
25577  * Bootstrap Tooltip class
25578  * This is basic at present - all componets support it by default, however they should add tooltipEl() method
25579  * to determine which dom element triggers the tooltip.
25580  * 
25581  * It needs to add support for additional attributes like tooltip-position
25582  * 
25583  * @constructor
25584  * Create a new Toolti
25585  * @param {Object} config The config object
25586  */
25587
25588 Roo.bootstrap.Tooltip = function(config){
25589     Roo.bootstrap.Tooltip.superclass.constructor.call(this, config);
25590     
25591     this.alignment = Roo.bootstrap.Tooltip.alignment;
25592     
25593     if(typeof(config) != 'undefined' && typeof(config.alignment) != 'undefined'){
25594         this.alignment = config.alignment;
25595     }
25596     
25597 };
25598
25599 Roo.apply(Roo.bootstrap.Tooltip, {
25600     /**
25601      * @function init initialize tooltip monitoring.
25602      * @static
25603      */
25604     currentEl : false,
25605     currentTip : false,
25606     currentRegion : false,
25607     
25608     //  init : delay?
25609     
25610     init : function()
25611     {
25612         Roo.get(document).on('mouseover', this.enter ,this);
25613         Roo.get(document).on('mouseout', this.leave, this);
25614          
25615         
25616         this.currentTip = new Roo.bootstrap.Tooltip();
25617     },
25618     
25619     enter : function(ev)
25620     {
25621         var dom = ev.getTarget();
25622         
25623         //Roo.log(['enter',dom]);
25624         var el = Roo.fly(dom);
25625         if (this.currentEl) {
25626             //Roo.log(dom);
25627             //Roo.log(this.currentEl);
25628             //Roo.log(this.currentEl.contains(dom));
25629             if (this.currentEl == el) {
25630                 return;
25631             }
25632             if (dom != this.currentEl.dom && this.currentEl.contains(dom)) {
25633                 return;
25634             }
25635
25636         }
25637         
25638         if (this.currentTip.el) {
25639             this.currentTip.el.setVisibilityMode(Roo.Element.DISPLAY).hide(); // force hiding...
25640         }    
25641         //Roo.log(ev);
25642         
25643         if(!el || el.dom == document){
25644             return;
25645         }
25646         
25647         var bindEl = el;
25648         
25649         // you can not look for children, as if el is the body.. then everythign is the child..
25650         if (!el.attr('tooltip')) { //
25651             if (!el.select("[tooltip]").elements.length) {
25652                 return;
25653             }
25654             // is the mouse over this child...?
25655             bindEl = el.select("[tooltip]").first();
25656             var xy = ev.getXY();
25657             if (!bindEl.getRegion().contains( { top : xy[1] ,right : xy[0] , bottom : xy[1], left : xy[0]})) {
25658                 //Roo.log("not in region.");
25659                 return;
25660             }
25661             //Roo.log("child element over..");
25662             
25663         }
25664         this.currentEl = bindEl;
25665         this.currentTip.bind(bindEl);
25666         this.currentRegion = Roo.lib.Region.getRegion(dom);
25667         this.currentTip.enter();
25668         
25669     },
25670     leave : function(ev)
25671     {
25672         var dom = ev.getTarget();
25673         //Roo.log(['leave',dom]);
25674         if (!this.currentEl) {
25675             return;
25676         }
25677         
25678         
25679         if (dom != this.currentEl.dom) {
25680             return;
25681         }
25682         var xy = ev.getXY();
25683         if (this.currentRegion.contains( new Roo.lib.Region( xy[1], xy[0] ,xy[1], xy[0]  ))) {
25684             return;
25685         }
25686         // only activate leave if mouse cursor is outside... bounding box..
25687         
25688         
25689         
25690         
25691         if (this.currentTip) {
25692             this.currentTip.leave();
25693         }
25694         //Roo.log('clear currentEl');
25695         this.currentEl = false;
25696         
25697         
25698     },
25699     alignment : {
25700         'left' : ['r-l', [-2,0], 'right'],
25701         'right' : ['l-r', [2,0], 'left'],
25702         'bottom' : ['t-b', [0,2], 'top'],
25703         'top' : [ 'b-t', [0,-2], 'bottom']
25704     }
25705     
25706 });
25707
25708
25709 Roo.extend(Roo.bootstrap.Tooltip, Roo.bootstrap.Component,  {
25710     
25711     
25712     bindEl : false,
25713     
25714     delay : null, // can be { show : 300 , hide: 500}
25715     
25716     timeout : null,
25717     
25718     hoverState : null, //???
25719     
25720     placement : 'bottom', 
25721     
25722     alignment : false,
25723     
25724     getAutoCreate : function(){
25725     
25726         var cfg = {
25727            cls : 'tooltip',
25728            role : 'tooltip',
25729            cn : [
25730                 {
25731                     cls : 'tooltip-arrow'
25732                 },
25733                 {
25734                     cls : 'tooltip-inner'
25735                 }
25736            ]
25737         };
25738         
25739         return cfg;
25740     },
25741     bind : function(el)
25742     {
25743         this.bindEl = el;
25744     },
25745       
25746     
25747     enter : function () {
25748        
25749         if (this.timeout != null) {
25750             clearTimeout(this.timeout);
25751         }
25752         
25753         this.hoverState = 'in';
25754          //Roo.log("enter - show");
25755         if (!this.delay || !this.delay.show) {
25756             this.show();
25757             return;
25758         }
25759         var _t = this;
25760         this.timeout = setTimeout(function () {
25761             if (_t.hoverState == 'in') {
25762                 _t.show();
25763             }
25764         }, this.delay.show);
25765     },
25766     leave : function()
25767     {
25768         clearTimeout(this.timeout);
25769     
25770         this.hoverState = 'out';
25771          if (!this.delay || !this.delay.hide) {
25772             this.hide();
25773             return;
25774         }
25775        
25776         var _t = this;
25777         this.timeout = setTimeout(function () {
25778             //Roo.log("leave - timeout");
25779             
25780             if (_t.hoverState == 'out') {
25781                 _t.hide();
25782                 Roo.bootstrap.Tooltip.currentEl = false;
25783             }
25784         }, delay);
25785     },
25786     
25787     show : function (msg)
25788     {
25789         if (!this.el) {
25790             this.render(document.body);
25791         }
25792         // set content.
25793         //Roo.log([this.bindEl, this.bindEl.attr('tooltip')]);
25794         
25795         var tip = msg || this.bindEl.attr('tooltip') || this.bindEl.select("[tooltip]").first().attr('tooltip');
25796         
25797         this.el.select('.tooltip-inner',true).first().dom.innerHTML = tip;
25798         
25799         this.el.removeClass(['fade','top','bottom', 'left', 'right','in']);
25800         
25801         var placement = typeof this.placement == 'function' ?
25802             this.placement.call(this, this.el, on_el) :
25803             this.placement;
25804             
25805         var autoToken = /\s?auto?\s?/i;
25806         var autoPlace = autoToken.test(placement);
25807         if (autoPlace) {
25808             placement = placement.replace(autoToken, '') || 'top';
25809         }
25810         
25811         //this.el.detach()
25812         //this.el.setXY([0,0]);
25813         this.el.show();
25814         //this.el.dom.style.display='block';
25815         
25816         //this.el.appendTo(on_el);
25817         
25818         var p = this.getPosition();
25819         var box = this.el.getBox();
25820         
25821         if (autoPlace) {
25822             // fixme..
25823         }
25824         
25825         var align = this.alignment[placement];
25826         
25827         var xy = this.el.getAlignToXY(this.bindEl, align[0], align[1]);
25828         
25829         if(placement == 'top' || placement == 'bottom'){
25830             if(xy[0] < 0){
25831                 placement = 'right';
25832             }
25833             
25834             if(xy[0] + this.el.getWidth() > Roo.lib.Dom.getViewWidth()){
25835                 placement = 'left';
25836             }
25837             
25838             var scroll = Roo.select('body', true).first().getScroll();
25839             
25840             if(xy[1] > Roo.lib.Dom.getViewHeight() + scroll.top - this.el.getHeight()){
25841                 placement = 'top';
25842             }
25843             
25844         }
25845         
25846         this.el.alignTo(this.bindEl, align[0],align[1]);
25847         //var arrow = this.el.select('.arrow',true).first();
25848         //arrow.set(align[2], 
25849         
25850         this.el.addClass(placement);
25851         
25852         this.el.addClass('in fade');
25853         
25854         this.hoverState = null;
25855         
25856         if (this.el.hasClass('fade')) {
25857             // fade it?
25858         }
25859         
25860     },
25861     hide : function()
25862     {
25863          
25864         if (!this.el) {
25865             return;
25866         }
25867         //this.el.setXY([0,0]);
25868         this.el.removeClass('in');
25869         //this.el.hide();
25870         
25871     }
25872     
25873 });
25874  
25875
25876  /*
25877  * - LGPL
25878  *
25879  * Location Picker
25880  * 
25881  */
25882
25883 /**
25884  * @class Roo.bootstrap.LocationPicker
25885  * @extends Roo.bootstrap.Component
25886  * Bootstrap LocationPicker class
25887  * @cfg {Number} latitude Position when init default 0
25888  * @cfg {Number} longitude Position when init default 0
25889  * @cfg {Number} zoom default 15
25890  * @cfg {String} mapTypeId default google.maps.MapTypeId.ROADMAP
25891  * @cfg {Boolean} mapTypeControl default false
25892  * @cfg {Boolean} disableDoubleClickZoom default false
25893  * @cfg {Boolean} scrollwheel default true
25894  * @cfg {Boolean} streetViewControl default false
25895  * @cfg {Number} radius default 0
25896  * @cfg {String} locationName
25897  * @cfg {Boolean} draggable default true
25898  * @cfg {Boolean} enableAutocomplete default false
25899  * @cfg {Boolean} enableReverseGeocode default true
25900  * @cfg {String} markerTitle
25901  * 
25902  * @constructor
25903  * Create a new LocationPicker
25904  * @param {Object} config The config object
25905  */
25906
25907
25908 Roo.bootstrap.LocationPicker = function(config){
25909     
25910     Roo.bootstrap.LocationPicker.superclass.constructor.call(this, config);
25911     
25912     this.addEvents({
25913         /**
25914          * @event initial
25915          * Fires when the picker initialized.
25916          * @param {Roo.bootstrap.LocationPicker} this
25917          * @param {Google Location} location
25918          */
25919         initial : true,
25920         /**
25921          * @event positionchanged
25922          * Fires when the picker position changed.
25923          * @param {Roo.bootstrap.LocationPicker} this
25924          * @param {Google Location} location
25925          */
25926         positionchanged : true,
25927         /**
25928          * @event resize
25929          * Fires when the map resize.
25930          * @param {Roo.bootstrap.LocationPicker} this
25931          */
25932         resize : true,
25933         /**
25934          * @event show
25935          * Fires when the map show.
25936          * @param {Roo.bootstrap.LocationPicker} this
25937          */
25938         show : true,
25939         /**
25940          * @event hide
25941          * Fires when the map hide.
25942          * @param {Roo.bootstrap.LocationPicker} this
25943          */
25944         hide : true,
25945         /**
25946          * @event mapClick
25947          * Fires when click the map.
25948          * @param {Roo.bootstrap.LocationPicker} this
25949          * @param {Map event} e
25950          */
25951         mapClick : true,
25952         /**
25953          * @event mapRightClick
25954          * Fires when right click the map.
25955          * @param {Roo.bootstrap.LocationPicker} this
25956          * @param {Map event} e
25957          */
25958         mapRightClick : true,
25959         /**
25960          * @event markerClick
25961          * Fires when click the marker.
25962          * @param {Roo.bootstrap.LocationPicker} this
25963          * @param {Map event} e
25964          */
25965         markerClick : true,
25966         /**
25967          * @event markerRightClick
25968          * Fires when right click the marker.
25969          * @param {Roo.bootstrap.LocationPicker} this
25970          * @param {Map event} e
25971          */
25972         markerRightClick : true,
25973         /**
25974          * @event OverlayViewDraw
25975          * Fires when OverlayView Draw
25976          * @param {Roo.bootstrap.LocationPicker} this
25977          */
25978         OverlayViewDraw : true,
25979         /**
25980          * @event OverlayViewOnAdd
25981          * Fires when OverlayView Draw
25982          * @param {Roo.bootstrap.LocationPicker} this
25983          */
25984         OverlayViewOnAdd : true,
25985         /**
25986          * @event OverlayViewOnRemove
25987          * Fires when OverlayView Draw
25988          * @param {Roo.bootstrap.LocationPicker} this
25989          */
25990         OverlayViewOnRemove : true,
25991         /**
25992          * @event OverlayViewShow
25993          * Fires when OverlayView Draw
25994          * @param {Roo.bootstrap.LocationPicker} this
25995          * @param {Pixel} cpx
25996          */
25997         OverlayViewShow : true,
25998         /**
25999          * @event OverlayViewHide
26000          * Fires when OverlayView Draw
26001          * @param {Roo.bootstrap.LocationPicker} this
26002          */
26003         OverlayViewHide : true,
26004         /**
26005          * @event loadexception
26006          * Fires when load google lib failed.
26007          * @param {Roo.bootstrap.LocationPicker} this
26008          */
26009         loadexception : true
26010     });
26011         
26012 };
26013
26014 Roo.extend(Roo.bootstrap.LocationPicker, Roo.bootstrap.Component,  {
26015     
26016     gMapContext: false,
26017     
26018     latitude: 0,
26019     longitude: 0,
26020     zoom: 15,
26021     mapTypeId: false,
26022     mapTypeControl: false,
26023     disableDoubleClickZoom: false,
26024     scrollwheel: true,
26025     streetViewControl: false,
26026     radius: 0,
26027     locationName: '',
26028     draggable: true,
26029     enableAutocomplete: false,
26030     enableReverseGeocode: true,
26031     markerTitle: '',
26032     
26033     getAutoCreate: function()
26034     {
26035
26036         var cfg = {
26037             tag: 'div',
26038             cls: 'roo-location-picker'
26039         };
26040         
26041         return cfg
26042     },
26043     
26044     initEvents: function(ct, position)
26045     {       
26046         if(!this.el.getWidth() || this.isApplied()){
26047             return;
26048         }
26049         
26050         this.el.setVisibilityMode(Roo.Element.DISPLAY);
26051         
26052         this.initial();
26053     },
26054     
26055     initial: function()
26056     {
26057         if(typeof(google) == 'undefined' || typeof(google.maps) == 'undefined'){
26058             this.fireEvent('loadexception', this);
26059             return;
26060         }
26061         
26062         if(!this.mapTypeId){
26063             this.mapTypeId = google.maps.MapTypeId.ROADMAP;
26064         }
26065         
26066         this.gMapContext = this.GMapContext();
26067         
26068         this.initOverlayView();
26069         
26070         this.OverlayView = new Roo.bootstrap.LocationPicker.OverlayView(this.gMapContext.map);
26071         
26072         var _this = this;
26073                 
26074         google.maps.event.addListener(this.gMapContext.marker, "dragend", function(event) {
26075             _this.setPosition(_this.gMapContext.marker.position);
26076         });
26077         
26078         google.maps.event.addListener(this.gMapContext.map, 'click', function(event){
26079             _this.fireEvent('mapClick', this, event);
26080             
26081         });
26082
26083         google.maps.event.addListener(this.gMapContext.map, 'rightclick', function(event){
26084             _this.fireEvent('mapRightClick', this, event);
26085             
26086         });
26087         
26088         google.maps.event.addListener(this.gMapContext.marker, 'click', function(event){
26089             _this.fireEvent('markerClick', this, event);
26090             
26091         });
26092
26093         google.maps.event.addListener(this.gMapContext.marker, 'rightclick', function(event){
26094             _this.fireEvent('markerRightClick', this, event);
26095             
26096         });
26097         
26098         this.setPosition(this.gMapContext.location);
26099         
26100         this.fireEvent('initial', this, this.gMapContext.location);
26101     },
26102     
26103     initOverlayView: function()
26104     {
26105         var _this = this;
26106         
26107         Roo.bootstrap.LocationPicker.OverlayView.prototype = Roo.apply(new google.maps.OverlayView(), {
26108             
26109             draw: function()
26110             {
26111                 _this.fireEvent('OverlayViewDraw', _this);
26112             },
26113             
26114             onAdd: function()
26115             {
26116                 _this.fireEvent('OverlayViewOnAdd', _this);
26117             },
26118             
26119             onRemove: function()
26120             {
26121                 _this.fireEvent('OverlayViewOnRemove', _this);
26122             },
26123             
26124             show: function(cpx)
26125             {
26126                 _this.fireEvent('OverlayViewShow', _this, cpx);
26127             },
26128             
26129             hide: function()
26130             {
26131                 _this.fireEvent('OverlayViewHide', _this);
26132             }
26133             
26134         });
26135     },
26136     
26137     fromLatLngToContainerPixel: function(event)
26138     {
26139         return this.OverlayView.getProjection().fromLatLngToContainerPixel(event.latLng);
26140     },
26141     
26142     isApplied: function() 
26143     {
26144         return this.getGmapContext() == false ? false : true;
26145     },
26146     
26147     getGmapContext: function() 
26148     {
26149         return (typeof(this.gMapContext) == 'undefined') ? false : this.gMapContext;
26150     },
26151     
26152     GMapContext: function() 
26153     {
26154         var position = new google.maps.LatLng(this.latitude, this.longitude);
26155         
26156         var _map = new google.maps.Map(this.el.dom, {
26157             center: position,
26158             zoom: this.zoom,
26159             mapTypeId: this.mapTypeId,
26160             mapTypeControl: this.mapTypeControl,
26161             disableDoubleClickZoom: this.disableDoubleClickZoom,
26162             scrollwheel: this.scrollwheel,
26163             streetViewControl: this.streetViewControl,
26164             locationName: this.locationName,
26165             draggable: this.draggable,
26166             enableAutocomplete: this.enableAutocomplete,
26167             enableReverseGeocode: this.enableReverseGeocode
26168         });
26169         
26170         var _marker = new google.maps.Marker({
26171             position: position,
26172             map: _map,
26173             title: this.markerTitle,
26174             draggable: this.draggable
26175         });
26176         
26177         return {
26178             map: _map,
26179             marker: _marker,
26180             circle: null,
26181             location: position,
26182             radius: this.radius,
26183             locationName: this.locationName,
26184             addressComponents: {
26185                 formatted_address: null,
26186                 addressLine1: null,
26187                 addressLine2: null,
26188                 streetName: null,
26189                 streetNumber: null,
26190                 city: null,
26191                 district: null,
26192                 state: null,
26193                 stateOrProvince: null
26194             },
26195             settings: this,
26196             domContainer: this.el.dom,
26197             geodecoder: new google.maps.Geocoder()
26198         };
26199     },
26200     
26201     drawCircle: function(center, radius, options) 
26202     {
26203         if (this.gMapContext.circle != null) {
26204             this.gMapContext.circle.setMap(null);
26205         }
26206         if (radius > 0) {
26207             radius *= 1;
26208             options = Roo.apply({}, options, {
26209                 strokeColor: "#0000FF",
26210                 strokeOpacity: .35,
26211                 strokeWeight: 2,
26212                 fillColor: "#0000FF",
26213                 fillOpacity: .2
26214             });
26215             
26216             options.map = this.gMapContext.map;
26217             options.radius = radius;
26218             options.center = center;
26219             this.gMapContext.circle = new google.maps.Circle(options);
26220             return this.gMapContext.circle;
26221         }
26222         
26223         return null;
26224     },
26225     
26226     setPosition: function(location) 
26227     {
26228         this.gMapContext.location = location;
26229         this.gMapContext.marker.setPosition(location);
26230         this.gMapContext.map.panTo(location);
26231         this.drawCircle(location, this.gMapContext.radius, {});
26232         
26233         var _this = this;
26234         
26235         if (this.gMapContext.settings.enableReverseGeocode) {
26236             this.gMapContext.geodecoder.geocode({
26237                 latLng: this.gMapContext.location
26238             }, function(results, status) {
26239                 
26240                 if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
26241                     _this.gMapContext.locationName = results[0].formatted_address;
26242                     _this.gMapContext.addressComponents = _this.address_component_from_google_geocode(results[0].address_components);
26243                     
26244                     _this.fireEvent('positionchanged', this, location);
26245                 }
26246             });
26247             
26248             return;
26249         }
26250         
26251         this.fireEvent('positionchanged', this, location);
26252     },
26253     
26254     resize: function()
26255     {
26256         google.maps.event.trigger(this.gMapContext.map, "resize");
26257         
26258         this.gMapContext.map.setCenter(this.gMapContext.marker.position);
26259         
26260         this.fireEvent('resize', this);
26261     },
26262     
26263     setPositionByLatLng: function(latitude, longitude)
26264     {
26265         this.setPosition(new google.maps.LatLng(latitude, longitude));
26266     },
26267     
26268     getCurrentPosition: function() 
26269     {
26270         return {
26271             latitude: this.gMapContext.location.lat(),
26272             longitude: this.gMapContext.location.lng()
26273         };
26274     },
26275     
26276     getAddressName: function() 
26277     {
26278         return this.gMapContext.locationName;
26279     },
26280     
26281     getAddressComponents: function() 
26282     {
26283         return this.gMapContext.addressComponents;
26284     },
26285     
26286     address_component_from_google_geocode: function(address_components) 
26287     {
26288         var result = {};
26289         
26290         for (var i = 0; i < address_components.length; i++) {
26291             var component = address_components[i];
26292             if (component.types.indexOf("postal_code") >= 0) {
26293                 result.postalCode = component.short_name;
26294             } else if (component.types.indexOf("street_number") >= 0) {
26295                 result.streetNumber = component.short_name;
26296             } else if (component.types.indexOf("route") >= 0) {
26297                 result.streetName = component.short_name;
26298             } else if (component.types.indexOf("neighborhood") >= 0) {
26299                 result.city = component.short_name;
26300             } else if (component.types.indexOf("locality") >= 0) {
26301                 result.city = component.short_name;
26302             } else if (component.types.indexOf("sublocality") >= 0) {
26303                 result.district = component.short_name;
26304             } else if (component.types.indexOf("administrative_area_level_1") >= 0) {
26305                 result.stateOrProvince = component.short_name;
26306             } else if (component.types.indexOf("country") >= 0) {
26307                 result.country = component.short_name;
26308             }
26309         }
26310         
26311         result.addressLine1 = [ result.streetNumber, result.streetName ].join(" ").trim();
26312         result.addressLine2 = "";
26313         return result;
26314     },
26315     
26316     setZoomLevel: function(zoom)
26317     {
26318         this.gMapContext.map.setZoom(zoom);
26319     },
26320     
26321     show: function()
26322     {
26323         if(!this.el){
26324             return;
26325         }
26326         
26327         this.el.show();
26328         
26329         this.resize();
26330         
26331         this.fireEvent('show', this);
26332     },
26333     
26334     hide: function()
26335     {
26336         if(!this.el){
26337             return;
26338         }
26339         
26340         this.el.hide();
26341         
26342         this.fireEvent('hide', this);
26343     }
26344     
26345 });
26346
26347 Roo.apply(Roo.bootstrap.LocationPicker, {
26348     
26349     OverlayView : function(map, options)
26350     {
26351         options = options || {};
26352         
26353         this.setMap(map);
26354     }
26355     
26356     
26357 });/*
26358  * - LGPL
26359  *
26360  * Alert
26361  * 
26362  */
26363
26364 /**
26365  * @class Roo.bootstrap.Alert
26366  * @extends Roo.bootstrap.Component
26367  * Bootstrap Alert class
26368  * @cfg {String} title The title of alert
26369  * @cfg {String} html The content of alert
26370  * @cfg {String} weight (  success | info | warning | danger )
26371  * @cfg {String} faicon font-awesomeicon
26372  * 
26373  * @constructor
26374  * Create a new alert
26375  * @param {Object} config The config object
26376  */
26377
26378
26379 Roo.bootstrap.Alert = function(config){
26380     Roo.bootstrap.Alert.superclass.constructor.call(this, config);
26381     
26382 };
26383
26384 Roo.extend(Roo.bootstrap.Alert, Roo.bootstrap.Component,  {
26385     
26386     title: '',
26387     html: '',
26388     weight: false,
26389     faicon: false,
26390     
26391     getAutoCreate : function()
26392     {
26393         
26394         var cfg = {
26395             tag : 'div',
26396             cls : 'alert',
26397             cn : [
26398                 {
26399                     tag : 'i',
26400                     cls : 'roo-alert-icon'
26401                     
26402                 },
26403                 {
26404                     tag : 'b',
26405                     cls : 'roo-alert-title',
26406                     html : this.title
26407                 },
26408                 {
26409                     tag : 'span',
26410                     cls : 'roo-alert-text',
26411                     html : this.html
26412                 }
26413             ]
26414         };
26415         
26416         if(this.faicon){
26417             cfg.cn[0].cls += ' fa ' + this.faicon;
26418         }
26419         
26420         if(this.weight){
26421             cfg.cls += ' alert-' + this.weight;
26422         }
26423         
26424         return cfg;
26425     },
26426     
26427     initEvents: function() 
26428     {
26429         this.el.setVisibilityMode(Roo.Element.DISPLAY);
26430     },
26431     
26432     setTitle : function(str)
26433     {
26434         this.el.select('.roo-alert-title',true).first().dom.innerHTML = str;
26435     },
26436     
26437     setText : function(str)
26438     {
26439         this.el.select('.roo-alert-text',true).first().dom.innerHTML = str;
26440     },
26441     
26442     setWeight : function(weight)
26443     {
26444         if(this.weight){
26445             this.el.select('.alert',true).first().removeClass('alert-' + this.weight);
26446         }
26447         
26448         this.weight = weight;
26449         
26450         this.el.select('.alert',true).first().addClass('alert-' + this.weight);
26451     },
26452     
26453     setIcon : function(icon)
26454     {
26455         if(this.faicon){
26456             this.el.select('.roo-alert-icon',true).first().removeClass(['fa', 'fa-' + this.faicon]);
26457         }
26458         
26459         this.faicon = icon;
26460         
26461         this.el.select('.roo-alert-icon',true).first().addClass(['fa', 'fa-' + this.faicon]);
26462     },
26463     
26464     hide: function() 
26465     {
26466         this.el.hide();   
26467     },
26468     
26469     show: function() 
26470     {  
26471         this.el.show();   
26472     }
26473     
26474 });
26475
26476  
26477 /*
26478 * Licence: LGPL
26479 */
26480
26481 /**
26482  * @class Roo.bootstrap.UploadCropbox
26483  * @extends Roo.bootstrap.Component
26484  * Bootstrap UploadCropbox class
26485  * @cfg {String} emptyText show when image has been loaded
26486  * @cfg {String} rotateNotify show when image too small to rotate
26487  * @cfg {Number} errorTimeout default 3000
26488  * @cfg {Number} minWidth default 300
26489  * @cfg {Number} minHeight default 300
26490  * @cfg {Array} buttons default ['rotateLeft', 'pictureBtn', 'rotateRight']
26491  * @cfg {Boolean} isDocument (true|false) default false
26492  * @cfg {String} url action url
26493  * @cfg {String} paramName default 'imageUpload'
26494  * @cfg {String} method default POST
26495  * @cfg {Boolean} loadMask (true|false) default true
26496  * @cfg {Boolean} loadingText default 'Loading...'
26497  * 
26498  * @constructor
26499  * Create a new UploadCropbox
26500  * @param {Object} config The config object
26501  */
26502
26503 Roo.bootstrap.UploadCropbox = function(config){
26504     Roo.bootstrap.UploadCropbox.superclass.constructor.call(this, config);
26505     
26506     this.addEvents({
26507         /**
26508          * @event beforeselectfile
26509          * Fire before select file
26510          * @param {Roo.bootstrap.UploadCropbox} this
26511          */
26512         "beforeselectfile" : true,
26513         /**
26514          * @event initial
26515          * Fire after initEvent
26516          * @param {Roo.bootstrap.UploadCropbox} this
26517          */
26518         "initial" : true,
26519         /**
26520          * @event crop
26521          * Fire after initEvent
26522          * @param {Roo.bootstrap.UploadCropbox} this
26523          * @param {String} data
26524          */
26525         "crop" : true,
26526         /**
26527          * @event prepare
26528          * Fire when preparing the file data
26529          * @param {Roo.bootstrap.UploadCropbox} this
26530          * @param {Object} file
26531          */
26532         "prepare" : true,
26533         /**
26534          * @event exception
26535          * Fire when get exception
26536          * @param {Roo.bootstrap.UploadCropbox} this
26537          * @param {XMLHttpRequest} xhr
26538          */
26539         "exception" : true,
26540         /**
26541          * @event beforeloadcanvas
26542          * Fire before load the canvas
26543          * @param {Roo.bootstrap.UploadCropbox} this
26544          * @param {String} src
26545          */
26546         "beforeloadcanvas" : true,
26547         /**
26548          * @event trash
26549          * Fire when trash image
26550          * @param {Roo.bootstrap.UploadCropbox} this
26551          */
26552         "trash" : true,
26553         /**
26554          * @event download
26555          * Fire when download the image
26556          * @param {Roo.bootstrap.UploadCropbox} this
26557          */
26558         "download" : true,
26559         /**
26560          * @event footerbuttonclick
26561          * Fire when footerbuttonclick
26562          * @param {Roo.bootstrap.UploadCropbox} this
26563          * @param {String} type
26564          */
26565         "footerbuttonclick" : true,
26566         /**
26567          * @event resize
26568          * Fire when resize
26569          * @param {Roo.bootstrap.UploadCropbox} this
26570          */
26571         "resize" : true,
26572         /**
26573          * @event rotate
26574          * Fire when rotate the image
26575          * @param {Roo.bootstrap.UploadCropbox} this
26576          * @param {String} pos
26577          */
26578         "rotate" : true,
26579         /**
26580          * @event inspect
26581          * Fire when inspect the file
26582          * @param {Roo.bootstrap.UploadCropbox} this
26583          * @param {Object} file
26584          */
26585         "inspect" : true,
26586         /**
26587          * @event upload
26588          * Fire when xhr upload the file
26589          * @param {Roo.bootstrap.UploadCropbox} this
26590          * @param {Object} data
26591          */
26592         "upload" : true,
26593         /**
26594          * @event arrange
26595          * Fire when arrange the file data
26596          * @param {Roo.bootstrap.UploadCropbox} this
26597          * @param {Object} formData
26598          */
26599         "arrange" : true
26600     });
26601     
26602     this.buttons = this.buttons || Roo.bootstrap.UploadCropbox.footer.STANDARD;
26603 };
26604
26605 Roo.extend(Roo.bootstrap.UploadCropbox, Roo.bootstrap.Component,  {
26606     
26607     emptyText : 'Click to upload image',
26608     rotateNotify : 'Image is too small to rotate',
26609     errorTimeout : 3000,
26610     scale : 0,
26611     baseScale : 1,
26612     rotate : 0,
26613     dragable : false,
26614     pinching : false,
26615     mouseX : 0,
26616     mouseY : 0,
26617     cropData : false,
26618     minWidth : 300,
26619     minHeight : 300,
26620     file : false,
26621     exif : {},
26622     baseRotate : 1,
26623     cropType : 'image/jpeg',
26624     buttons : false,
26625     canvasLoaded : false,
26626     isDocument : false,
26627     method : 'POST',
26628     paramName : 'imageUpload',
26629     loadMask : true,
26630     loadingText : 'Loading...',
26631     maskEl : false,
26632     
26633     getAutoCreate : function()
26634     {
26635         var cfg = {
26636             tag : 'div',
26637             cls : 'roo-upload-cropbox',
26638             cn : [
26639                 {
26640                     tag : 'input',
26641                     cls : 'roo-upload-cropbox-selector',
26642                     type : 'file'
26643                 },
26644                 {
26645                     tag : 'div',
26646                     cls : 'roo-upload-cropbox-body',
26647                     style : 'cursor:pointer',
26648                     cn : [
26649                         {
26650                             tag : 'div',
26651                             cls : 'roo-upload-cropbox-preview'
26652                         },
26653                         {
26654                             tag : 'div',
26655                             cls : 'roo-upload-cropbox-thumb'
26656                         },
26657                         {
26658                             tag : 'div',
26659                             cls : 'roo-upload-cropbox-empty-notify',
26660                             html : this.emptyText
26661                         },
26662                         {
26663                             tag : 'div',
26664                             cls : 'roo-upload-cropbox-error-notify alert alert-danger',
26665                             html : this.rotateNotify
26666                         }
26667                     ]
26668                 },
26669                 {
26670                     tag : 'div',
26671                     cls : 'roo-upload-cropbox-footer',
26672                     cn : {
26673                         tag : 'div',
26674                         cls : 'btn-group btn-group-justified roo-upload-cropbox-btn-group',
26675                         cn : []
26676                     }
26677                 }
26678             ]
26679         };
26680         
26681         return cfg;
26682     },
26683     
26684     onRender : function(ct, position)
26685     {
26686         Roo.bootstrap.UploadCropbox.superclass.onRender.call(this, ct, position);
26687         
26688         if (this.buttons.length) {
26689             
26690             Roo.each(this.buttons, function(bb) {
26691                 
26692                 var btn = this.el.select('.roo-upload-cropbox-footer div.roo-upload-cropbox-btn-group').first().createChild(bb);
26693                 
26694                 btn.on('click', this.onFooterButtonClick.createDelegate(this, [bb.action], true));
26695                 
26696             }, this);
26697         }
26698         
26699         if(this.loadMask){
26700             this.maskEl = this.el;
26701         }
26702     },
26703     
26704     initEvents : function()
26705     {
26706         this.urlAPI = (window.createObjectURL && window) || 
26707                                 (window.URL && URL.revokeObjectURL && URL) || 
26708                                 (window.webkitURL && webkitURL);
26709                         
26710         this.bodyEl = this.el.select('.roo-upload-cropbox-body', true).first();
26711         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
26712         
26713         this.selectorEl = this.el.select('.roo-upload-cropbox-selector', true).first();
26714         this.selectorEl.hide();
26715         
26716         this.previewEl = this.el.select('.roo-upload-cropbox-preview', true).first();
26717         this.previewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
26718         
26719         this.thumbEl = this.el.select('.roo-upload-cropbox-thumb', true).first();
26720         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
26721         this.thumbEl.hide();
26722         
26723         this.notifyEl = this.el.select('.roo-upload-cropbox-empty-notify', true).first();
26724         this.notifyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
26725         
26726         this.errorEl = this.el.select('.roo-upload-cropbox-error-notify', true).first();
26727         this.errorEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
26728         this.errorEl.hide();
26729         
26730         this.footerEl = this.el.select('.roo-upload-cropbox-footer', true).first();
26731         this.footerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
26732         this.footerEl.hide();
26733         
26734         this.setThumbBoxSize();
26735         
26736         this.bind();
26737         
26738         this.resize();
26739         
26740         this.fireEvent('initial', this);
26741     },
26742
26743     bind : function()
26744     {
26745         var _this = this;
26746         
26747         window.addEventListener("resize", function() { _this.resize(); } );
26748         
26749         this.bodyEl.on('click', this.beforeSelectFile, this);
26750         
26751         if(Roo.isTouch){
26752             this.bodyEl.on('touchstart', this.onTouchStart, this);
26753             this.bodyEl.on('touchmove', this.onTouchMove, this);
26754             this.bodyEl.on('touchend', this.onTouchEnd, this);
26755         }
26756         
26757         if(!Roo.isTouch){
26758             this.bodyEl.on('mousedown', this.onMouseDown, this);
26759             this.bodyEl.on('mousemove', this.onMouseMove, this);
26760             var mousewheel = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
26761             this.bodyEl.on(mousewheel, this.onMouseWheel, this);
26762             Roo.get(document).on('mouseup', this.onMouseUp, this);
26763         }
26764         
26765         this.selectorEl.on('change', this.onFileSelected, this);
26766     },
26767     
26768     reset : function()
26769     {    
26770         this.scale = 0;
26771         this.baseScale = 1;
26772         this.rotate = 0;
26773         this.baseRotate = 1;
26774         this.dragable = false;
26775         this.pinching = false;
26776         this.mouseX = 0;
26777         this.mouseY = 0;
26778         this.cropData = false;
26779         this.notifyEl.dom.innerHTML = this.emptyText;
26780         
26781         this.selectorEl.dom.value = '';
26782         
26783     },
26784     
26785     resize : function()
26786     {
26787         if(this.fireEvent('resize', this) != false){
26788             this.setThumbBoxPosition();
26789             this.setCanvasPosition();
26790         }
26791     },
26792     
26793     onFooterButtonClick : function(e, el, o, type)
26794     {
26795         switch (type) {
26796             case 'rotate-left' :
26797                 this.onRotateLeft(e);
26798                 break;
26799             case 'rotate-right' :
26800                 this.onRotateRight(e);
26801                 break;
26802             case 'picture' :
26803                 this.beforeSelectFile(e);
26804                 break;
26805             case 'trash' :
26806                 this.trash(e);
26807                 break;
26808             case 'crop' :
26809                 this.crop(e);
26810                 break;
26811             case 'download' :
26812                 this.download(e);
26813                 break;
26814             default :
26815                 break;
26816         }
26817         
26818         this.fireEvent('footerbuttonclick', this, type);
26819     },
26820     
26821     beforeSelectFile : function(e)
26822     {
26823         e.preventDefault();
26824         
26825         if(this.fireEvent('beforeselectfile', this) != false){
26826             this.selectorEl.dom.click();
26827         }
26828     },
26829     
26830     onFileSelected : function(e)
26831     {
26832         e.preventDefault();
26833         
26834         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
26835             return;
26836         }
26837         
26838         var file = this.selectorEl.dom.files[0];
26839         
26840         if(this.fireEvent('inspect', this, file) != false){
26841             this.prepare(file);
26842         }
26843         
26844     },
26845     
26846     trash : function(e)
26847     {
26848         this.fireEvent('trash', this);
26849     },
26850     
26851     download : function(e)
26852     {
26853         this.fireEvent('download', this);
26854     },
26855     
26856     loadCanvas : function(src)
26857     {   
26858         if(this.fireEvent('beforeloadcanvas', this, src) != false){
26859             
26860             this.reset();
26861             
26862             this.imageEl = document.createElement('img');
26863             
26864             var _this = this;
26865             
26866             this.imageEl.addEventListener("load", function(){ _this.onLoadCanvas(); });
26867             
26868             this.imageEl.src = src;
26869         }
26870     },
26871     
26872     onLoadCanvas : function()
26873     {   
26874         this.imageEl.OriginWidth = this.imageEl.naturalWidth || this.imageEl.width;
26875         this.imageEl.OriginHeight = this.imageEl.naturalHeight || this.imageEl.height;
26876         
26877         this.bodyEl.un('click', this.beforeSelectFile, this);
26878         
26879         this.notifyEl.hide();
26880         this.thumbEl.show();
26881         this.footerEl.show();
26882         
26883         this.baseRotateLevel();
26884         
26885         if(this.isDocument){
26886             this.setThumbBoxSize();
26887         }
26888         
26889         this.setThumbBoxPosition();
26890         
26891         this.baseScaleLevel();
26892         
26893         this.draw();
26894         
26895         this.resize();
26896         
26897         this.canvasLoaded = true;
26898         
26899         if(this.loadMask){
26900             this.maskEl.unmask();
26901         }
26902         
26903     },
26904     
26905     setCanvasPosition : function()
26906     {   
26907         if(!this.canvasEl){
26908             return;
26909         }
26910         
26911         var pw = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
26912         var ph = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
26913         
26914         this.previewEl.setLeft(pw);
26915         this.previewEl.setTop(ph);
26916         
26917     },
26918     
26919     onMouseDown : function(e)
26920     {   
26921         e.stopEvent();
26922         
26923         this.dragable = true;
26924         this.pinching = false;
26925         
26926         if(this.isDocument && (this.canvasEl.width < this.thumbEl.getWidth() || this.canvasEl.height < this.thumbEl.getHeight())){
26927             this.dragable = false;
26928             return;
26929         }
26930         
26931         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
26932         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
26933         
26934     },
26935     
26936     onMouseMove : function(e)
26937     {   
26938         e.stopEvent();
26939         
26940         if(!this.canvasLoaded){
26941             return;
26942         }
26943         
26944         if (!this.dragable){
26945             return;
26946         }
26947         
26948         var minX = Math.ceil(this.thumbEl.getLeft(true));
26949         var minY = Math.ceil(this.thumbEl.getTop(true));
26950         
26951         var maxX = Math.ceil(minX + this.thumbEl.getWidth() - this.canvasEl.width);
26952         var maxY = Math.ceil(minY + this.thumbEl.getHeight() - this.canvasEl.height);
26953         
26954         var x = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
26955         var y = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
26956         
26957         x = x - this.mouseX;
26958         y = y - this.mouseY;
26959         
26960         var bgX = Math.ceil(x + this.previewEl.getLeft(true));
26961         var bgY = Math.ceil(y + this.previewEl.getTop(true));
26962         
26963         bgX = (minX < bgX) ? minX : ((maxX > bgX) ? maxX : bgX);
26964         bgY = (minY < bgY) ? minY : ((maxY > bgY) ? maxY : bgY);
26965         
26966         this.previewEl.setLeft(bgX);
26967         this.previewEl.setTop(bgY);
26968         
26969         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
26970         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
26971     },
26972     
26973     onMouseUp : function(e)
26974     {   
26975         e.stopEvent();
26976         
26977         this.dragable = false;
26978     },
26979     
26980     onMouseWheel : function(e)
26981     {   
26982         e.stopEvent();
26983         
26984         this.startScale = this.scale;
26985         
26986         this.scale = (e.getWheelDelta() == 1) ? (this.scale + 1) : (this.scale - 1);
26987         
26988         if(!this.zoomable()){
26989             this.scale = this.startScale;
26990             return;
26991         }
26992         
26993         this.draw();
26994         
26995         return;
26996     },
26997     
26998     zoomable : function()
26999     {
27000         var minScale = this.thumbEl.getWidth() / this.minWidth;
27001         
27002         if(this.minWidth < this.minHeight){
27003             minScale = this.thumbEl.getHeight() / this.minHeight;
27004         }
27005         
27006         var width = Math.ceil(this.imageEl.OriginWidth * this.getScaleLevel() / minScale);
27007         var height = Math.ceil(this.imageEl.OriginHeight * this.getScaleLevel() / minScale);
27008         
27009         if(
27010                 this.isDocument &&
27011                 (this.rotate == 0 || this.rotate == 180) && 
27012                 (
27013                     width > this.imageEl.OriginWidth || 
27014                     height > this.imageEl.OriginHeight ||
27015                     (width < this.minWidth && height < this.minHeight)
27016                 )
27017         ){
27018             return false;
27019         }
27020         
27021         if(
27022                 this.isDocument &&
27023                 (this.rotate == 90 || this.rotate == 270) && 
27024                 (
27025                     width > this.imageEl.OriginWidth || 
27026                     height > this.imageEl.OriginHeight ||
27027                     (width < this.minHeight && height < this.minWidth)
27028                 )
27029         ){
27030             return false;
27031         }
27032         
27033         if(
27034                 !this.isDocument &&
27035                 (this.rotate == 0 || this.rotate == 180) && 
27036                 (
27037                     width < this.minWidth || 
27038                     width > this.imageEl.OriginWidth || 
27039                     height < this.minHeight || 
27040                     height > this.imageEl.OriginHeight
27041                 )
27042         ){
27043             return false;
27044         }
27045         
27046         if(
27047                 !this.isDocument &&
27048                 (this.rotate == 90 || this.rotate == 270) && 
27049                 (
27050                     width < this.minHeight || 
27051                     width > this.imageEl.OriginWidth || 
27052                     height < this.minWidth || 
27053                     height > this.imageEl.OriginHeight
27054                 )
27055         ){
27056             return false;
27057         }
27058         
27059         return true;
27060         
27061     },
27062     
27063     onRotateLeft : function(e)
27064     {   
27065         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
27066             
27067             var minScale = this.thumbEl.getWidth() / this.minWidth;
27068             
27069             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
27070             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
27071             
27072             this.startScale = this.scale;
27073             
27074             while (this.getScaleLevel() < minScale){
27075             
27076                 this.scale = this.scale + 1;
27077                 
27078                 if(!this.zoomable()){
27079                     break;
27080                 }
27081                 
27082                 if(
27083                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
27084                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
27085                 ){
27086                     continue;
27087                 }
27088                 
27089                 this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
27090
27091                 this.draw();
27092                 
27093                 return;
27094             }
27095             
27096             this.scale = this.startScale;
27097             
27098             this.onRotateFail();
27099             
27100             return false;
27101         }
27102         
27103         this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
27104
27105         if(this.isDocument){
27106             this.setThumbBoxSize();
27107             this.setThumbBoxPosition();
27108             this.setCanvasPosition();
27109         }
27110         
27111         this.draw();
27112         
27113         this.fireEvent('rotate', this, 'left');
27114         
27115     },
27116     
27117     onRotateRight : function(e)
27118     {
27119         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
27120             
27121             var minScale = this.thumbEl.getWidth() / this.minWidth;
27122         
27123             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
27124             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
27125             
27126             this.startScale = this.scale;
27127             
27128             while (this.getScaleLevel() < minScale){
27129             
27130                 this.scale = this.scale + 1;
27131                 
27132                 if(!this.zoomable()){
27133                     break;
27134                 }
27135                 
27136                 if(
27137                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
27138                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
27139                 ){
27140                     continue;
27141                 }
27142                 
27143                 this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
27144
27145                 this.draw();
27146                 
27147                 return;
27148             }
27149             
27150             this.scale = this.startScale;
27151             
27152             this.onRotateFail();
27153             
27154             return false;
27155         }
27156         
27157         this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
27158
27159         if(this.isDocument){
27160             this.setThumbBoxSize();
27161             this.setThumbBoxPosition();
27162             this.setCanvasPosition();
27163         }
27164         
27165         this.draw();
27166         
27167         this.fireEvent('rotate', this, 'right');
27168     },
27169     
27170     onRotateFail : function()
27171     {
27172         this.errorEl.show(true);
27173         
27174         var _this = this;
27175         
27176         (function() { _this.errorEl.hide(true); }).defer(this.errorTimeout);
27177     },
27178     
27179     draw : function()
27180     {
27181         this.previewEl.dom.innerHTML = '';
27182         
27183         var canvasEl = document.createElement("canvas");
27184         
27185         var contextEl = canvasEl.getContext("2d");
27186         
27187         canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
27188         canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
27189         var center = this.imageEl.OriginWidth / 2;
27190         
27191         if(this.imageEl.OriginWidth < this.imageEl.OriginHeight){
27192             canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
27193             canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
27194             center = this.imageEl.OriginHeight / 2;
27195         }
27196         
27197         contextEl.scale(this.getScaleLevel(), this.getScaleLevel());
27198         
27199         contextEl.translate(center, center);
27200         contextEl.rotate(this.rotate * Math.PI / 180);
27201
27202         contextEl.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
27203         
27204         this.canvasEl = document.createElement("canvas");
27205         
27206         this.contextEl = this.canvasEl.getContext("2d");
27207         
27208         switch (this.rotate) {
27209             case 0 :
27210                 
27211                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
27212                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
27213                 
27214                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
27215                 
27216                 break;
27217             case 90 : 
27218                 
27219                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
27220                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
27221                 
27222                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
27223                     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);
27224                     break;
27225                 }
27226                 
27227                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
27228                 
27229                 break;
27230             case 180 :
27231                 
27232                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
27233                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
27234                 
27235                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
27236                     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);
27237                     break;
27238                 }
27239                 
27240                 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);
27241                 
27242                 break;
27243             case 270 :
27244                 
27245                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
27246                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
27247         
27248                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
27249                     this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
27250                     break;
27251                 }
27252                 
27253                 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);
27254                 
27255                 break;
27256             default : 
27257                 break;
27258         }
27259         
27260         this.previewEl.appendChild(this.canvasEl);
27261         
27262         this.setCanvasPosition();
27263     },
27264     
27265     crop : function()
27266     {
27267         if(!this.canvasLoaded){
27268             return;
27269         }
27270         
27271         var imageCanvas = document.createElement("canvas");
27272         
27273         var imageContext = imageCanvas.getContext("2d");
27274         
27275         imageCanvas.width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
27276         imageCanvas.height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
27277         
27278         var center = imageCanvas.width / 2;
27279         
27280         imageContext.translate(center, center);
27281         
27282         imageContext.rotate(this.rotate * Math.PI / 180);
27283         
27284         imageContext.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
27285         
27286         var canvas = document.createElement("canvas");
27287         
27288         var context = canvas.getContext("2d");
27289                 
27290         canvas.width = this.minWidth;
27291         canvas.height = this.minHeight;
27292
27293         switch (this.rotate) {
27294             case 0 :
27295                 
27296                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
27297                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
27298                 
27299                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
27300                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
27301                 
27302                 var targetWidth = this.minWidth - 2 * x;
27303                 var targetHeight = this.minHeight - 2 * y;
27304                 
27305                 var scale = 1;
27306                 
27307                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
27308                     scale = targetWidth / width;
27309                 }
27310                 
27311                 if(x > 0 && y == 0){
27312                     scale = targetHeight / height;
27313                 }
27314                 
27315                 if(x > 0 && y > 0){
27316                     scale = targetWidth / width;
27317                     
27318                     if(width < height){
27319                         scale = targetHeight / height;
27320                     }
27321                 }
27322                 
27323                 context.scale(scale, scale);
27324                 
27325                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
27326                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
27327
27328                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
27329                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
27330
27331                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
27332                 
27333                 break;
27334             case 90 : 
27335                 
27336                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
27337                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
27338                 
27339                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
27340                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
27341                 
27342                 var targetWidth = this.minWidth - 2 * x;
27343                 var targetHeight = this.minHeight - 2 * y;
27344                 
27345                 var scale = 1;
27346                 
27347                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
27348                     scale = targetWidth / width;
27349                 }
27350                 
27351                 if(x > 0 && y == 0){
27352                     scale = targetHeight / height;
27353                 }
27354                 
27355                 if(x > 0 && y > 0){
27356                     scale = targetWidth / width;
27357                     
27358                     if(width < height){
27359                         scale = targetHeight / height;
27360                     }
27361                 }
27362                 
27363                 context.scale(scale, scale);
27364                 
27365                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
27366                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
27367
27368                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
27369                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
27370                 
27371                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
27372                 
27373                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
27374                 
27375                 break;
27376             case 180 :
27377                 
27378                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
27379                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
27380                 
27381                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
27382                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
27383                 
27384                 var targetWidth = this.minWidth - 2 * x;
27385                 var targetHeight = this.minHeight - 2 * y;
27386                 
27387                 var scale = 1;
27388                 
27389                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
27390                     scale = targetWidth / width;
27391                 }
27392                 
27393                 if(x > 0 && y == 0){
27394                     scale = targetHeight / height;
27395                 }
27396                 
27397                 if(x > 0 && y > 0){
27398                     scale = targetWidth / width;
27399                     
27400                     if(width < height){
27401                         scale = targetHeight / height;
27402                     }
27403                 }
27404                 
27405                 context.scale(scale, scale);
27406                 
27407                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
27408                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
27409
27410                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
27411                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
27412
27413                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
27414                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
27415                 
27416                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
27417                 
27418                 break;
27419             case 270 :
27420                 
27421                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
27422                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
27423                 
27424                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
27425                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
27426                 
27427                 var targetWidth = this.minWidth - 2 * x;
27428                 var targetHeight = this.minHeight - 2 * y;
27429                 
27430                 var scale = 1;
27431                 
27432                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
27433                     scale = targetWidth / width;
27434                 }
27435                 
27436                 if(x > 0 && y == 0){
27437                     scale = targetHeight / height;
27438                 }
27439                 
27440                 if(x > 0 && y > 0){
27441                     scale = targetWidth / width;
27442                     
27443                     if(width < height){
27444                         scale = targetHeight / height;
27445                     }
27446                 }
27447                 
27448                 context.scale(scale, scale);
27449                 
27450                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
27451                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
27452
27453                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
27454                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
27455                 
27456                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
27457                 
27458                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
27459                 
27460                 break;
27461             default : 
27462                 break;
27463         }
27464         
27465         this.cropData = canvas.toDataURL(this.cropType);
27466         
27467         if(this.fireEvent('crop', this, this.cropData) !== false){
27468             this.process(this.file, this.cropData);
27469         }
27470         
27471         return;
27472         
27473     },
27474     
27475     setThumbBoxSize : function()
27476     {
27477         var width, height;
27478         
27479         if(this.isDocument && typeof(this.imageEl) != 'undefined'){
27480             width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.max(this.minWidth, this.minHeight) : Math.min(this.minWidth, this.minHeight);
27481             height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.min(this.minWidth, this.minHeight) : Math.max(this.minWidth, this.minHeight);
27482             
27483             this.minWidth = width;
27484             this.minHeight = height;
27485             
27486             if(this.rotate == 90 || this.rotate == 270){
27487                 this.minWidth = height;
27488                 this.minHeight = width;
27489             }
27490         }
27491         
27492         height = 300;
27493         width = Math.ceil(this.minWidth * height / this.minHeight);
27494         
27495         if(this.minWidth > this.minHeight){
27496             width = 300;
27497             height = Math.ceil(this.minHeight * width / this.minWidth);
27498         }
27499         
27500         this.thumbEl.setStyle({
27501             width : width + 'px',
27502             height : height + 'px'
27503         });
27504
27505         return;
27506             
27507     },
27508     
27509     setThumbBoxPosition : function()
27510     {
27511         var x = Math.ceil((this.bodyEl.getWidth() - this.thumbEl.getWidth()) / 2 );
27512         var y = Math.ceil((this.bodyEl.getHeight() - this.thumbEl.getHeight()) / 2);
27513         
27514         this.thumbEl.setLeft(x);
27515         this.thumbEl.setTop(y);
27516         
27517     },
27518     
27519     baseRotateLevel : function()
27520     {
27521         this.baseRotate = 1;
27522         
27523         if(
27524                 typeof(this.exif) != 'undefined' &&
27525                 typeof(this.exif[Roo.bootstrap.UploadCropbox['tags']['Orientation']]) != 'undefined' &&
27526                 [1, 3, 6, 8].indexOf(this.exif[Roo.bootstrap.UploadCropbox['tags']['Orientation']]) != -1
27527         ){
27528             this.baseRotate = this.exif[Roo.bootstrap.UploadCropbox['tags']['Orientation']];
27529         }
27530         
27531         this.rotate = Roo.bootstrap.UploadCropbox['Orientation'][this.baseRotate];
27532         
27533     },
27534     
27535     baseScaleLevel : function()
27536     {
27537         var width, height;
27538         
27539         if(this.isDocument){
27540             
27541             if(this.baseRotate == 6 || this.baseRotate == 8){
27542             
27543                 height = this.thumbEl.getHeight();
27544                 this.baseScale = height / this.imageEl.OriginWidth;
27545
27546                 if(this.imageEl.OriginHeight * this.baseScale > this.thumbEl.getWidth()){
27547                     width = this.thumbEl.getWidth();
27548                     this.baseScale = width / this.imageEl.OriginHeight;
27549                 }
27550
27551                 return;
27552             }
27553
27554             height = this.thumbEl.getHeight();
27555             this.baseScale = height / this.imageEl.OriginHeight;
27556
27557             if(this.imageEl.OriginWidth * this.baseScale > this.thumbEl.getWidth()){
27558                 width = this.thumbEl.getWidth();
27559                 this.baseScale = width / this.imageEl.OriginWidth;
27560             }
27561
27562             return;
27563         }
27564         
27565         if(this.baseRotate == 6 || this.baseRotate == 8){
27566             
27567             width = this.thumbEl.getHeight();
27568             this.baseScale = width / this.imageEl.OriginHeight;
27569             
27570             if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getWidth()){
27571                 height = this.thumbEl.getWidth();
27572                 this.baseScale = height / this.imageEl.OriginHeight;
27573             }
27574             
27575             if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
27576                 height = this.thumbEl.getWidth();
27577                 this.baseScale = height / this.imageEl.OriginHeight;
27578                 
27579                 if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getHeight()){
27580                     width = this.thumbEl.getHeight();
27581                     this.baseScale = width / this.imageEl.OriginWidth;
27582                 }
27583             }
27584             
27585             return;
27586         }
27587         
27588         width = this.thumbEl.getWidth();
27589         this.baseScale = width / this.imageEl.OriginWidth;
27590         
27591         if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getHeight()){
27592             height = this.thumbEl.getHeight();
27593             this.baseScale = height / this.imageEl.OriginHeight;
27594         }
27595         
27596         if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
27597             
27598             height = this.thumbEl.getHeight();
27599             this.baseScale = height / this.imageEl.OriginHeight;
27600             
27601             if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getWidth()){
27602                 width = this.thumbEl.getWidth();
27603                 this.baseScale = width / this.imageEl.OriginWidth;
27604             }
27605             
27606         }
27607         
27608         return;
27609     },
27610     
27611     getScaleLevel : function()
27612     {
27613         return this.baseScale * Math.pow(1.1, this.scale);
27614     },
27615     
27616     onTouchStart : function(e)
27617     {
27618         if(!this.canvasLoaded){
27619             this.beforeSelectFile(e);
27620             return;
27621         }
27622         
27623         var touches = e.browserEvent.touches;
27624         
27625         if(!touches){
27626             return;
27627         }
27628         
27629         if(touches.length == 1){
27630             this.onMouseDown(e);
27631             return;
27632         }
27633         
27634         if(touches.length != 2){
27635             return;
27636         }
27637         
27638         var coords = [];
27639         
27640         for(var i = 0, finger; finger = touches[i]; i++){
27641             coords.push(finger.pageX, finger.pageY);
27642         }
27643         
27644         var x = Math.pow(coords[0] - coords[2], 2);
27645         var y = Math.pow(coords[1] - coords[3], 2);
27646         
27647         this.startDistance = Math.sqrt(x + y);
27648         
27649         this.startScale = this.scale;
27650         
27651         this.pinching = true;
27652         this.dragable = false;
27653         
27654     },
27655     
27656     onTouchMove : function(e)
27657     {
27658         if(!this.pinching && !this.dragable){
27659             return;
27660         }
27661         
27662         var touches = e.browserEvent.touches;
27663         
27664         if(!touches){
27665             return;
27666         }
27667         
27668         if(this.dragable){
27669             this.onMouseMove(e);
27670             return;
27671         }
27672         
27673         var coords = [];
27674         
27675         for(var i = 0, finger; finger = touches[i]; i++){
27676             coords.push(finger.pageX, finger.pageY);
27677         }
27678         
27679         var x = Math.pow(coords[0] - coords[2], 2);
27680         var y = Math.pow(coords[1] - coords[3], 2);
27681         
27682         this.endDistance = Math.sqrt(x + y);
27683         
27684         this.scale = this.startScale + Math.floor(Math.log(this.endDistance / this.startDistance) / Math.log(1.1));
27685         
27686         if(!this.zoomable()){
27687             this.scale = this.startScale;
27688             return;
27689         }
27690         
27691         this.draw();
27692         
27693     },
27694     
27695     onTouchEnd : function(e)
27696     {
27697         this.pinching = false;
27698         this.dragable = false;
27699         
27700     },
27701     
27702     process : function(file, crop)
27703     {
27704         if(this.loadMask){
27705             this.maskEl.mask(this.loadingText);
27706         }
27707         
27708         this.xhr = new XMLHttpRequest();
27709         
27710         file.xhr = this.xhr;
27711
27712         this.xhr.open(this.method, this.url, true);
27713         
27714         var headers = {
27715             "Accept": "application/json",
27716             "Cache-Control": "no-cache",
27717             "X-Requested-With": "XMLHttpRequest"
27718         };
27719         
27720         for (var headerName in headers) {
27721             var headerValue = headers[headerName];
27722             if (headerValue) {
27723                 this.xhr.setRequestHeader(headerName, headerValue);
27724             }
27725         }
27726         
27727         var _this = this;
27728         
27729         this.xhr.onload = function()
27730         {
27731             _this.xhrOnLoad(_this.xhr);
27732         }
27733         
27734         this.xhr.onerror = function()
27735         {
27736             _this.xhrOnError(_this.xhr);
27737         }
27738         
27739         var formData = new FormData();
27740
27741         formData.append('returnHTML', 'NO');
27742         
27743         if(crop){
27744             formData.append('crop', crop);
27745         }
27746         
27747         if(typeof(file) != 'undefined' && (typeof(file.id) == 'undefined' || file.id * 1 < 1)){
27748             formData.append(this.paramName, file, file.name);
27749         }
27750         
27751         if(typeof(file.filename) != 'undefined'){
27752             formData.append('filename', file.filename);
27753         }
27754         
27755         if(typeof(file.mimetype) != 'undefined'){
27756             formData.append('mimetype', file.mimetype);
27757         }
27758         
27759         if(this.fireEvent('arrange', this, formData) != false){
27760             this.xhr.send(formData);
27761         };
27762     },
27763     
27764     xhrOnLoad : function(xhr)
27765     {
27766         if(this.loadMask){
27767             this.maskEl.unmask();
27768         }
27769         
27770         if (xhr.readyState !== 4) {
27771             this.fireEvent('exception', this, xhr);
27772             return;
27773         }
27774
27775         var response = Roo.decode(xhr.responseText);
27776         
27777         if(!response.success){
27778             this.fireEvent('exception', this, xhr);
27779             return;
27780         }
27781         
27782         var response = Roo.decode(xhr.responseText);
27783         
27784         this.fireEvent('upload', this, response);
27785         
27786     },
27787     
27788     xhrOnError : function()
27789     {
27790         if(this.loadMask){
27791             this.maskEl.unmask();
27792         }
27793         
27794         Roo.log('xhr on error');
27795         
27796         var response = Roo.decode(xhr.responseText);
27797           
27798         Roo.log(response);
27799         
27800     },
27801     
27802     prepare : function(file)
27803     {   
27804         if(this.loadMask){
27805             this.maskEl.mask(this.loadingText);
27806         }
27807         
27808         this.file = false;
27809         this.exif = {};
27810         
27811         if(typeof(file) === 'string'){
27812             this.loadCanvas(file);
27813             return;
27814         }
27815         
27816         if(!file || !this.urlAPI){
27817             return;
27818         }
27819         
27820         this.file = file;
27821         this.cropType = file.type;
27822         
27823         var _this = this;
27824         
27825         if(this.fireEvent('prepare', this, this.file) != false){
27826             
27827             var reader = new FileReader();
27828             
27829             reader.onload = function (e) {
27830                 if (e.target.error) {
27831                     Roo.log(e.target.error);
27832                     return;
27833                 }
27834                 
27835                 var buffer = e.target.result,
27836                     dataView = new DataView(buffer),
27837                     offset = 2,
27838                     maxOffset = dataView.byteLength - 4,
27839                     markerBytes,
27840                     markerLength;
27841                 
27842                 if (dataView.getUint16(0) === 0xffd8) {
27843                     while (offset < maxOffset) {
27844                         markerBytes = dataView.getUint16(offset);
27845                         
27846                         if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) {
27847                             markerLength = dataView.getUint16(offset + 2) + 2;
27848                             if (offset + markerLength > dataView.byteLength) {
27849                                 Roo.log('Invalid meta data: Invalid segment size.');
27850                                 break;
27851                             }
27852                             
27853                             if(markerBytes == 0xffe1){
27854                                 _this.parseExifData(
27855                                     dataView,
27856                                     offset,
27857                                     markerLength
27858                                 );
27859                             }
27860                             
27861                             offset += markerLength;
27862                             
27863                             continue;
27864                         }
27865                         
27866                         break;
27867                     }
27868                     
27869                 }
27870                 
27871                 var url = _this.urlAPI.createObjectURL(_this.file);
27872                 
27873                 _this.loadCanvas(url);
27874                 
27875                 return;
27876             }
27877             
27878             reader.readAsArrayBuffer(this.file);
27879             
27880         }
27881         
27882     },
27883     
27884     parseExifData : function(dataView, offset, length)
27885     {
27886         var tiffOffset = offset + 10,
27887             littleEndian,
27888             dirOffset;
27889     
27890         if (dataView.getUint32(offset + 4) !== 0x45786966) {
27891             // No Exif data, might be XMP data instead
27892             return;
27893         }
27894         
27895         // Check for the ASCII code for "Exif" (0x45786966):
27896         if (dataView.getUint32(offset + 4) !== 0x45786966) {
27897             // No Exif data, might be XMP data instead
27898             return;
27899         }
27900         if (tiffOffset + 8 > dataView.byteLength) {
27901             Roo.log('Invalid Exif data: Invalid segment size.');
27902             return;
27903         }
27904         // Check for the two null bytes:
27905         if (dataView.getUint16(offset + 8) !== 0x0000) {
27906             Roo.log('Invalid Exif data: Missing byte alignment offset.');
27907             return;
27908         }
27909         // Check the byte alignment:
27910         switch (dataView.getUint16(tiffOffset)) {
27911         case 0x4949:
27912             littleEndian = true;
27913             break;
27914         case 0x4D4D:
27915             littleEndian = false;
27916             break;
27917         default:
27918             Roo.log('Invalid Exif data: Invalid byte alignment marker.');
27919             return;
27920         }
27921         // Check for the TIFF tag marker (0x002A):
27922         if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
27923             Roo.log('Invalid Exif data: Missing TIFF marker.');
27924             return;
27925         }
27926         // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
27927         dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
27928         
27929         this.parseExifTags(
27930             dataView,
27931             tiffOffset,
27932             tiffOffset + dirOffset,
27933             littleEndian
27934         );
27935     },
27936     
27937     parseExifTags : function(dataView, tiffOffset, dirOffset, littleEndian)
27938     {
27939         var tagsNumber,
27940             dirEndOffset,
27941             i;
27942         if (dirOffset + 6 > dataView.byteLength) {
27943             Roo.log('Invalid Exif data: Invalid directory offset.');
27944             return;
27945         }
27946         tagsNumber = dataView.getUint16(dirOffset, littleEndian);
27947         dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
27948         if (dirEndOffset + 4 > dataView.byteLength) {
27949             Roo.log('Invalid Exif data: Invalid directory size.');
27950             return;
27951         }
27952         for (i = 0; i < tagsNumber; i += 1) {
27953             this.parseExifTag(
27954                 dataView,
27955                 tiffOffset,
27956                 dirOffset + 2 + 12 * i, // tag offset
27957                 littleEndian
27958             );
27959         }
27960         // Return the offset to the next directory:
27961         return dataView.getUint32(dirEndOffset, littleEndian);
27962     },
27963     
27964     parseExifTag : function (dataView, tiffOffset, offset, littleEndian) 
27965     {
27966         var tag = dataView.getUint16(offset, littleEndian);
27967         
27968         this.exif[tag] = this.getExifValue(
27969             dataView,
27970             tiffOffset,
27971             offset,
27972             dataView.getUint16(offset + 2, littleEndian), // tag type
27973             dataView.getUint32(offset + 4, littleEndian), // tag length
27974             littleEndian
27975         );
27976     },
27977     
27978     getExifValue : function (dataView, tiffOffset, offset, type, length, littleEndian)
27979     {
27980         var tagType = Roo.bootstrap.UploadCropbox.exifTagTypes[type],
27981             tagSize,
27982             dataOffset,
27983             values,
27984             i,
27985             str,
27986             c;
27987     
27988         if (!tagType) {
27989             Roo.log('Invalid Exif data: Invalid tag type.');
27990             return;
27991         }
27992         
27993         tagSize = tagType.size * length;
27994         // Determine if the value is contained in the dataOffset bytes,
27995         // or if the value at the dataOffset is a pointer to the actual data:
27996         dataOffset = tagSize > 4 ?
27997                 tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8);
27998         if (dataOffset + tagSize > dataView.byteLength) {
27999             Roo.log('Invalid Exif data: Invalid data offset.');
28000             return;
28001         }
28002         if (length === 1) {
28003             return tagType.getValue(dataView, dataOffset, littleEndian);
28004         }
28005         values = [];
28006         for (i = 0; i < length; i += 1) {
28007             values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian);
28008         }
28009         
28010         if (tagType.ascii) {
28011             str = '';
28012             // Concatenate the chars:
28013             for (i = 0; i < values.length; i += 1) {
28014                 c = values[i];
28015                 // Ignore the terminating NULL byte(s):
28016                 if (c === '\u0000') {
28017                     break;
28018                 }
28019                 str += c;
28020             }
28021             return str;
28022         }
28023         return values;
28024     }
28025     
28026 });
28027
28028 Roo.apply(Roo.bootstrap.UploadCropbox, {
28029     tags : {
28030         'Orientation': 0x0112
28031     },
28032     
28033     Orientation: {
28034             1: 0, //'top-left',
28035 //            2: 'top-right',
28036             3: 180, //'bottom-right',
28037 //            4: 'bottom-left',
28038 //            5: 'left-top',
28039             6: 90, //'right-top',
28040 //            7: 'right-bottom',
28041             8: 270 //'left-bottom'
28042     },
28043     
28044     exifTagTypes : {
28045         // byte, 8-bit unsigned int:
28046         1: {
28047             getValue: function (dataView, dataOffset) {
28048                 return dataView.getUint8(dataOffset);
28049             },
28050             size: 1
28051         },
28052         // ascii, 8-bit byte:
28053         2: {
28054             getValue: function (dataView, dataOffset) {
28055                 return String.fromCharCode(dataView.getUint8(dataOffset));
28056             },
28057             size: 1,
28058             ascii: true
28059         },
28060         // short, 16 bit int:
28061         3: {
28062             getValue: function (dataView, dataOffset, littleEndian) {
28063                 return dataView.getUint16(dataOffset, littleEndian);
28064             },
28065             size: 2
28066         },
28067         // long, 32 bit int:
28068         4: {
28069             getValue: function (dataView, dataOffset, littleEndian) {
28070                 return dataView.getUint32(dataOffset, littleEndian);
28071             },
28072             size: 4
28073         },
28074         // rational = two long values, first is numerator, second is denominator:
28075         5: {
28076             getValue: function (dataView, dataOffset, littleEndian) {
28077                 return dataView.getUint32(dataOffset, littleEndian) /
28078                     dataView.getUint32(dataOffset + 4, littleEndian);
28079             },
28080             size: 8
28081         },
28082         // slong, 32 bit signed int:
28083         9: {
28084             getValue: function (dataView, dataOffset, littleEndian) {
28085                 return dataView.getInt32(dataOffset, littleEndian);
28086             },
28087             size: 4
28088         },
28089         // srational, two slongs, first is numerator, second is denominator:
28090         10: {
28091             getValue: function (dataView, dataOffset, littleEndian) {
28092                 return dataView.getInt32(dataOffset, littleEndian) /
28093                     dataView.getInt32(dataOffset + 4, littleEndian);
28094             },
28095             size: 8
28096         }
28097     },
28098     
28099     footer : {
28100         STANDARD : [
28101             {
28102                 tag : 'div',
28103                 cls : 'btn-group roo-upload-cropbox-rotate-left',
28104                 action : 'rotate-left',
28105                 cn : [
28106                     {
28107                         tag : 'button',
28108                         cls : 'btn btn-default',
28109                         html : '<i class="fa fa-undo"></i>'
28110                     }
28111                 ]
28112             },
28113             {
28114                 tag : 'div',
28115                 cls : 'btn-group roo-upload-cropbox-picture',
28116                 action : 'picture',
28117                 cn : [
28118                     {
28119                         tag : 'button',
28120                         cls : 'btn btn-default',
28121                         html : '<i class="fa fa-picture-o"></i>'
28122                     }
28123                 ]
28124             },
28125             {
28126                 tag : 'div',
28127                 cls : 'btn-group roo-upload-cropbox-rotate-right',
28128                 action : 'rotate-right',
28129                 cn : [
28130                     {
28131                         tag : 'button',
28132                         cls : 'btn btn-default',
28133                         html : '<i class="fa fa-repeat"></i>'
28134                     }
28135                 ]
28136             }
28137         ],
28138         DOCUMENT : [
28139             {
28140                 tag : 'div',
28141                 cls : 'btn-group roo-upload-cropbox-rotate-left',
28142                 action : 'rotate-left',
28143                 cn : [
28144                     {
28145                         tag : 'button',
28146                         cls : 'btn btn-default',
28147                         html : '<i class="fa fa-undo"></i>'
28148                     }
28149                 ]
28150             },
28151             {
28152                 tag : 'div',
28153                 cls : 'btn-group roo-upload-cropbox-download',
28154                 action : 'download',
28155                 cn : [
28156                     {
28157                         tag : 'button',
28158                         cls : 'btn btn-default',
28159                         html : '<i class="fa fa-download"></i>'
28160                     }
28161                 ]
28162             },
28163             {
28164                 tag : 'div',
28165                 cls : 'btn-group roo-upload-cropbox-crop',
28166                 action : 'crop',
28167                 cn : [
28168                     {
28169                         tag : 'button',
28170                         cls : 'btn btn-default',
28171                         html : '<i class="fa fa-crop"></i>'
28172                     }
28173                 ]
28174             },
28175             {
28176                 tag : 'div',
28177                 cls : 'btn-group roo-upload-cropbox-trash',
28178                 action : 'trash',
28179                 cn : [
28180                     {
28181                         tag : 'button',
28182                         cls : 'btn btn-default',
28183                         html : '<i class="fa fa-trash"></i>'
28184                     }
28185                 ]
28186             },
28187             {
28188                 tag : 'div',
28189                 cls : 'btn-group roo-upload-cropbox-rotate-right',
28190                 action : 'rotate-right',
28191                 cn : [
28192                     {
28193                         tag : 'button',
28194                         cls : 'btn btn-default',
28195                         html : '<i class="fa fa-repeat"></i>'
28196                     }
28197                 ]
28198             }
28199         ],
28200         ROTATOR : [
28201             {
28202                 tag : 'div',
28203                 cls : 'btn-group roo-upload-cropbox-rotate-left',
28204                 action : 'rotate-left',
28205                 cn : [
28206                     {
28207                         tag : 'button',
28208                         cls : 'btn btn-default',
28209                         html : '<i class="fa fa-undo"></i>'
28210                     }
28211                 ]
28212             },
28213             {
28214                 tag : 'div',
28215                 cls : 'btn-group roo-upload-cropbox-rotate-right',
28216                 action : 'rotate-right',
28217                 cn : [
28218                     {
28219                         tag : 'button',
28220                         cls : 'btn btn-default',
28221                         html : '<i class="fa fa-repeat"></i>'
28222                     }
28223                 ]
28224             }
28225         ]
28226     }
28227 });
28228
28229 /*
28230 * Licence: LGPL
28231 */
28232
28233 /**
28234  * @class Roo.bootstrap.DocumentManager
28235  * @extends Roo.bootstrap.Component
28236  * Bootstrap DocumentManager class
28237  * @cfg {String} paramName default 'imageUpload'
28238  * @cfg {String} toolTipName default 'filename'
28239  * @cfg {String} method default POST
28240  * @cfg {String} url action url
28241  * @cfg {Number} boxes number of boxes, 0 is no limit.. default 0
28242  * @cfg {Boolean} multiple multiple upload default true
28243  * @cfg {Number} thumbSize default 300
28244  * @cfg {String} fieldLabel
28245  * @cfg {Number} labelWidth default 4
28246  * @cfg {String} labelAlign (left|top) default left
28247  * @cfg {Boolean} editable (true|false) allow edit when upload a image default true
28248 * @cfg {Number} labellg set the width of label (1-12)
28249  * @cfg {Number} labelmd set the width of label (1-12)
28250  * @cfg {Number} labelsm set the width of label (1-12)
28251  * @cfg {Number} labelxs set the width of label (1-12)
28252  * 
28253  * @constructor
28254  * Create a new DocumentManager
28255  * @param {Object} config The config object
28256  */
28257
28258 Roo.bootstrap.DocumentManager = function(config){
28259     Roo.bootstrap.DocumentManager.superclass.constructor.call(this, config);
28260     
28261     this.files = [];
28262     this.delegates = [];
28263     
28264     this.addEvents({
28265         /**
28266          * @event initial
28267          * Fire when initial the DocumentManager
28268          * @param {Roo.bootstrap.DocumentManager} this
28269          */
28270         "initial" : true,
28271         /**
28272          * @event inspect
28273          * inspect selected file
28274          * @param {Roo.bootstrap.DocumentManager} this
28275          * @param {File} file
28276          */
28277         "inspect" : true,
28278         /**
28279          * @event exception
28280          * Fire when xhr load exception
28281          * @param {Roo.bootstrap.DocumentManager} this
28282          * @param {XMLHttpRequest} xhr
28283          */
28284         "exception" : true,
28285         /**
28286          * @event afterupload
28287          * Fire when xhr load exception
28288          * @param {Roo.bootstrap.DocumentManager} this
28289          * @param {XMLHttpRequest} xhr
28290          */
28291         "afterupload" : true,
28292         /**
28293          * @event prepare
28294          * prepare the form data
28295          * @param {Roo.bootstrap.DocumentManager} this
28296          * @param {Object} formData
28297          */
28298         "prepare" : true,
28299         /**
28300          * @event remove
28301          * Fire when remove the file
28302          * @param {Roo.bootstrap.DocumentManager} this
28303          * @param {Object} file
28304          */
28305         "remove" : true,
28306         /**
28307          * @event refresh
28308          * Fire after refresh the file
28309          * @param {Roo.bootstrap.DocumentManager} this
28310          */
28311         "refresh" : true,
28312         /**
28313          * @event click
28314          * Fire after click the image
28315          * @param {Roo.bootstrap.DocumentManager} this
28316          * @param {Object} file
28317          */
28318         "click" : true,
28319         /**
28320          * @event edit
28321          * Fire when upload a image and editable set to true
28322          * @param {Roo.bootstrap.DocumentManager} this
28323          * @param {Object} file
28324          */
28325         "edit" : true,
28326         /**
28327          * @event beforeselectfile
28328          * Fire before select file
28329          * @param {Roo.bootstrap.DocumentManager} this
28330          */
28331         "beforeselectfile" : true,
28332         /**
28333          * @event process
28334          * Fire before process file
28335          * @param {Roo.bootstrap.DocumentManager} this
28336          * @param {Object} file
28337          */
28338         "process" : true
28339         
28340     });
28341 };
28342
28343 Roo.extend(Roo.bootstrap.DocumentManager, Roo.bootstrap.Component,  {
28344     
28345     boxes : 0,
28346     inputName : '',
28347     thumbSize : 300,
28348     multiple : true,
28349     files : false,
28350     method : 'POST',
28351     url : '',
28352     paramName : 'imageUpload',
28353     toolTipName : 'filename',
28354     fieldLabel : '',
28355     labelWidth : 4,
28356     labelAlign : 'left',
28357     editable : true,
28358     delegates : false,
28359     xhr : false, 
28360     
28361     labellg : 0,
28362     labelmd : 0,
28363     labelsm : 0,
28364     labelxs : 0,
28365     
28366     getAutoCreate : function()
28367     {   
28368         var managerWidget = {
28369             tag : 'div',
28370             cls : 'roo-document-manager',
28371             cn : [
28372                 {
28373                     tag : 'input',
28374                     cls : 'roo-document-manager-selector',
28375                     type : 'file'
28376                 },
28377                 {
28378                     tag : 'div',
28379                     cls : 'roo-document-manager-uploader',
28380                     cn : [
28381                         {
28382                             tag : 'div',
28383                             cls : 'roo-document-manager-upload-btn',
28384                             html : '<i class="fa fa-plus"></i>'
28385                         }
28386                     ]
28387                     
28388                 }
28389             ]
28390         };
28391         
28392         var content = [
28393             {
28394                 tag : 'div',
28395                 cls : 'column col-md-12',
28396                 cn : managerWidget
28397             }
28398         ];
28399         
28400         if(this.fieldLabel.length){
28401             
28402             content = [
28403                 {
28404                     tag : 'div',
28405                     cls : 'column col-md-12',
28406                     html : this.fieldLabel
28407                 },
28408                 {
28409                     tag : 'div',
28410                     cls : 'column col-md-12',
28411                     cn : managerWidget
28412                 }
28413             ];
28414
28415             if(this.labelAlign == 'left'){
28416                 content = [
28417                     {
28418                         tag : 'div',
28419                         cls : 'column',
28420                         html : this.fieldLabel
28421                     },
28422                     {
28423                         tag : 'div',
28424                         cls : 'column',
28425                         cn : managerWidget
28426                     }
28427                 ];
28428                 
28429                 if(this.labelWidth > 12){
28430                     content[0].style = "width: " + this.labelWidth + 'px';
28431                 }
28432
28433                 if(this.labelWidth < 13 && this.labelmd == 0){
28434                     this.labelmd = this.labelWidth;
28435                 }
28436
28437                 if(this.labellg > 0){
28438                     content[0].cls += ' col-lg-' + this.labellg;
28439                     content[1].cls += ' col-lg-' + (12 - this.labellg);
28440                 }
28441
28442                 if(this.labelmd > 0){
28443                     content[0].cls += ' col-md-' + this.labelmd;
28444                     content[1].cls += ' col-md-' + (12 - this.labelmd);
28445                 }
28446
28447                 if(this.labelsm > 0){
28448                     content[0].cls += ' col-sm-' + this.labelsm;
28449                     content[1].cls += ' col-sm-' + (12 - this.labelsm);
28450                 }
28451
28452                 if(this.labelxs > 0){
28453                     content[0].cls += ' col-xs-' + this.labelxs;
28454                     content[1].cls += ' col-xs-' + (12 - this.labelxs);
28455                 }
28456                 
28457             }
28458         }
28459         
28460         var cfg = {
28461             tag : 'div',
28462             cls : 'row clearfix',
28463             cn : content
28464         };
28465         
28466         return cfg;
28467         
28468     },
28469     
28470     initEvents : function()
28471     {
28472         this.managerEl = this.el.select('.roo-document-manager', true).first();
28473         this.managerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
28474         
28475         this.selectorEl = this.el.select('.roo-document-manager-selector', true).first();
28476         this.selectorEl.hide();
28477         
28478         if(this.multiple){
28479             this.selectorEl.attr('multiple', 'multiple');
28480         }
28481         
28482         this.selectorEl.on('change', this.onFileSelected, this);
28483         
28484         this.uploader = this.el.select('.roo-document-manager-uploader', true).first();
28485         this.uploader.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
28486         
28487         this.uploader.on('click', this.onUploaderClick, this);
28488         
28489         this.renderProgressDialog();
28490         
28491         var _this = this;
28492         
28493         window.addEventListener("resize", function() { _this.refresh(); } );
28494         
28495         this.fireEvent('initial', this);
28496     },
28497     
28498     renderProgressDialog : function()
28499     {
28500         var _this = this;
28501         
28502         this.progressDialog = new Roo.bootstrap.Modal({
28503             cls : 'roo-document-manager-progress-dialog',
28504             allow_close : false,
28505             title : '',
28506             buttons : [
28507                 {
28508                     name  :'cancel',
28509                     weight : 'danger',
28510                     html : 'Cancel'
28511                 }
28512             ], 
28513             listeners : { 
28514                 btnclick : function() {
28515                     _this.uploadCancel();
28516                     this.hide();
28517                 }
28518             }
28519         });
28520          
28521         this.progressDialog.render(Roo.get(document.body));
28522          
28523         this.progress = new Roo.bootstrap.Progress({
28524             cls : 'roo-document-manager-progress',
28525             active : true,
28526             striped : true
28527         });
28528         
28529         this.progress.render(this.progressDialog.getChildContainer());
28530         
28531         this.progressBar = new Roo.bootstrap.ProgressBar({
28532             cls : 'roo-document-manager-progress-bar',
28533             aria_valuenow : 0,
28534             aria_valuemin : 0,
28535             aria_valuemax : 12,
28536             panel : 'success'
28537         });
28538         
28539         this.progressBar.render(this.progress.getChildContainer());
28540     },
28541     
28542     onUploaderClick : function(e)
28543     {
28544         e.preventDefault();
28545      
28546         if(this.fireEvent('beforeselectfile', this) != false){
28547             this.selectorEl.dom.click();
28548         }
28549         
28550     },
28551     
28552     onFileSelected : function(e)
28553     {
28554         e.preventDefault();
28555         
28556         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
28557             return;
28558         }
28559         
28560         Roo.each(this.selectorEl.dom.files, function(file){
28561             if(this.fireEvent('inspect', this, file) != false){
28562                 this.files.push(file);
28563             }
28564         }, this);
28565         
28566         this.queue();
28567         
28568     },
28569     
28570     queue : function()
28571     {
28572         this.selectorEl.dom.value = '';
28573         
28574         if(!this.files.length){
28575             return;
28576         }
28577         
28578         if(this.boxes > 0 && this.files.length > this.boxes){
28579             this.files = this.files.slice(0, this.boxes);
28580         }
28581         
28582         this.uploader.show();
28583         
28584         if(this.boxes > 0 && this.files.length > this.boxes - 1){
28585             this.uploader.hide();
28586         }
28587         
28588         var _this = this;
28589         
28590         var files = [];
28591         
28592         var docs = [];
28593         
28594         Roo.each(this.files, function(file){
28595             
28596             if(typeof(file.id) != 'undefined' && file.id * 1 > 0){
28597                 var f = this.renderPreview(file);
28598                 files.push(f);
28599                 return;
28600             }
28601             
28602             if(file.type.indexOf('image') != -1){
28603                 this.delegates.push(
28604                     (function(){
28605                         _this.process(file);
28606                     }).createDelegate(this)
28607                 );
28608         
28609                 return;
28610             }
28611             
28612             docs.push(
28613                 (function(){
28614                     _this.process(file);
28615                 }).createDelegate(this)
28616             );
28617             
28618         }, this);
28619         
28620         this.files = files;
28621         
28622         this.delegates = this.delegates.concat(docs);
28623         
28624         if(!this.delegates.length){
28625             this.refresh();
28626             return;
28627         }
28628         
28629         this.progressBar.aria_valuemax = this.delegates.length;
28630         
28631         this.arrange();
28632         
28633         return;
28634     },
28635     
28636     arrange : function()
28637     {
28638         if(!this.delegates.length){
28639             this.progressDialog.hide();
28640             this.refresh();
28641             return;
28642         }
28643         
28644         var delegate = this.delegates.shift();
28645         
28646         this.progressDialog.show();
28647         
28648         this.progressDialog.setTitle((this.progressBar.aria_valuemax - this.delegates.length) + ' / ' + this.progressBar.aria_valuemax);
28649         
28650         this.progressBar.update(this.progressBar.aria_valuemax - this.delegates.length);
28651         
28652         delegate();
28653     },
28654     
28655     refresh : function()
28656     {
28657         this.uploader.show();
28658         
28659         if(this.boxes > 0 && this.files.length > this.boxes - 1){
28660             this.uploader.hide();
28661         }
28662         
28663         Roo.isTouch ? this.closable(false) : this.closable(true);
28664         
28665         this.fireEvent('refresh', this);
28666     },
28667     
28668     onRemove : function(e, el, o)
28669     {
28670         e.preventDefault();
28671         
28672         this.fireEvent('remove', this, o);
28673         
28674     },
28675     
28676     remove : function(o)
28677     {
28678         var files = [];
28679         
28680         Roo.each(this.files, function(file){
28681             if(typeof(file.id) == 'undefined' || file.id * 1 < 1 || file.id != o.id){
28682                 files.push(file);
28683                 return;
28684             }
28685
28686             o.target.remove();
28687
28688         }, this);
28689         
28690         this.files = files;
28691         
28692         this.refresh();
28693     },
28694     
28695     clear : function()
28696     {
28697         Roo.each(this.files, function(file){
28698             if(!file.target){
28699                 return;
28700             }
28701             
28702             file.target.remove();
28703
28704         }, this);
28705         
28706         this.files = [];
28707         
28708         this.refresh();
28709     },
28710     
28711     onClick : function(e, el, o)
28712     {
28713         e.preventDefault();
28714         
28715         this.fireEvent('click', this, o);
28716         
28717     },
28718     
28719     closable : function(closable)
28720     {
28721         Roo.each(this.managerEl.select('.roo-document-manager-preview > button.close', true).elements, function(el){
28722             
28723             el.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
28724             
28725             if(closable){
28726                 el.show();
28727                 return;
28728             }
28729             
28730             el.hide();
28731             
28732         }, this);
28733     },
28734     
28735     xhrOnLoad : function(xhr)
28736     {
28737         Roo.each(this.managerEl.select('.roo-document-manager-loading', true).elements, function(el){
28738             el.remove();
28739         }, this);
28740         
28741         if (xhr.readyState !== 4) {
28742             this.arrange();
28743             this.fireEvent('exception', this, xhr);
28744             return;
28745         }
28746
28747         var response = Roo.decode(xhr.responseText);
28748         
28749         if(!response.success){
28750             this.arrange();
28751             this.fireEvent('exception', this, xhr);
28752             return;
28753         }
28754         
28755         var file = this.renderPreview(response.data);
28756         
28757         this.files.push(file);
28758         
28759         this.arrange();
28760         
28761         this.fireEvent('afterupload', this, xhr);
28762         
28763     },
28764     
28765     xhrOnError : function(xhr)
28766     {
28767         Roo.log('xhr on error');
28768         
28769         var response = Roo.decode(xhr.responseText);
28770           
28771         Roo.log(response);
28772         
28773         this.arrange();
28774     },
28775     
28776     process : function(file)
28777     {
28778         if(this.fireEvent('process', this, file) !== false){
28779             if(this.editable && file.type.indexOf('image') != -1){
28780                 this.fireEvent('edit', this, file);
28781                 return;
28782             }
28783
28784             this.uploadStart(file, false);
28785
28786             return;
28787         }
28788         
28789     },
28790     
28791     uploadStart : function(file, crop)
28792     {
28793         this.xhr = new XMLHttpRequest();
28794         
28795         if(typeof(file.id) != 'undefined' && file.id * 1 > 0){
28796             this.arrange();
28797             return;
28798         }
28799         
28800         file.xhr = this.xhr;
28801             
28802         this.managerEl.createChild({
28803             tag : 'div',
28804             cls : 'roo-document-manager-loading',
28805             cn : [
28806                 {
28807                     tag : 'div',
28808                     tooltip : file.name,
28809                     cls : 'roo-document-manager-thumb',
28810                     html : '<i class="fa fa-circle-o-notch fa-spin"></i>'
28811                 }
28812             ]
28813
28814         });
28815
28816         this.xhr.open(this.method, this.url, true);
28817         
28818         var headers = {
28819             "Accept": "application/json",
28820             "Cache-Control": "no-cache",
28821             "X-Requested-With": "XMLHttpRequest"
28822         };
28823         
28824         for (var headerName in headers) {
28825             var headerValue = headers[headerName];
28826             if (headerValue) {
28827                 this.xhr.setRequestHeader(headerName, headerValue);
28828             }
28829         }
28830         
28831         var _this = this;
28832         
28833         this.xhr.onload = function()
28834         {
28835             _this.xhrOnLoad(_this.xhr);
28836         }
28837         
28838         this.xhr.onerror = function()
28839         {
28840             _this.xhrOnError(_this.xhr);
28841         }
28842         
28843         var formData = new FormData();
28844
28845         formData.append('returnHTML', 'NO');
28846         
28847         if(crop){
28848             formData.append('crop', crop);
28849         }
28850         
28851         formData.append(this.paramName, file, file.name);
28852         
28853         var options = {
28854             file : file, 
28855             manually : false
28856         };
28857         
28858         if(this.fireEvent('prepare', this, formData, options) != false){
28859             
28860             if(options.manually){
28861                 return;
28862             }
28863             
28864             this.xhr.send(formData);
28865             return;
28866         };
28867         
28868         this.uploadCancel();
28869     },
28870     
28871     uploadCancel : function()
28872     {
28873         if (this.xhr) {
28874             this.xhr.abort();
28875         }
28876         
28877         this.delegates = [];
28878         
28879         Roo.each(this.managerEl.select('.roo-document-manager-loading', true).elements, function(el){
28880             el.remove();
28881         }, this);
28882         
28883         this.arrange();
28884     },
28885     
28886     renderPreview : function(file)
28887     {
28888         if(typeof(file.target) != 'undefined' && file.target){
28889             return file;
28890         }
28891         
28892         var img_src = encodeURI(baseURL +'/Images/Thumb/' + this.thumbSize + '/' + file.id + '/' + file.filename);
28893         
28894         var previewEl = this.managerEl.createChild({
28895             tag : 'div',
28896             cls : 'roo-document-manager-preview',
28897             cn : [
28898                 {
28899                     tag : 'div',
28900                     tooltip : file[this.toolTipName],
28901                     cls : 'roo-document-manager-thumb',
28902                     html : '<img tooltip="' + file[this.toolTipName] + '" src="' + img_src + '">'
28903                 },
28904                 {
28905                     tag : 'button',
28906                     cls : 'close',
28907                     html : '<i class="fa fa-times-circle"></i>'
28908                 }
28909             ]
28910         });
28911
28912         var close = previewEl.select('button.close', true).first();
28913
28914         close.on('click', this.onRemove, this, file);
28915
28916         file.target = previewEl;
28917
28918         var image = previewEl.select('img', true).first();
28919         
28920         var _this = this;
28921         
28922         image.dom.addEventListener("load", function(){ _this.onPreviewLoad(file, image); });
28923         
28924         image.on('click', this.onClick, this, file);
28925         
28926         return file;
28927         
28928     },
28929     
28930     onPreviewLoad : function(file, image)
28931     {
28932         if(typeof(file.target) == 'undefined' || !file.target){
28933             return;
28934         }
28935         
28936         var width = image.dom.naturalWidth || image.dom.width;
28937         var height = image.dom.naturalHeight || image.dom.height;
28938         
28939         if(width > height){
28940             file.target.addClass('wide');
28941             return;
28942         }
28943         
28944         file.target.addClass('tall');
28945         return;
28946         
28947     },
28948     
28949     uploadFromSource : function(file, crop)
28950     {
28951         this.xhr = new XMLHttpRequest();
28952         
28953         this.managerEl.createChild({
28954             tag : 'div',
28955             cls : 'roo-document-manager-loading',
28956             cn : [
28957                 {
28958                     tag : 'div',
28959                     tooltip : file.name,
28960                     cls : 'roo-document-manager-thumb',
28961                     html : '<i class="fa fa-circle-o-notch fa-spin"></i>'
28962                 }
28963             ]
28964
28965         });
28966
28967         this.xhr.open(this.method, this.url, true);
28968         
28969         var headers = {
28970             "Accept": "application/json",
28971             "Cache-Control": "no-cache",
28972             "X-Requested-With": "XMLHttpRequest"
28973         };
28974         
28975         for (var headerName in headers) {
28976             var headerValue = headers[headerName];
28977             if (headerValue) {
28978                 this.xhr.setRequestHeader(headerName, headerValue);
28979             }
28980         }
28981         
28982         var _this = this;
28983         
28984         this.xhr.onload = function()
28985         {
28986             _this.xhrOnLoad(_this.xhr);
28987         }
28988         
28989         this.xhr.onerror = function()
28990         {
28991             _this.xhrOnError(_this.xhr);
28992         }
28993         
28994         var formData = new FormData();
28995
28996         formData.append('returnHTML', 'NO');
28997         
28998         formData.append('crop', crop);
28999         
29000         if(typeof(file.filename) != 'undefined'){
29001             formData.append('filename', file.filename);
29002         }
29003         
29004         if(typeof(file.mimetype) != 'undefined'){
29005             formData.append('mimetype', file.mimetype);
29006         }
29007         
29008         Roo.log(formData);
29009         
29010         if(this.fireEvent('prepare', this, formData) != false){
29011             this.xhr.send(formData);
29012         };
29013     }
29014 });
29015
29016 /*
29017 * Licence: LGPL
29018 */
29019
29020 /**
29021  * @class Roo.bootstrap.DocumentViewer
29022  * @extends Roo.bootstrap.Component
29023  * Bootstrap DocumentViewer class
29024  * @cfg {Boolean} showDownload (true|false) show download button (default true)
29025  * @cfg {Boolean} showTrash (true|false) show trash button (default true)
29026  * 
29027  * @constructor
29028  * Create a new DocumentViewer
29029  * @param {Object} config The config object
29030  */
29031
29032 Roo.bootstrap.DocumentViewer = function(config){
29033     Roo.bootstrap.DocumentViewer.superclass.constructor.call(this, config);
29034     
29035     this.addEvents({
29036         /**
29037          * @event initial
29038          * Fire after initEvent
29039          * @param {Roo.bootstrap.DocumentViewer} this
29040          */
29041         "initial" : true,
29042         /**
29043          * @event click
29044          * Fire after click
29045          * @param {Roo.bootstrap.DocumentViewer} this
29046          */
29047         "click" : true,
29048         /**
29049          * @event download
29050          * Fire after download button
29051          * @param {Roo.bootstrap.DocumentViewer} this
29052          */
29053         "download" : true,
29054         /**
29055          * @event trash
29056          * Fire after trash button
29057          * @param {Roo.bootstrap.DocumentViewer} this
29058          */
29059         "trash" : true
29060         
29061     });
29062 };
29063
29064 Roo.extend(Roo.bootstrap.DocumentViewer, Roo.bootstrap.Component,  {
29065     
29066     showDownload : true,
29067     
29068     showTrash : true,
29069     
29070     getAutoCreate : function()
29071     {
29072         var cfg = {
29073             tag : 'div',
29074             cls : 'roo-document-viewer',
29075             cn : [
29076                 {
29077                     tag : 'div',
29078                     cls : 'roo-document-viewer-body',
29079                     cn : [
29080                         {
29081                             tag : 'div',
29082                             cls : 'roo-document-viewer-thumb',
29083                             cn : [
29084                                 {
29085                                     tag : 'img',
29086                                     cls : 'roo-document-viewer-image'
29087                                 }
29088                             ]
29089                         }
29090                     ]
29091                 },
29092                 {
29093                     tag : 'div',
29094                     cls : 'roo-document-viewer-footer',
29095                     cn : {
29096                         tag : 'div',
29097                         cls : 'btn-group btn-group-justified roo-document-viewer-btn-group',
29098                         cn : [
29099                             {
29100                                 tag : 'div',
29101                                 cls : 'btn-group roo-document-viewer-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-document-viewer-trash',
29113                                 cn : [
29114                                     {
29115                                         tag : 'button',
29116                                         cls : 'btn btn-default',
29117                                         html : '<i class="fa fa-trash"></i>'
29118                                     }
29119                                 ]
29120                             }
29121                         ]
29122                     }
29123                 }
29124             ]
29125         };
29126         
29127         return cfg;
29128     },
29129     
29130     initEvents : function()
29131     {
29132         this.bodyEl = this.el.select('.roo-document-viewer-body', true).first();
29133         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY);
29134         
29135         this.thumbEl = this.el.select('.roo-document-viewer-thumb', true).first();
29136         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY);
29137         
29138         this.imageEl = this.el.select('.roo-document-viewer-image', true).first();
29139         this.imageEl.setVisibilityMode(Roo.Element.DISPLAY);
29140         
29141         this.footerEl = this.el.select('.roo-document-viewer-footer', true).first();
29142         this.footerEl.setVisibilityMode(Roo.Element.DISPLAY);
29143         
29144         this.downloadBtn = this.el.select('.roo-document-viewer-download', true).first();
29145         this.downloadBtn.setVisibilityMode(Roo.Element.DISPLAY);
29146         
29147         this.trashBtn = this.el.select('.roo-document-viewer-trash', true).first();
29148         this.trashBtn.setVisibilityMode(Roo.Element.DISPLAY);
29149         
29150         this.bodyEl.on('click', this.onClick, this);
29151         this.downloadBtn.on('click', this.onDownload, this);
29152         this.trashBtn.on('click', this.onTrash, this);
29153         
29154         this.downloadBtn.hide();
29155         this.trashBtn.hide();
29156         
29157         if(this.showDownload){
29158             this.downloadBtn.show();
29159         }
29160         
29161         if(this.showTrash){
29162             this.trashBtn.show();
29163         }
29164         
29165         if(!this.showDownload && !this.showTrash) {
29166             this.footerEl.hide();
29167         }
29168         
29169     },
29170     
29171     initial : function()
29172     {
29173         this.fireEvent('initial', this);
29174         
29175     },
29176     
29177     onClick : function(e)
29178     {
29179         e.preventDefault();
29180         
29181         this.fireEvent('click', this);
29182     },
29183     
29184     onDownload : function(e)
29185     {
29186         e.preventDefault();
29187         
29188         this.fireEvent('download', this);
29189     },
29190     
29191     onTrash : function(e)
29192     {
29193         e.preventDefault();
29194         
29195         this.fireEvent('trash', this);
29196     }
29197     
29198 });
29199 /*
29200  * - LGPL
29201  *
29202  * nav progress bar
29203  * 
29204  */
29205
29206 /**
29207  * @class Roo.bootstrap.NavProgressBar
29208  * @extends Roo.bootstrap.Component
29209  * Bootstrap NavProgressBar class
29210  * 
29211  * @constructor
29212  * Create a new nav progress bar
29213  * @param {Object} config The config object
29214  */
29215
29216 Roo.bootstrap.NavProgressBar = function(config){
29217     Roo.bootstrap.NavProgressBar.superclass.constructor.call(this, config);
29218
29219     this.bullets = this.bullets || [];
29220    
29221 //    Roo.bootstrap.NavProgressBar.register(this);
29222      this.addEvents({
29223         /**
29224              * @event changed
29225              * Fires when the active item changes
29226              * @param {Roo.bootstrap.NavProgressBar} this
29227              * @param {Roo.bootstrap.NavProgressItem} selected The item selected
29228              * @param {Roo.bootstrap.NavProgressItem} prev The previously selected item 
29229          */
29230         'changed': true
29231      });
29232     
29233 };
29234
29235 Roo.extend(Roo.bootstrap.NavProgressBar, Roo.bootstrap.Component,  {
29236     
29237     bullets : [],
29238     barItems : [],
29239     
29240     getAutoCreate : function()
29241     {
29242         var cfg = Roo.apply({}, Roo.bootstrap.NavProgressBar.superclass.getAutoCreate.call(this));
29243         
29244         cfg = {
29245             tag : 'div',
29246             cls : 'roo-navigation-bar-group',
29247             cn : [
29248                 {
29249                     tag : 'div',
29250                     cls : 'roo-navigation-top-bar'
29251                 },
29252                 {
29253                     tag : 'div',
29254                     cls : 'roo-navigation-bullets-bar',
29255                     cn : [
29256                         {
29257                             tag : 'ul',
29258                             cls : 'roo-navigation-bar'
29259                         }
29260                     ]
29261                 },
29262                 
29263                 {
29264                     tag : 'div',
29265                     cls : 'roo-navigation-bottom-bar'
29266                 }
29267             ]
29268             
29269         };
29270         
29271         return cfg;
29272         
29273     },
29274     
29275     initEvents: function() 
29276     {
29277         
29278     },
29279     
29280     onRender : function(ct, position) 
29281     {
29282         Roo.bootstrap.NavProgressBar.superclass.onRender.call(this, ct, position);
29283         
29284         if(this.bullets.length){
29285             Roo.each(this.bullets, function(b){
29286                this.addItem(b);
29287             }, this);
29288         }
29289         
29290         this.format();
29291         
29292     },
29293     
29294     addItem : function(cfg)
29295     {
29296         var item = new Roo.bootstrap.NavProgressItem(cfg);
29297         
29298         item.parentId = this.id;
29299         item.render(this.el.select('.roo-navigation-bar', true).first(), null);
29300         
29301         if(cfg.html){
29302             var top = new Roo.bootstrap.Element({
29303                 tag : 'div',
29304                 cls : 'roo-navigation-bar-text'
29305             });
29306             
29307             var bottom = new Roo.bootstrap.Element({
29308                 tag : 'div',
29309                 cls : 'roo-navigation-bar-text'
29310             });
29311             
29312             top.onRender(this.el.select('.roo-navigation-top-bar', true).first(), null);
29313             bottom.onRender(this.el.select('.roo-navigation-bottom-bar', true).first(), null);
29314             
29315             var topText = new Roo.bootstrap.Element({
29316                 tag : 'span',
29317                 html : (typeof(cfg.position) != 'undefined' && cfg.position == 'top') ? cfg.html : ''
29318             });
29319             
29320             var bottomText = new Roo.bootstrap.Element({
29321                 tag : 'span',
29322                 html : (typeof(cfg.position) != 'undefined' && cfg.position == 'top') ? '' : cfg.html
29323             });
29324             
29325             topText.onRender(top.el, null);
29326             bottomText.onRender(bottom.el, null);
29327             
29328             item.topEl = top;
29329             item.bottomEl = bottom;
29330         }
29331         
29332         this.barItems.push(item);
29333         
29334         return item;
29335     },
29336     
29337     getActive : function()
29338     {
29339         var active = false;
29340         
29341         Roo.each(this.barItems, function(v){
29342             
29343             if (!v.isActive()) {
29344                 return;
29345             }
29346             
29347             active = v;
29348             return false;
29349             
29350         });
29351         
29352         return active;
29353     },
29354     
29355     setActiveItem : function(item)
29356     {
29357         var prev = false;
29358         
29359         Roo.each(this.barItems, function(v){
29360             if (v.rid == item.rid) {
29361                 return ;
29362             }
29363             
29364             if (v.isActive()) {
29365                 v.setActive(false);
29366                 prev = v;
29367             }
29368         });
29369
29370         item.setActive(true);
29371         
29372         this.fireEvent('changed', this, item, prev);
29373     },
29374     
29375     getBarItem: function(rid)
29376     {
29377         var ret = false;
29378         
29379         Roo.each(this.barItems, function(e) {
29380             if (e.rid != rid) {
29381                 return;
29382             }
29383             
29384             ret =  e;
29385             return false;
29386         });
29387         
29388         return ret;
29389     },
29390     
29391     indexOfItem : function(item)
29392     {
29393         var index = false;
29394         
29395         Roo.each(this.barItems, function(v, i){
29396             
29397             if (v.rid != item.rid) {
29398                 return;
29399             }
29400             
29401             index = i;
29402             return false
29403         });
29404         
29405         return index;
29406     },
29407     
29408     setActiveNext : function()
29409     {
29410         var i = this.indexOfItem(this.getActive());
29411         
29412         if (i > this.barItems.length) {
29413             return;
29414         }
29415         
29416         this.setActiveItem(this.barItems[i+1]);
29417     },
29418     
29419     setActivePrev : function()
29420     {
29421         var i = this.indexOfItem(this.getActive());
29422         
29423         if (i  < 1) {
29424             return;
29425         }
29426         
29427         this.setActiveItem(this.barItems[i-1]);
29428     },
29429     
29430     format : function()
29431     {
29432         if(!this.barItems.length){
29433             return;
29434         }
29435      
29436         var width = 100 / this.barItems.length;
29437         
29438         Roo.each(this.barItems, function(i){
29439             i.el.setStyle('width', width + '%');
29440             i.topEl.el.setStyle('width', width + '%');
29441             i.bottomEl.el.setStyle('width', width + '%');
29442         }, this);
29443         
29444     }
29445     
29446 });
29447 /*
29448  * - LGPL
29449  *
29450  * Nav Progress Item
29451  * 
29452  */
29453
29454 /**
29455  * @class Roo.bootstrap.NavProgressItem
29456  * @extends Roo.bootstrap.Component
29457  * Bootstrap NavProgressItem class
29458  * @cfg {String} rid the reference id
29459  * @cfg {Boolean} active (true|false) Is item active default false
29460  * @cfg {Boolean} disabled (true|false) Is item active default false
29461  * @cfg {String} html
29462  * @cfg {String} position (top|bottom) text position default bottom
29463  * @cfg {String} icon show icon instead of number
29464  * 
29465  * @constructor
29466  * Create a new NavProgressItem
29467  * @param {Object} config The config object
29468  */
29469 Roo.bootstrap.NavProgressItem = function(config){
29470     Roo.bootstrap.NavProgressItem.superclass.constructor.call(this, config);
29471     this.addEvents({
29472         // raw events
29473         /**
29474          * @event click
29475          * The raw click event for the entire grid.
29476          * @param {Roo.bootstrap.NavProgressItem} this
29477          * @param {Roo.EventObject} e
29478          */
29479         "click" : true
29480     });
29481    
29482 };
29483
29484 Roo.extend(Roo.bootstrap.NavProgressItem, Roo.bootstrap.Component,  {
29485     
29486     rid : '',
29487     active : false,
29488     disabled : false,
29489     html : '',
29490     position : 'bottom',
29491     icon : false,
29492     
29493     getAutoCreate : function()
29494     {
29495         var iconCls = 'roo-navigation-bar-item-icon';
29496         
29497         iconCls += ((this.icon) ? (' ' + this.icon) : (' step-number')) ;
29498         
29499         var cfg = {
29500             tag: 'li',
29501             cls: 'roo-navigation-bar-item',
29502             cn : [
29503                 {
29504                     tag : 'i',
29505                     cls : iconCls
29506                 }
29507             ]
29508         };
29509         
29510         if(this.active){
29511             cfg.cls += ' active';
29512         }
29513         if(this.disabled){
29514             cfg.cls += ' disabled';
29515         }
29516         
29517         return cfg;
29518     },
29519     
29520     disable : function()
29521     {
29522         this.setDisabled(true);
29523     },
29524     
29525     enable : function()
29526     {
29527         this.setDisabled(false);
29528     },
29529     
29530     initEvents: function() 
29531     {
29532         this.iconEl = this.el.select('.roo-navigation-bar-item-icon', true).first();
29533         
29534         this.iconEl.on('click', this.onClick, this);
29535     },
29536     
29537     onClick : function(e)
29538     {
29539         e.preventDefault();
29540         
29541         if(this.disabled){
29542             return;
29543         }
29544         
29545         if(this.fireEvent('click', this, e) === false){
29546             return;
29547         };
29548         
29549         this.parent().setActiveItem(this);
29550     },
29551     
29552     isActive: function () 
29553     {
29554         return this.active;
29555     },
29556     
29557     setActive : function(state)
29558     {
29559         if(this.active == state){
29560             return;
29561         }
29562         
29563         this.active = state;
29564         
29565         if (state) {
29566             this.el.addClass('active');
29567             return;
29568         }
29569         
29570         this.el.removeClass('active');
29571         
29572         return;
29573     },
29574     
29575     setDisabled : function(state)
29576     {
29577         if(this.disabled == state){
29578             return;
29579         }
29580         
29581         this.disabled = state;
29582         
29583         if (state) {
29584             this.el.addClass('disabled');
29585             return;
29586         }
29587         
29588         this.el.removeClass('disabled');
29589     },
29590     
29591     tooltipEl : function()
29592     {
29593         return this.el.select('.roo-navigation-bar-item-icon', true).first();;
29594     }
29595 });
29596  
29597
29598  /*
29599  * - LGPL
29600  *
29601  * FieldLabel
29602  * 
29603  */
29604
29605 /**
29606  * @class Roo.bootstrap.FieldLabel
29607  * @extends Roo.bootstrap.Component
29608  * Bootstrap FieldLabel class
29609  * @cfg {String} html contents of the element
29610  * @cfg {String} tag tag of the element default label
29611  * @cfg {String} cls class of the element
29612  * @cfg {String} target label target 
29613  * @cfg {Boolean} allowBlank (true|false) target allowBlank default true
29614  * @cfg {String} invalidClass default "text-danger fa fa-lg fa-exclamation-triangle"
29615  * @cfg {String} validClass default "text-success fa fa-lg fa-check"
29616  * @cfg {String} iconTooltip default "This field is required"
29617  * 
29618  * @constructor
29619  * Create a new FieldLabel
29620  * @param {Object} config The config object
29621  */
29622
29623 Roo.bootstrap.FieldLabel = function(config){
29624     Roo.bootstrap.Element.superclass.constructor.call(this, config);
29625     
29626     this.addEvents({
29627             /**
29628              * @event invalid
29629              * Fires after the field has been marked as invalid.
29630              * @param {Roo.form.FieldLabel} this
29631              * @param {String} msg The validation message
29632              */
29633             invalid : true,
29634             /**
29635              * @event valid
29636              * Fires after the field has been validated with no errors.
29637              * @param {Roo.form.FieldLabel} this
29638              */
29639             valid : true
29640         });
29641 };
29642
29643 Roo.extend(Roo.bootstrap.FieldLabel, Roo.bootstrap.Component,  {
29644     
29645     tag: 'label',
29646     cls: '',
29647     html: '',
29648     target: '',
29649     allowBlank : true,
29650     invalidClass : 'text-danger fa fa-lg fa-exclamation-triangle',
29651     validClass : 'text-success fa fa-lg fa-check',
29652     iconTooltip : 'This field is required',
29653     
29654     getAutoCreate : function(){
29655         
29656         var cfg = {
29657             tag : this.tag,
29658             cls : 'roo-bootstrap-field-label ' + this.cls,
29659             for : this.target,
29660             cn : [
29661                 {
29662                     tag : 'i',
29663                     cls : '',
29664                     tooltip : this.iconTooltip
29665                 },
29666                 {
29667                     tag : 'span',
29668                     html : this.html
29669                 }
29670             ] 
29671         };
29672         
29673         return cfg;
29674     },
29675     
29676     initEvents: function() 
29677     {
29678         Roo.bootstrap.Element.superclass.initEvents.call(this);
29679         
29680         this.iconEl = this.el.select('i', true).first();
29681         
29682         this.iconEl.setVisibilityMode(Roo.Element.DISPLAY).hide();
29683         
29684         Roo.bootstrap.FieldLabel.register(this);
29685     },
29686     
29687     /**
29688      * Mark this field as valid
29689      */
29690     markValid : function()
29691     {
29692         this.iconEl.show();
29693         
29694         this.iconEl.removeClass(this.invalidClass);
29695         
29696         this.iconEl.addClass(this.validClass);
29697         
29698         this.fireEvent('valid', this);
29699     },
29700     
29701     /**
29702      * Mark this field as invalid
29703      * @param {String} msg The validation message
29704      */
29705     markInvalid : function(msg)
29706     {
29707         this.iconEl.show();
29708         
29709         this.iconEl.removeClass(this.validClass);
29710         
29711         this.iconEl.addClass(this.invalidClass);
29712         
29713         this.fireEvent('invalid', this, msg);
29714     }
29715     
29716    
29717 });
29718
29719 Roo.apply(Roo.bootstrap.FieldLabel, {
29720     
29721     groups: {},
29722     
29723      /**
29724     * register a FieldLabel Group
29725     * @param {Roo.bootstrap.FieldLabel} the FieldLabel to add
29726     */
29727     register : function(label)
29728     {
29729         if(this.groups.hasOwnProperty(label.target)){
29730             return;
29731         }
29732      
29733         this.groups[label.target] = label;
29734         
29735     },
29736     /**
29737     * fetch a FieldLabel Group based on the target
29738     * @param {string} target
29739     * @returns {Roo.bootstrap.FieldLabel} the CheckBox group
29740     */
29741     get: function(target) {
29742         if (typeof(this.groups[target]) == 'undefined') {
29743             return false;
29744         }
29745         
29746         return this.groups[target] ;
29747     }
29748 });
29749
29750  
29751
29752  /*
29753  * - LGPL
29754  *
29755  * page DateSplitField.
29756  * 
29757  */
29758
29759
29760 /**
29761  * @class Roo.bootstrap.DateSplitField
29762  * @extends Roo.bootstrap.Component
29763  * Bootstrap DateSplitField class
29764  * @cfg {string} fieldLabel - the label associated
29765  * @cfg {Number} labelWidth set the width of label (0-12)
29766  * @cfg {String} labelAlign (top|left)
29767  * @cfg {Boolean} dayAllowBlank (true|false) default false
29768  * @cfg {Boolean} monthAllowBlank (true|false) default false
29769  * @cfg {Boolean} yearAllowBlank (true|false) default false
29770  * @cfg {string} dayPlaceholder 
29771  * @cfg {string} monthPlaceholder
29772  * @cfg {string} yearPlaceholder
29773  * @cfg {string} dayFormat default 'd'
29774  * @cfg {string} monthFormat default 'm'
29775  * @cfg {string} yearFormat default 'Y'
29776  * @cfg {Number} labellg set the width of label (1-12)
29777  * @cfg {Number} labelmd set the width of label (1-12)
29778  * @cfg {Number} labelsm set the width of label (1-12)
29779  * @cfg {Number} labelxs set the width of label (1-12)
29780
29781  *     
29782  * @constructor
29783  * Create a new DateSplitField
29784  * @param {Object} config The config object
29785  */
29786
29787 Roo.bootstrap.DateSplitField = function(config){
29788     Roo.bootstrap.DateSplitField.superclass.constructor.call(this, config);
29789     
29790     this.addEvents({
29791         // raw events
29792          /**
29793          * @event years
29794          * getting the data of years
29795          * @param {Roo.bootstrap.DateSplitField} this
29796          * @param {Object} years
29797          */
29798         "years" : true,
29799         /**
29800          * @event days
29801          * getting the data of days
29802          * @param {Roo.bootstrap.DateSplitField} this
29803          * @param {Object} days
29804          */
29805         "days" : true,
29806         /**
29807          * @event invalid
29808          * Fires after the field has been marked as invalid.
29809          * @param {Roo.form.Field} this
29810          * @param {String} msg The validation message
29811          */
29812         invalid : true,
29813        /**
29814          * @event valid
29815          * Fires after the field has been validated with no errors.
29816          * @param {Roo.form.Field} this
29817          */
29818         valid : true
29819     });
29820 };
29821
29822 Roo.extend(Roo.bootstrap.DateSplitField, Roo.bootstrap.Component,  {
29823     
29824     fieldLabel : '',
29825     labelAlign : 'top',
29826     labelWidth : 3,
29827     dayAllowBlank : false,
29828     monthAllowBlank : false,
29829     yearAllowBlank : false,
29830     dayPlaceholder : '',
29831     monthPlaceholder : '',
29832     yearPlaceholder : '',
29833     dayFormat : 'd',
29834     monthFormat : 'm',
29835     yearFormat : 'Y',
29836     isFormField : true,
29837     labellg : 0,
29838     labelmd : 0,
29839     labelsm : 0,
29840     labelxs : 0,
29841     
29842     getAutoCreate : function()
29843     {
29844         var cfg = {
29845             tag : 'div',
29846             cls : 'row roo-date-split-field-group',
29847             cn : [
29848                 {
29849                     tag : 'input',
29850                     type : 'hidden',
29851                     cls : 'form-hidden-field roo-date-split-field-group-value',
29852                     name : this.name
29853                 }
29854             ]
29855         };
29856         
29857         var labelCls = 'col-md-12';
29858         var contentCls = 'col-md-4';
29859         
29860         if(this.fieldLabel){
29861             
29862             var label = {
29863                 tag : 'div',
29864                 cls : 'column roo-date-split-field-label col-md-' + ((this.labelAlign == 'top') ? '12' : this.labelWidth),
29865                 cn : [
29866                     {
29867                         tag : 'label',
29868                         html : this.fieldLabel
29869                     }
29870                 ]
29871             };
29872             
29873             if(this.labelAlign == 'left'){
29874             
29875                 if(this.labelWidth > 12){
29876                     label.style = "width: " + this.labelWidth + 'px';
29877                 }
29878
29879                 if(this.labelWidth < 13 && this.labelmd == 0){
29880                     this.labelmd = this.labelWidth;
29881                 }
29882
29883                 if(this.labellg > 0){
29884                     labelCls = ' col-lg-' + this.labellg;
29885                     contentCls = ' col-lg-' + ((12 - this.labellg) / 3);
29886                 }
29887
29888                 if(this.labelmd > 0){
29889                     labelCls = ' col-md-' + this.labelmd;
29890                     contentCls = ' col-md-' + ((12 - this.labelmd) / 3);
29891                 }
29892
29893                 if(this.labelsm > 0){
29894                     labelCls = ' col-sm-' + this.labelsm;
29895                     contentCls = ' col-sm-' + ((12 - this.labelsm) / 3);
29896                 }
29897
29898                 if(this.labelxs > 0){
29899                     labelCls = ' col-xs-' + this.labelxs;
29900                     contentCls = ' col-xs-' + ((12 - this.labelxs) / 3);
29901                 }
29902             }
29903             
29904             label.cls += ' ' + labelCls;
29905             
29906             cfg.cn.push(label);
29907         }
29908         
29909         Roo.each(['day', 'month', 'year'], function(t){
29910             cfg.cn.push({
29911                 tag : 'div',
29912                 cls : 'column roo-date-split-field-' + t + ' ' + contentCls
29913             });
29914         }, this);
29915         
29916         return cfg;
29917     },
29918     
29919     inputEl: function ()
29920     {
29921         return this.el.select('.roo-date-split-field-group-value', true).first();
29922     },
29923     
29924     onRender : function(ct, position) 
29925     {
29926         var _this = this;
29927         
29928         Roo.bootstrap.NavProgressBar.superclass.onRender.call(this, ct, position);
29929         
29930         this.inputEl = this.el.select('.roo-date-split-field-group-value', true).first();
29931         
29932         this.dayField = new Roo.bootstrap.ComboBox({
29933             allowBlank : this.dayAllowBlank,
29934             alwaysQuery : true,
29935             displayField : 'value',
29936             editable : false,
29937             fieldLabel : '',
29938             forceSelection : true,
29939             mode : 'local',
29940             placeholder : this.dayPlaceholder,
29941             selectOnFocus : true,
29942             tpl : '<div class="roo-select2-result"><b>{value}</b></div>',
29943             triggerAction : 'all',
29944             typeAhead : true,
29945             valueField : 'value',
29946             store : new Roo.data.SimpleStore({
29947                 data : (function() {    
29948                     var days = [];
29949                     _this.fireEvent('days', _this, days);
29950                     return days;
29951                 })(),
29952                 fields : [ 'value' ]
29953             }),
29954             listeners : {
29955                 select : function (_self, record, index)
29956                 {
29957                     _this.setValue(_this.getValue());
29958                 }
29959             }
29960         });
29961
29962         this.dayField.render(this.el.select('.roo-date-split-field-day', true).first(), null);
29963         
29964         this.monthField = new Roo.bootstrap.MonthField({
29965             after : '<i class=\"fa fa-calendar\"></i>',
29966             allowBlank : this.monthAllowBlank,
29967             placeholder : this.monthPlaceholder,
29968             readOnly : true,
29969             listeners : {
29970                 render : function (_self)
29971                 {
29972                     this.el.select('span.input-group-addon', true).first().on('click', function(e){
29973                         e.preventDefault();
29974                         _self.focus();
29975                     });
29976                 },
29977                 select : function (_self, oldvalue, newvalue)
29978                 {
29979                     _this.setValue(_this.getValue());
29980                 }
29981             }
29982         });
29983         
29984         this.monthField.render(this.el.select('.roo-date-split-field-month', true).first(), null);
29985         
29986         this.yearField = new Roo.bootstrap.ComboBox({
29987             allowBlank : this.yearAllowBlank,
29988             alwaysQuery : true,
29989             displayField : 'value',
29990             editable : false,
29991             fieldLabel : '',
29992             forceSelection : true,
29993             mode : 'local',
29994             placeholder : this.yearPlaceholder,
29995             selectOnFocus : true,
29996             tpl : '<div class="roo-select2-result"><b>{value}</b></div>',
29997             triggerAction : 'all',
29998             typeAhead : true,
29999             valueField : 'value',
30000             store : new Roo.data.SimpleStore({
30001                 data : (function() {
30002                     var years = [];
30003                     _this.fireEvent('years', _this, years);
30004                     return years;
30005                 })(),
30006                 fields : [ 'value' ]
30007             }),
30008             listeners : {
30009                 select : function (_self, record, index)
30010                 {
30011                     _this.setValue(_this.getValue());
30012                 }
30013             }
30014         });
30015
30016         this.yearField.render(this.el.select('.roo-date-split-field-year', true).first(), null);
30017     },
30018     
30019     setValue : function(v, format)
30020     {
30021         this.inputEl.dom.value = v;
30022         
30023         var f = format || (this.yearFormat + '-' + this.monthFormat + '-' + this.dayFormat);
30024         
30025         var d = Date.parseDate(v, f);
30026         
30027         if(!d){
30028             this.validate();
30029             return;
30030         }
30031         
30032         this.setDay(d.format(this.dayFormat));
30033         this.setMonth(d.format(this.monthFormat));
30034         this.setYear(d.format(this.yearFormat));
30035         
30036         this.validate();
30037         
30038         return;
30039     },
30040     
30041     setDay : function(v)
30042     {
30043         this.dayField.setValue(v);
30044         this.inputEl.dom.value = this.getValue();
30045         this.validate();
30046         return;
30047     },
30048     
30049     setMonth : function(v)
30050     {
30051         this.monthField.setValue(v, true);
30052         this.inputEl.dom.value = this.getValue();
30053         this.validate();
30054         return;
30055     },
30056     
30057     setYear : function(v)
30058     {
30059         this.yearField.setValue(v);
30060         this.inputEl.dom.value = this.getValue();
30061         this.validate();
30062         return;
30063     },
30064     
30065     getDay : function()
30066     {
30067         return this.dayField.getValue();
30068     },
30069     
30070     getMonth : function()
30071     {
30072         return this.monthField.getValue();
30073     },
30074     
30075     getYear : function()
30076     {
30077         return this.yearField.getValue();
30078     },
30079     
30080     getValue : function()
30081     {
30082         var f = this.yearFormat + '-' + this.monthFormat + '-' + this.dayFormat;
30083         
30084         var date = this.yearField.getValue() + '-' + this.monthField.getValue() + '-' + this.dayField.getValue();
30085         
30086         return date;
30087     },
30088     
30089     reset : function()
30090     {
30091         this.setDay('');
30092         this.setMonth('');
30093         this.setYear('');
30094         this.inputEl.dom.value = '';
30095         this.validate();
30096         return;
30097     },
30098     
30099     validate : function()
30100     {
30101         var d = this.dayField.validate();
30102         var m = this.monthField.validate();
30103         var y = this.yearField.validate();
30104         
30105         var valid = true;
30106         
30107         if(
30108                 (!this.dayAllowBlank && !d) ||
30109                 (!this.monthAllowBlank && !m) ||
30110                 (!this.yearAllowBlank && !y)
30111         ){
30112             valid = false;
30113         }
30114         
30115         if(this.dayAllowBlank && this.monthAllowBlank && this.yearAllowBlank){
30116             return valid;
30117         }
30118         
30119         if(valid){
30120             this.markValid();
30121             return valid;
30122         }
30123         
30124         this.markInvalid();
30125         
30126         return valid;
30127     },
30128     
30129     markValid : function()
30130     {
30131         
30132         var label = this.el.select('label', true).first();
30133         var icon = this.el.select('i.fa-star', true).first();
30134
30135         if(label && icon){
30136             icon.remove();
30137         }
30138         
30139         this.fireEvent('valid', this);
30140     },
30141     
30142      /**
30143      * Mark this field as invalid
30144      * @param {String} msg The validation message
30145      */
30146     markInvalid : function(msg)
30147     {
30148         
30149         var label = this.el.select('label', true).first();
30150         var icon = this.el.select('i.fa-star', true).first();
30151
30152         if(label && !icon){
30153             this.el.select('.roo-date-split-field-label', true).createChild({
30154                 tag : 'i',
30155                 cls : 'text-danger fa fa-lg fa-star',
30156                 tooltip : 'This field is required',
30157                 style : 'margin-right:5px;'
30158             }, label, true);
30159         }
30160         
30161         this.fireEvent('invalid', this, msg);
30162     },
30163     
30164     clearInvalid : function()
30165     {
30166         var label = this.el.select('label', true).first();
30167         var icon = this.el.select('i.fa-star', true).first();
30168
30169         if(label && icon){
30170             icon.remove();
30171         }
30172         
30173         this.fireEvent('valid', this);
30174     },
30175     
30176     getName: function()
30177     {
30178         return this.name;
30179     }
30180     
30181 });
30182
30183  /**
30184  *
30185  * This is based on 
30186  * http://masonry.desandro.com
30187  *
30188  * The idea is to render all the bricks based on vertical width...
30189  *
30190  * The original code extends 'outlayer' - we might need to use that....
30191  * 
30192  */
30193
30194
30195 /**
30196  * @class Roo.bootstrap.LayoutMasonry
30197  * @extends Roo.bootstrap.Component
30198  * Bootstrap Layout Masonry class
30199  * 
30200  * @constructor
30201  * Create a new Element
30202  * @param {Object} config The config object
30203  */
30204
30205 Roo.bootstrap.LayoutMasonry = function(config){
30206     
30207     Roo.bootstrap.LayoutMasonry.superclass.constructor.call(this, config);
30208     
30209     this.bricks = [];
30210     
30211     Roo.bootstrap.LayoutMasonry.register(this);
30212     
30213     this.addEvents({
30214         // raw events
30215         /**
30216          * @event layout
30217          * Fire after layout the items
30218          * @param {Roo.bootstrap.LayoutMasonry} this
30219          * @param {Roo.EventObject} e
30220          */
30221         "layout" : true
30222     });
30223     
30224 };
30225
30226 Roo.extend(Roo.bootstrap.LayoutMasonry, Roo.bootstrap.Component,  {
30227     
30228     /**
30229      * @cfg {Boolean} isLayoutInstant = no animation?
30230      */   
30231     isLayoutInstant : false, // needed?
30232    
30233     /**
30234      * @cfg {Number} boxWidth  width of the columns
30235      */   
30236     boxWidth : 450,
30237     
30238       /**
30239      * @cfg {Number} boxHeight  - 0 for square, or fix it at a certian height
30240      */   
30241     boxHeight : 0,
30242     
30243     /**
30244      * @cfg {Number} padWidth padding below box..
30245      */   
30246     padWidth : 10, 
30247     
30248     /**
30249      * @cfg {Number} gutter gutter width..
30250      */   
30251     gutter : 10,
30252     
30253      /**
30254      * @cfg {Number} maxCols maximum number of columns
30255      */   
30256     
30257     maxCols: 0,
30258     
30259     /**
30260      * @cfg {Boolean} isAutoInitial defalut true
30261      */   
30262     isAutoInitial : true, 
30263     
30264     containerWidth: 0,
30265     
30266     /**
30267      * @cfg {Boolean} isHorizontal defalut false
30268      */   
30269     isHorizontal : false, 
30270
30271     currentSize : null,
30272     
30273     tag: 'div',
30274     
30275     cls: '',
30276     
30277     bricks: null, //CompositeElement
30278     
30279     cols : 1,
30280     
30281     _isLayoutInited : false,
30282     
30283 //    isAlternative : false, // only use for vertical layout...
30284     
30285     /**
30286      * @cfg {Number} alternativePadWidth padding below box..
30287      */   
30288     alternativePadWidth : 50,
30289     
30290     selectedBrick : [],
30291     
30292     getAutoCreate : function(){
30293         
30294         var cfg = Roo.apply({}, Roo.bootstrap.LayoutMasonry.superclass.getAutoCreate.call(this));
30295         
30296         var cfg = {
30297             tag: this.tag,
30298             cls: 'blog-masonary-wrapper ' + this.cls,
30299             cn : {
30300                 cls : 'mas-boxes masonary'
30301             }
30302         };
30303         
30304         return cfg;
30305     },
30306     
30307     getChildContainer: function( )
30308     {
30309         if (this.boxesEl) {
30310             return this.boxesEl;
30311         }
30312         
30313         this.boxesEl = this.el.select('.mas-boxes').first();
30314         
30315         return this.boxesEl;
30316     },
30317     
30318     
30319     initEvents : function()
30320     {
30321         var _this = this;
30322         
30323         if(this.isAutoInitial){
30324             Roo.log('hook children rendered');
30325             this.on('childrenrendered', function() {
30326                 Roo.log('children rendered');
30327                 _this.initial();
30328             } ,this);
30329         }
30330     },
30331     
30332     initial : function()
30333     {
30334         this.selectedBrick = [];
30335         
30336         this.currentSize = this.el.getBox(true);
30337         
30338         Roo.EventManager.onWindowResize(this.resize, this); 
30339
30340         if(!this.isAutoInitial){
30341             this.layout();
30342             return;
30343         }
30344         
30345         this.layout();
30346         
30347         return;
30348         //this.layout.defer(500,this);
30349         
30350     },
30351     
30352     resize : function()
30353     {
30354         var cs = this.el.getBox(true);
30355         
30356         if (
30357                 this.currentSize.width == cs.width && 
30358                 this.currentSize.x == cs.x && 
30359                 this.currentSize.height == cs.height && 
30360                 this.currentSize.y == cs.y 
30361         ) {
30362             Roo.log("no change in with or X or Y");
30363             return;
30364         }
30365         
30366         this.currentSize = cs;
30367         
30368         this.layout();
30369         
30370     },
30371     
30372     layout : function()
30373     {   
30374         this._resetLayout();
30375         
30376         var isInstant = this.isLayoutInstant !== undefined ? this.isLayoutInstant : !this._isLayoutInited;
30377         
30378         this.layoutItems( isInstant );
30379       
30380         this._isLayoutInited = true;
30381         
30382         this.fireEvent('layout', this);
30383         
30384     },
30385     
30386     _resetLayout : function()
30387     {
30388         if(this.isHorizontal){
30389             this.horizontalMeasureColumns();
30390             return;
30391         }
30392         
30393         this.verticalMeasureColumns();
30394         
30395     },
30396     
30397     verticalMeasureColumns : function()
30398     {
30399         this.getContainerWidth();
30400         
30401 //        if(Roo.lib.Dom.getViewWidth() < 768 && this.isAlternative){
30402 //            this.colWidth = Math.floor(this.containerWidth * 0.8);
30403 //            return;
30404 //        }
30405         
30406         var boxWidth = this.boxWidth + this.padWidth;
30407         
30408         if(this.containerWidth < this.boxWidth){
30409             boxWidth = this.containerWidth
30410         }
30411         
30412         var containerWidth = this.containerWidth;
30413         
30414         var cols = Math.floor(containerWidth / boxWidth);
30415         
30416         this.cols = Math.max( cols, 1 );
30417         
30418         this.cols = this.maxCols > 0 ? Math.min( this.cols, this.maxCols ) : this.cols;
30419         
30420         var totalBoxWidth = this.cols * boxWidth - this.padWidth;
30421         
30422         var avail = Math.floor((containerWidth - totalBoxWidth) / this.cols);
30423         
30424         this.colWidth = boxWidth + avail - this.padWidth;
30425         
30426         this.unitWidth = Math.round((this.colWidth - (this.gutter * 2)) / 3);
30427         this.unitHeight = this.boxHeight > 0 ? this.boxHeight  : this.unitWidth;
30428     },
30429     
30430     horizontalMeasureColumns : function()
30431     {
30432         this.getContainerWidth();
30433         
30434         var boxWidth = this.boxWidth;
30435         
30436         if(this.containerWidth < boxWidth){
30437             boxWidth = this.containerWidth;
30438         }
30439         
30440         this.unitWidth = Math.floor((boxWidth - (this.gutter * 2)) / 3);
30441         
30442         this.el.setHeight(boxWidth);
30443         
30444     },
30445     
30446     getContainerWidth : function()
30447     {
30448         this.containerWidth = this.el.getBox(true).width;  //maybe use getComputedWidth
30449     },
30450     
30451     layoutItems : function( isInstant )
30452     {
30453         Roo.log(this.bricks);
30454         
30455         var items = Roo.apply([], this.bricks);
30456         
30457         if(this.isHorizontal){
30458             this._horizontalLayoutItems( items , isInstant );
30459             return;
30460         }
30461         
30462 //        if(Roo.lib.Dom.getViewWidth() < 768 && this.isAlternative){
30463 //            this._verticalAlternativeLayoutItems( items , isInstant );
30464 //            return;
30465 //        }
30466         
30467         this._verticalLayoutItems( items , isInstant );
30468         
30469     },
30470     
30471     _verticalLayoutItems : function ( items , isInstant)
30472     {
30473         if ( !items || !items.length ) {
30474             return;
30475         }
30476         
30477         var standard = [
30478             ['xs', 'xs', 'xs', 'tall'],
30479             ['xs', 'xs', 'tall'],
30480             ['xs', 'xs', 'sm'],
30481             ['xs', 'xs', 'xs'],
30482             ['xs', 'tall'],
30483             ['xs', 'sm'],
30484             ['xs', 'xs'],
30485             ['xs'],
30486             
30487             ['sm', 'xs', 'xs'],
30488             ['sm', 'xs'],
30489             ['sm'],
30490             
30491             ['tall', 'xs', 'xs', 'xs'],
30492             ['tall', 'xs', 'xs'],
30493             ['tall', 'xs'],
30494             ['tall']
30495             
30496         ];
30497         
30498         var queue = [];
30499         
30500         var boxes = [];
30501         
30502         var box = [];
30503         
30504         Roo.each(items, function(item, k){
30505             
30506             switch (item.size) {
30507                 // these layouts take up a full box,
30508                 case 'md' :
30509                 case 'md-left' :
30510                 case 'md-right' :
30511                 case 'wide' :
30512                     
30513                     if(box.length){
30514                         boxes.push(box);
30515                         box = [];
30516                     }
30517                     
30518                     boxes.push([item]);
30519                     
30520                     break;
30521                     
30522                 case 'xs' :
30523                 case 'sm' :
30524                 case 'tall' :
30525                     
30526                     box.push(item);
30527                     
30528                     break;
30529                 default :
30530                     break;
30531                     
30532             }
30533             
30534         }, this);
30535         
30536         if(box.length){
30537             boxes.push(box);
30538             box = [];
30539         }
30540         
30541         var filterPattern = function(box, length)
30542         {
30543             if(!box.length){
30544                 return;
30545             }
30546             
30547             var match = false;
30548             
30549             var pattern = box.slice(0, length);
30550             
30551             var format = [];
30552             
30553             Roo.each(pattern, function(i){
30554                 format.push(i.size);
30555             }, this);
30556             
30557             Roo.each(standard, function(s){
30558                 
30559                 if(String(s) != String(format)){
30560                     return;
30561                 }
30562                 
30563                 match = true;
30564                 return false;
30565                 
30566             }, this);
30567             
30568             if(!match && length == 1){
30569                 return;
30570             }
30571             
30572             if(!match){
30573                 filterPattern(box, length - 1);
30574                 return;
30575             }
30576                 
30577             queue.push(pattern);
30578
30579             box = box.slice(length, box.length);
30580
30581             filterPattern(box, 4);
30582
30583             return;
30584             
30585         }
30586         
30587         Roo.each(boxes, function(box, k){
30588             
30589             if(!box.length){
30590                 return;
30591             }
30592             
30593             if(box.length == 1){
30594                 queue.push(box);
30595                 return;
30596             }
30597             
30598             filterPattern(box, 4);
30599             
30600         }, this);
30601         
30602         this._processVerticalLayoutQueue( queue, isInstant );
30603         
30604     },
30605     
30606 //    _verticalAlternativeLayoutItems : function( items , isInstant )
30607 //    {
30608 //        if ( !items || !items.length ) {
30609 //            return;
30610 //        }
30611 //
30612 //        this._processVerticalAlternativeLayoutQueue( items, isInstant );
30613 //        
30614 //    },
30615     
30616     _horizontalLayoutItems : function ( items , isInstant)
30617     {
30618         if ( !items || !items.length || items.length < 3) {
30619             return;
30620         }
30621         
30622         items.reverse();
30623         
30624         var eItems = items.slice(0, 3);
30625         
30626         items = items.slice(3, items.length);
30627         
30628         var standard = [
30629             ['xs', 'xs', 'xs', 'wide'],
30630             ['xs', 'xs', 'wide'],
30631             ['xs', 'xs', 'sm'],
30632             ['xs', 'xs', 'xs'],
30633             ['xs', 'wide'],
30634             ['xs', 'sm'],
30635             ['xs', 'xs'],
30636             ['xs'],
30637             
30638             ['sm', 'xs', 'xs'],
30639             ['sm', 'xs'],
30640             ['sm'],
30641             
30642             ['wide', 'xs', 'xs', 'xs'],
30643             ['wide', 'xs', 'xs'],
30644             ['wide', 'xs'],
30645             ['wide'],
30646             
30647             ['wide-thin']
30648         ];
30649         
30650         var queue = [];
30651         
30652         var boxes = [];
30653         
30654         var box = [];
30655         
30656         Roo.each(items, function(item, k){
30657             
30658             switch (item.size) {
30659                 case 'md' :
30660                 case 'md-left' :
30661                 case 'md-right' :
30662                 case 'tall' :
30663                     
30664                     if(box.length){
30665                         boxes.push(box);
30666                         box = [];
30667                     }
30668                     
30669                     boxes.push([item]);
30670                     
30671                     break;
30672                     
30673                 case 'xs' :
30674                 case 'sm' :
30675                 case 'wide' :
30676                 case 'wide-thin' :
30677                     
30678                     box.push(item);
30679                     
30680                     break;
30681                 default :
30682                     break;
30683                     
30684             }
30685             
30686         }, this);
30687         
30688         if(box.length){
30689             boxes.push(box);
30690             box = [];
30691         }
30692         
30693         var filterPattern = function(box, length)
30694         {
30695             if(!box.length){
30696                 return;
30697             }
30698             
30699             var match = false;
30700             
30701             var pattern = box.slice(0, length);
30702             
30703             var format = [];
30704             
30705             Roo.each(pattern, function(i){
30706                 format.push(i.size);
30707             }, this);
30708             
30709             Roo.each(standard, function(s){
30710                 
30711                 if(String(s) != String(format)){
30712                     return;
30713                 }
30714                 
30715                 match = true;
30716                 return false;
30717                 
30718             }, this);
30719             
30720             if(!match && length == 1){
30721                 return;
30722             }
30723             
30724             if(!match){
30725                 filterPattern(box, length - 1);
30726                 return;
30727             }
30728                 
30729             queue.push(pattern);
30730
30731             box = box.slice(length, box.length);
30732
30733             filterPattern(box, 4);
30734
30735             return;
30736             
30737         }
30738         
30739         Roo.each(boxes, function(box, k){
30740             
30741             if(!box.length){
30742                 return;
30743             }
30744             
30745             if(box.length == 1){
30746                 queue.push(box);
30747                 return;
30748             }
30749             
30750             filterPattern(box, 4);
30751             
30752         }, this);
30753         
30754         
30755         var prune = [];
30756         
30757         var pos = this.el.getBox(true);
30758         
30759         var minX = pos.x;
30760         
30761         var maxX = pos.right - this.unitWidth * 3 - this.gutter * 2 - this.padWidth;
30762         
30763         var hit_end = false;
30764         
30765         Roo.each(queue, function(box){
30766             
30767             if(hit_end){
30768                 
30769                 Roo.each(box, function(b){
30770                 
30771                     b.el.setVisibilityMode(Roo.Element.DISPLAY);
30772                     b.el.hide();
30773
30774                 }, this);
30775
30776                 return;
30777             }
30778             
30779             var mx = 0;
30780             
30781             Roo.each(box, function(b){
30782                 
30783                 b.el.setVisibilityMode(Roo.Element.DISPLAY);
30784                 b.el.show();
30785
30786                 mx = Math.max(mx, b.x);
30787                 
30788             }, this);
30789             
30790             maxX = maxX - this.unitWidth * mx - this.gutter * (mx - 1) - this.padWidth;
30791             
30792             if(maxX < minX){
30793                 
30794                 Roo.each(box, function(b){
30795                 
30796                     b.el.setVisibilityMode(Roo.Element.DISPLAY);
30797                     b.el.hide();
30798                     
30799                 }, this);
30800                 
30801                 hit_end = true;
30802                 
30803                 return;
30804             }
30805             
30806             prune.push(box);
30807             
30808         }, this);
30809         
30810         this._processHorizontalLayoutQueue( prune, eItems, isInstant );
30811     },
30812     
30813     /** Sets position of item in DOM
30814     * @param {Element} item
30815     * @param {Number} x - horizontal position
30816     * @param {Number} y - vertical position
30817     * @param {Boolean} isInstant - disables transitions
30818     */
30819     _processVerticalLayoutQueue : function( queue, isInstant )
30820     {
30821         var pos = this.el.getBox(true);
30822         var x = pos.x;
30823         var y = pos.y;
30824         var maxY = [];
30825         
30826         for (var i = 0; i < this.cols; i++){
30827             maxY[i] = pos.y;
30828         }
30829         
30830         Roo.each(queue, function(box, k){
30831             
30832             var col = k % this.cols;
30833             
30834             Roo.each(box, function(b,kk){
30835                 
30836                 b.el.position('absolute');
30837                 
30838                 var width = Math.floor(this.unitWidth * b.x + (this.gutter * (b.x - 1)) + b.el.getPadding('lr'));
30839                 var height = Math.floor(this.unitHeight * b.y + (this.gutter * (b.y - 1)) + b.el.getPadding('tb'));
30840                 
30841                 if(b.size == 'md-left' || b.size == 'md-right'){
30842                     width = Math.floor(this.unitWidth * (b.x - 1) + (this.gutter * (b.x - 2)) + b.el.getPadding('lr'));
30843                     height = Math.floor(this.unitHeight * (b.y - 1) + (this.gutter * (b.y - 2)) + b.el.getPadding('tb'));
30844                 }
30845                 
30846                 b.el.setWidth(width);
30847                 b.el.setHeight(height);
30848                 // iframe?
30849                 b.el.select('iframe',true).setSize(width,height);
30850                 
30851             }, this);
30852             
30853             for (var i = 0; i < this.cols; i++){
30854                 
30855                 if(maxY[i] < maxY[col]){
30856                     col = i;
30857                     continue;
30858                 }
30859                 
30860                 col = Math.min(col, i);
30861                 
30862             }
30863             
30864             x = pos.x + col * (this.colWidth + this.padWidth);
30865             
30866             y = maxY[col];
30867             
30868             var positions = [];
30869             
30870             switch (box.length){
30871                 case 1 :
30872                     positions = this.getVerticalOneBoxColPositions(x, y, box);
30873                     break;
30874                 case 2 :
30875                     positions = this.getVerticalTwoBoxColPositions(x, y, box);
30876                     break;
30877                 case 3 :
30878                     positions = this.getVerticalThreeBoxColPositions(x, y, box);
30879                     break;
30880                 case 4 :
30881                     positions = this.getVerticalFourBoxColPositions(x, y, box);
30882                     break;
30883                 default :
30884                     break;
30885             }
30886             
30887             Roo.each(box, function(b,kk){
30888                 
30889                 b.el.setXY([positions[kk].x, positions[kk].y], isInstant ? false : true);
30890                 
30891                 var sz = b.el.getSize();
30892                 
30893                 maxY[col] = Math.max(maxY[col], positions[kk].y + sz.height + this.padWidth);
30894                 
30895             }, this);
30896             
30897         }, this);
30898         
30899         var mY = 0;
30900         
30901         for (var i = 0; i < this.cols; i++){
30902             mY = Math.max(mY, maxY[i]);
30903         }
30904         
30905         this.el.setHeight(mY - pos.y);
30906         
30907     },
30908     
30909 //    _processVerticalAlternativeLayoutQueue : function( items, isInstant )
30910 //    {
30911 //        var pos = this.el.getBox(true);
30912 //        var x = pos.x;
30913 //        var y = pos.y;
30914 //        var maxX = pos.right;
30915 //        
30916 //        var maxHeight = 0;
30917 //        
30918 //        Roo.each(items, function(item, k){
30919 //            
30920 //            var c = k % 2;
30921 //            
30922 //            item.el.position('absolute');
30923 //                
30924 //            var width = Math.floor(this.colWidth + item.el.getPadding('lr'));
30925 //
30926 //            item.el.setWidth(width);
30927 //
30928 //            var height = Math.floor(this.colWidth * item.y / item.x + item.el.getPadding('tb'));
30929 //
30930 //            item.el.setHeight(height);
30931 //            
30932 //            if(c == 0){
30933 //                item.el.setXY([x, y], isInstant ? false : true);
30934 //            } else {
30935 //                item.el.setXY([maxX - width, y], isInstant ? false : true);
30936 //            }
30937 //            
30938 //            y = y + height + this.alternativePadWidth;
30939 //            
30940 //            maxHeight = maxHeight + height + this.alternativePadWidth;
30941 //            
30942 //        }, this);
30943 //        
30944 //        this.el.setHeight(maxHeight);
30945 //        
30946 //    },
30947     
30948     _processHorizontalLayoutQueue : function( queue, eItems, isInstant )
30949     {
30950         var pos = this.el.getBox(true);
30951         
30952         var minX = pos.x;
30953         var minY = pos.y;
30954         
30955         var maxX = pos.right;
30956         
30957         this._processHorizontalEndItem(eItems, maxX, minX, minY, isInstant);
30958         
30959         var maxX = maxX - this.unitWidth * 3 - this.gutter * 2 - this.padWidth;
30960         
30961         Roo.each(queue, function(box, k){
30962             
30963             Roo.each(box, function(b, kk){
30964                 
30965                 b.el.position('absolute');
30966                 
30967                 var width = Math.floor(this.unitWidth * b.x + (this.gutter * (b.x - 1)) + b.el.getPadding('lr'));
30968                 var height = Math.floor(this.unitWidth * b.y + (this.gutter * (b.y - 1)) + b.el.getPadding('tb'));
30969                 
30970                 if(b.size == 'md-left' || b.size == 'md-right'){
30971                     width = Math.floor(this.unitWidth * (b.x - 1) + (this.gutter * (b.x - 2)) + b.el.getPadding('lr'));
30972                     height = Math.floor(this.unitWidth * (b.y - 1) + (this.gutter * (b.y - 2)) + b.el.getPadding('tb'));
30973                 }
30974                 
30975                 b.el.setWidth(width);
30976                 b.el.setHeight(height);
30977                 
30978             }, this);
30979             
30980             if(!box.length){
30981                 return;
30982             }
30983             
30984             var positions = [];
30985             
30986             switch (box.length){
30987                 case 1 :
30988                     positions = this.getHorizontalOneBoxColPositions(maxX, minY, box);
30989                     break;
30990                 case 2 :
30991                     positions = this.getHorizontalTwoBoxColPositions(maxX, minY, box);
30992                     break;
30993                 case 3 :
30994                     positions = this.getHorizontalThreeBoxColPositions(maxX, minY, box);
30995                     break;
30996                 case 4 :
30997                     positions = this.getHorizontalFourBoxColPositions(maxX, minY, box);
30998                     break;
30999                 default :
31000                     break;
31001             }
31002             
31003             Roo.each(box, function(b,kk){
31004                 
31005                 b.el.setXY([positions[kk].x, positions[kk].y], isInstant ? false : true);
31006                 
31007                 maxX = Math.min(maxX, positions[kk].x - this.padWidth);
31008                 
31009             }, this);
31010             
31011         }, this);
31012         
31013     },
31014     
31015     _processHorizontalEndItem : function(eItems, maxX, minX, minY, isInstant)
31016     {
31017         Roo.each(eItems, function(b,k){
31018             
31019             b.size = (k == 0) ? 'sm' : 'xs';
31020             b.x = (k == 0) ? 2 : 1;
31021             b.y = (k == 0) ? 2 : 1;
31022             
31023             b.el.position('absolute');
31024             
31025             var width = Math.floor(this.unitWidth * b.x + (this.gutter * (b.x - 1)) + b.el.getPadding('lr'));
31026                 
31027             b.el.setWidth(width);
31028             
31029             var height = Math.floor(this.unitWidth * b.y + (this.gutter * (b.y - 1)) + b.el.getPadding('tb'));
31030             
31031             b.el.setHeight(height);
31032             
31033         }, this);
31034
31035         var positions = [];
31036         
31037         positions.push({
31038             x : maxX - this.unitWidth * 2 - this.gutter,
31039             y : minY
31040         });
31041         
31042         positions.push({
31043             x : maxX - this.unitWidth,
31044             y : minY + (this.unitWidth + this.gutter) * 2
31045         });
31046         
31047         positions.push({
31048             x : maxX - this.unitWidth * 3 - this.gutter * 2,
31049             y : minY
31050         });
31051         
31052         Roo.each(eItems, function(b,k){
31053             
31054             b.el.setXY([positions[k].x, positions[k].y], isInstant ? false : true);
31055
31056         }, this);
31057         
31058     },
31059     
31060     getVerticalOneBoxColPositions : function(x, y, box)
31061     {
31062         var pos = [];
31063         
31064         var rand = Math.floor(Math.random() * ((4 - box[0].x)));
31065         
31066         if(box[0].size == 'md-left'){
31067             rand = 0;
31068         }
31069         
31070         if(box[0].size == 'md-right'){
31071             rand = 1;
31072         }
31073         
31074         pos.push({
31075             x : x + (this.unitWidth + this.gutter) * rand,
31076             y : y
31077         });
31078         
31079         return pos;
31080     },
31081     
31082     getVerticalTwoBoxColPositions : function(x, y, box)
31083     {
31084         var pos = [];
31085         
31086         if(box[0].size == 'xs'){
31087             
31088             pos.push({
31089                 x : x,
31090                 y : y + ((this.unitHeight + this.gutter) * Math.floor(Math.random() * box[1].y))
31091             });
31092
31093             pos.push({
31094                 x : x + (this.unitWidth + this.gutter) * (3 - box[1].x),
31095                 y : y
31096             });
31097             
31098             return pos;
31099             
31100         }
31101         
31102         pos.push({
31103             x : x,
31104             y : y
31105         });
31106
31107         pos.push({
31108             x : x + (this.unitWidth + this.gutter) * 2,
31109             y : y + ((this.unitHeight + this.gutter) * Math.floor(Math.random() * box[0].y))
31110         });
31111         
31112         return pos;
31113         
31114     },
31115     
31116     getVerticalThreeBoxColPositions : function(x, y, box)
31117     {
31118         var pos = [];
31119         
31120         if(box[0].size == 'xs' && box[1].size == 'xs' && box[2].size == 'xs'){
31121             
31122             pos.push({
31123                 x : x,
31124                 y : y
31125             });
31126
31127             pos.push({
31128                 x : x + (this.unitWidth + this.gutter) * 1,
31129                 y : y
31130             });
31131             
31132             pos.push({
31133                 x : x + (this.unitWidth + this.gutter) * 2,
31134                 y : y
31135             });
31136             
31137             return pos;
31138             
31139         }
31140         
31141         if(box[0].size == 'xs' && box[1].size == 'xs'){
31142             
31143             pos.push({
31144                 x : x,
31145                 y : y
31146             });
31147
31148             pos.push({
31149                 x : x,
31150                 y : y + ((this.unitHeight + this.gutter) * (box[2].y - 1))
31151             });
31152             
31153             pos.push({
31154                 x : x + (this.unitWidth + this.gutter) * 1,
31155                 y : y
31156             });
31157             
31158             return pos;
31159             
31160         }
31161         
31162         pos.push({
31163             x : x,
31164             y : y
31165         });
31166
31167         pos.push({
31168             x : x + (this.unitWidth + this.gutter) * 2,
31169             y : y
31170         });
31171
31172         pos.push({
31173             x : x + (this.unitWidth + this.gutter) * 2,
31174             y : y + (this.unitHeight + this.gutter) * (box[0].y - 1)
31175         });
31176             
31177         return pos;
31178         
31179     },
31180     
31181     getVerticalFourBoxColPositions : function(x, y, box)
31182     {
31183         var pos = [];
31184         
31185         if(box[0].size == 'xs'){
31186             
31187             pos.push({
31188                 x : x,
31189                 y : y
31190             });
31191
31192             pos.push({
31193                 x : x,
31194                 y : y + (this.unitHeight + this.gutter) * 1
31195             });
31196             
31197             pos.push({
31198                 x : x,
31199                 y : y + (this.unitHeight + this.gutter) * 2
31200             });
31201             
31202             pos.push({
31203                 x : x + (this.unitWidth + this.gutter) * 1,
31204                 y : y
31205             });
31206             
31207             return pos;
31208             
31209         }
31210         
31211         pos.push({
31212             x : x,
31213             y : y
31214         });
31215
31216         pos.push({
31217             x : x + (this.unitWidth + this.gutter) * 2,
31218             y : y
31219         });
31220
31221         pos.push({
31222             x : x + (this.unitHeightunitWidth + this.gutter) * 2,
31223             y : y + (this.unitHeight + this.gutter) * 1
31224         });
31225
31226         pos.push({
31227             x : x + (this.unitWidth + this.gutter) * 2,
31228             y : y + (this.unitWidth + this.gutter) * 2
31229         });
31230
31231         return pos;
31232         
31233     },
31234     
31235     getHorizontalOneBoxColPositions : function(maxX, minY, box)
31236     {
31237         var pos = [];
31238         
31239         if(box[0].size == 'md-left'){
31240             pos.push({
31241                 x : maxX - this.unitWidth * (box[0].x - 1) - this.gutter * (box[0].x - 2),
31242                 y : minY
31243             });
31244             
31245             return pos;
31246         }
31247         
31248         if(box[0].size == 'md-right'){
31249             pos.push({
31250                 x : maxX - this.unitWidth * (box[0].x - 1) - this.gutter * (box[0].x - 2),
31251                 y : minY + (this.unitWidth + this.gutter) * 1
31252             });
31253             
31254             return pos;
31255         }
31256         
31257         var rand = Math.floor(Math.random() * (4 - box[0].y));
31258         
31259         pos.push({
31260             x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
31261             y : minY + (this.unitWidth + this.gutter) * rand
31262         });
31263         
31264         return pos;
31265         
31266     },
31267     
31268     getHorizontalTwoBoxColPositions : function(maxX, minY, box)
31269     {
31270         var pos = [];
31271         
31272         if(box[0].size == 'xs'){
31273             
31274             pos.push({
31275                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
31276                 y : minY
31277             });
31278
31279             pos.push({
31280                 x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
31281                 y : minY + (this.unitWidth + this.gutter) * (3 - box[1].y)
31282             });
31283             
31284             return pos;
31285             
31286         }
31287         
31288         pos.push({
31289             x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
31290             y : minY
31291         });
31292
31293         pos.push({
31294             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
31295             y : minY + (this.unitWidth + this.gutter) * 2
31296         });
31297         
31298         return pos;
31299         
31300     },
31301     
31302     getHorizontalThreeBoxColPositions : function(maxX, minY, box)
31303     {
31304         var pos = [];
31305         
31306         if(box[0].size == 'xs' && box[1].size == 'xs' && box[2].size == 'xs'){
31307             
31308             pos.push({
31309                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
31310                 y : minY
31311             });
31312
31313             pos.push({
31314                 x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
31315                 y : minY + (this.unitWidth + this.gutter) * 1
31316             });
31317             
31318             pos.push({
31319                 x : maxX - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
31320                 y : minY + (this.unitWidth + this.gutter) * 2
31321             });
31322             
31323             return pos;
31324             
31325         }
31326         
31327         if(box[0].size == 'xs' && box[1].size == 'xs'){
31328             
31329             pos.push({
31330                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
31331                 y : minY
31332             });
31333
31334             pos.push({
31335                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1) - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
31336                 y : minY
31337             });
31338             
31339             pos.push({
31340                 x : maxX - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
31341                 y : minY + (this.unitWidth + this.gutter) * 1
31342             });
31343             
31344             return pos;
31345             
31346         }
31347         
31348         pos.push({
31349             x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
31350             y : minY
31351         });
31352
31353         pos.push({
31354             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
31355             y : minY + (this.unitWidth + this.gutter) * 2
31356         });
31357
31358         pos.push({
31359             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1) - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
31360             y : minY + (this.unitWidth + this.gutter) * 2
31361         });
31362             
31363         return pos;
31364         
31365     },
31366     
31367     getHorizontalFourBoxColPositions : function(maxX, minY, box)
31368     {
31369         var pos = [];
31370         
31371         if(box[0].size == 'xs'){
31372             
31373             pos.push({
31374                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
31375                 y : minY
31376             });
31377
31378             pos.push({
31379                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1) - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
31380                 y : minY
31381             });
31382             
31383             pos.push({
31384                 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),
31385                 y : minY
31386             });
31387             
31388             pos.push({
31389                 x : maxX - this.unitWidth * box[3].x - this.gutter * (box[3].x - 1),
31390                 y : minY + (this.unitWidth + this.gutter) * 1
31391             });
31392             
31393             return pos;
31394             
31395         }
31396         
31397         pos.push({
31398             x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
31399             y : minY
31400         });
31401         
31402         pos.push({
31403             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
31404             y : minY + (this.unitWidth + this.gutter) * 2
31405         });
31406         
31407         pos.push({
31408             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1) - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
31409             y : minY + (this.unitWidth + this.gutter) * 2
31410         });
31411         
31412         pos.push({
31413             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),
31414             y : minY + (this.unitWidth + this.gutter) * 2
31415         });
31416
31417         return pos;
31418         
31419     },
31420     
31421     /**
31422     * remove a Masonry Brick
31423     * @param {Roo.bootstrap.MasonryBrick} the masonry brick to remove
31424     */
31425     removeBrick : function(brick_id)
31426     {
31427         if (!brick_id) {
31428             return;
31429         }
31430         
31431         for (var i = 0; i<this.bricks.length; i++) {
31432             if (this.bricks[i].id == brick_id) {
31433                 this.bricks.splice(i,1);
31434                 this.el.dom.removeChild(Roo.get(brick_id).dom);
31435                 this.initial();
31436             }
31437         }
31438     },
31439     
31440     /**
31441     * adds a Masonry Brick
31442     * @param {Roo.bootstrap.MasonryBrick} the masonry brick to add
31443     */
31444     addBrick : function(cfg)
31445     {
31446         var cn = new Roo.bootstrap.MasonryBrick(cfg);
31447         //this.register(cn);
31448         cn.parentId = this.id;
31449         cn.onRender(this.el, null);
31450         return cn;
31451     },
31452     
31453     /**
31454     * register a Masonry Brick
31455     * @param {Roo.bootstrap.MasonryBrick} the masonry brick to add
31456     */
31457     
31458     register : function(brick)
31459     {
31460         this.bricks.push(brick);
31461         brick.masonryId = this.id;
31462     },
31463     
31464     /**
31465     * clear all the Masonry Brick
31466     */
31467     clearAll : function()
31468     {
31469         this.bricks = [];
31470         //this.getChildContainer().dom.innerHTML = "";
31471         this.el.dom.innerHTML = '';
31472     },
31473     
31474     getSelected : function()
31475     {
31476         if (!this.selectedBrick) {
31477             return false;
31478         }
31479         
31480         return this.selectedBrick;
31481     }
31482 });
31483
31484 Roo.apply(Roo.bootstrap.LayoutMasonry, {
31485     
31486     groups: {},
31487      /**
31488     * register a Masonry Layout
31489     * @param {Roo.bootstrap.LayoutMasonry} the masonry layout to add
31490     */
31491     
31492     register : function(layout)
31493     {
31494         this.groups[layout.id] = layout;
31495     },
31496     /**
31497     * fetch a  Masonry Layout based on the masonry layout ID
31498     * @param {string} the masonry layout to add
31499     * @returns {Roo.bootstrap.LayoutMasonry} the masonry layout
31500     */
31501     
31502     get: function(layout_id) {
31503         if (typeof(this.groups[layout_id]) == 'undefined') {
31504             return false;
31505         }
31506         return this.groups[layout_id] ;
31507     }
31508     
31509     
31510     
31511 });
31512
31513  
31514
31515  /**
31516  *
31517  * This is based on 
31518  * http://masonry.desandro.com
31519  *
31520  * The idea is to render all the bricks based on vertical width...
31521  *
31522  * The original code extends 'outlayer' - we might need to use that....
31523  * 
31524  */
31525
31526
31527 /**
31528  * @class Roo.bootstrap.LayoutMasonryAuto
31529  * @extends Roo.bootstrap.Component
31530  * Bootstrap Layout Masonry class
31531  * 
31532  * @constructor
31533  * Create a new Element
31534  * @param {Object} config The config object
31535  */
31536
31537 Roo.bootstrap.LayoutMasonryAuto = function(config){
31538     Roo.bootstrap.LayoutMasonryAuto.superclass.constructor.call(this, config);
31539 };
31540
31541 Roo.extend(Roo.bootstrap.LayoutMasonryAuto, Roo.bootstrap.Component,  {
31542     
31543       /**
31544      * @cfg {Boolean} isFitWidth  - resize the width..
31545      */   
31546     isFitWidth : false,  // options..
31547     /**
31548      * @cfg {Boolean} isOriginLeft = left align?
31549      */   
31550     isOriginLeft : true,
31551     /**
31552      * @cfg {Boolean} isOriginTop = top align?
31553      */   
31554     isOriginTop : false,
31555     /**
31556      * @cfg {Boolean} isLayoutInstant = no animation?
31557      */   
31558     isLayoutInstant : false, // needed?
31559     /**
31560      * @cfg {Boolean} isResizingContainer = not sure if this is used..
31561      */   
31562     isResizingContainer : true,
31563     /**
31564      * @cfg {Number} columnWidth  width of the columns 
31565      */   
31566     
31567     columnWidth : 0,
31568     
31569     /**
31570      * @cfg {Number} maxCols maximum number of columns
31571      */   
31572     
31573     maxCols: 0,
31574     /**
31575      * @cfg {Number} padHeight padding below box..
31576      */   
31577     
31578     padHeight : 10, 
31579     
31580     /**
31581      * @cfg {Boolean} isAutoInitial defalut true
31582      */   
31583     
31584     isAutoInitial : true, 
31585     
31586     // private?
31587     gutter : 0,
31588     
31589     containerWidth: 0,
31590     initialColumnWidth : 0,
31591     currentSize : null,
31592     
31593     colYs : null, // array.
31594     maxY : 0,
31595     padWidth: 10,
31596     
31597     
31598     tag: 'div',
31599     cls: '',
31600     bricks: null, //CompositeElement
31601     cols : 0, // array?
31602     // element : null, // wrapped now this.el
31603     _isLayoutInited : null, 
31604     
31605     
31606     getAutoCreate : function(){
31607         
31608         var cfg = {
31609             tag: this.tag,
31610             cls: 'blog-masonary-wrapper ' + this.cls,
31611             cn : {
31612                 cls : 'mas-boxes masonary'
31613             }
31614         };
31615         
31616         return cfg;
31617     },
31618     
31619     getChildContainer: function( )
31620     {
31621         if (this.boxesEl) {
31622             return this.boxesEl;
31623         }
31624         
31625         this.boxesEl = this.el.select('.mas-boxes').first();
31626         
31627         return this.boxesEl;
31628     },
31629     
31630     
31631     initEvents : function()
31632     {
31633         var _this = this;
31634         
31635         if(this.isAutoInitial){
31636             Roo.log('hook children rendered');
31637             this.on('childrenrendered', function() {
31638                 Roo.log('children rendered');
31639                 _this.initial();
31640             } ,this);
31641         }
31642         
31643     },
31644     
31645     initial : function()
31646     {
31647         this.reloadItems();
31648
31649         this.currentSize = this.el.getBox(true);
31650
31651         /// was window resize... - let's see if this works..
31652         Roo.EventManager.onWindowResize(this.resize, this); 
31653
31654         if(!this.isAutoInitial){
31655             this.layout();
31656             return;
31657         }
31658         
31659         this.layout.defer(500,this);
31660     },
31661     
31662     reloadItems: function()
31663     {
31664         this.bricks = this.el.select('.masonry-brick', true);
31665         
31666         this.bricks.each(function(b) {
31667             //Roo.log(b.getSize());
31668             if (!b.attr('originalwidth')) {
31669                 b.attr('originalwidth',  b.getSize().width);
31670             }
31671             
31672         });
31673         
31674         Roo.log(this.bricks.elements.length);
31675     },
31676     
31677     resize : function()
31678     {
31679         Roo.log('resize');
31680         var cs = this.el.getBox(true);
31681         
31682         if (this.currentSize.width == cs.width && this.currentSize.x == cs.x ) {
31683             Roo.log("no change in with or X");
31684             return;
31685         }
31686         this.currentSize = cs;
31687         this.layout();
31688     },
31689     
31690     layout : function()
31691     {
31692          Roo.log('layout');
31693         this._resetLayout();
31694         //this._manageStamps();
31695       
31696         // don't animate first layout
31697         var isInstant = this.isLayoutInstant !== undefined ? this.isLayoutInstant : !this._isLayoutInited;
31698         this.layoutItems( isInstant );
31699       
31700         // flag for initalized
31701         this._isLayoutInited = true;
31702     },
31703     
31704     layoutItems : function( isInstant )
31705     {
31706         //var items = this._getItemsForLayout( this.items );
31707         // original code supports filtering layout items.. we just ignore it..
31708         
31709         this._layoutItems( this.bricks , isInstant );
31710       
31711         this._postLayout();
31712     },
31713     _layoutItems : function ( items , isInstant)
31714     {
31715        //this.fireEvent( 'layout', this, items );
31716     
31717
31718         if ( !items || !items.elements.length ) {
31719           // no items, emit event with empty array
31720             return;
31721         }
31722
31723         var queue = [];
31724         items.each(function(item) {
31725             Roo.log("layout item");
31726             Roo.log(item);
31727             // get x/y object from method
31728             var position = this._getItemLayoutPosition( item );
31729             // enqueue
31730             position.item = item;
31731             position.isInstant = isInstant; // || item.isLayoutInstant; << not set yet...
31732             queue.push( position );
31733         }, this);
31734       
31735         this._processLayoutQueue( queue );
31736     },
31737     /** Sets position of item in DOM
31738     * @param {Element} item
31739     * @param {Number} x - horizontal position
31740     * @param {Number} y - vertical position
31741     * @param {Boolean} isInstant - disables transitions
31742     */
31743     _processLayoutQueue : function( queue )
31744     {
31745         for ( var i=0, len = queue.length; i < len; i++ ) {
31746             var obj = queue[i];
31747             obj.item.position('absolute');
31748             obj.item.setXY([obj.x,obj.y], obj.isInstant ? false : true);
31749         }
31750     },
31751       
31752     
31753     /**
31754     * Any logic you want to do after each layout,
31755     * i.e. size the container
31756     */
31757     _postLayout : function()
31758     {
31759         this.resizeContainer();
31760     },
31761     
31762     resizeContainer : function()
31763     {
31764         if ( !this.isResizingContainer ) {
31765             return;
31766         }
31767         var size = this._getContainerSize();
31768         if ( size ) {
31769             this.el.setSize(size.width,size.height);
31770             this.boxesEl.setSize(size.width,size.height);
31771         }
31772     },
31773     
31774     
31775     
31776     _resetLayout : function()
31777     {
31778         //this.getSize();  // -- does not really do anything.. it probably applies left/right etc. to obuject but not used
31779         this.colWidth = this.el.getWidth();
31780         //this.gutter = this.el.getWidth(); 
31781         
31782         this.measureColumns();
31783
31784         // reset column Y
31785         var i = this.cols;
31786         this.colYs = [];
31787         while (i--) {
31788             this.colYs.push( 0 );
31789         }
31790     
31791         this.maxY = 0;
31792     },
31793
31794     measureColumns : function()
31795     {
31796         this.getContainerWidth();
31797       // if columnWidth is 0, default to outerWidth of first item
31798         if ( !this.columnWidth ) {
31799             var firstItem = this.bricks.first();
31800             Roo.log(firstItem);
31801             this.columnWidth  = this.containerWidth;
31802             if (firstItem && firstItem.attr('originalwidth') ) {
31803                 this.columnWidth = 1* (firstItem.attr('originalwidth') || firstItem.getWidth());
31804             }
31805             // columnWidth fall back to item of first element
31806             Roo.log("set column width?");
31807                         this.initialColumnWidth = this.columnWidth  ;
31808
31809             // if first elem has no width, default to size of container
31810             
31811         }
31812         
31813         
31814         if (this.initialColumnWidth) {
31815             this.columnWidth = this.initialColumnWidth;
31816         }
31817         
31818         
31819             
31820         // column width is fixed at the top - however if container width get's smaller we should
31821         // reduce it...
31822         
31823         // this bit calcs how man columns..
31824             
31825         var columnWidth = this.columnWidth += this.gutter;
31826       
31827         // calculate columns
31828         var containerWidth = this.containerWidth + this.gutter;
31829         
31830         var cols = (containerWidth - this.padWidth) / (columnWidth - this.padWidth);
31831         // fix rounding errors, typically with gutters
31832         var excess = columnWidth - containerWidth % columnWidth;
31833         
31834         
31835         // if overshoot is less than a pixel, round up, otherwise floor it
31836         var mathMethod = excess && excess < 1 ? 'round' : 'floor';
31837         cols = Math[ mathMethod ]( cols );
31838         this.cols = Math.max( cols, 1 );
31839         this.cols = this.maxCols > 0 ? Math.min( this.cols, this.maxCols ) : this.cols;
31840         
31841          // padding positioning..
31842         var totalColWidth = this.cols * this.columnWidth;
31843         var padavail = this.containerWidth - totalColWidth;
31844         // so for 2 columns - we need 3 'pads'
31845         
31846         var padNeeded = (1+this.cols) * this.padWidth;
31847         
31848         var padExtra = Math.floor((padavail - padNeeded) / this.cols);
31849         
31850         this.columnWidth += padExtra
31851         //this.padWidth = Math.floor(padavail /  ( this.cols));
31852         
31853         // adjust colum width so that padding is fixed??
31854         
31855         // we have 3 columns ... total = width * 3
31856         // we have X left over... that should be used by 
31857         
31858         //if (this.expandC) {
31859             
31860         //}
31861         
31862         
31863         
31864     },
31865     
31866     getContainerWidth : function()
31867     {
31868        /* // container is parent if fit width
31869         var container = this.isFitWidth ? this.element.parentNode : this.element;
31870         // check that this.size and size are there
31871         // IE8 triggers resize on body size change, so they might not be
31872         
31873         var size = getSize( container );  //FIXME
31874         this.containerWidth = size && size.innerWidth; //FIXME
31875         */
31876          
31877         this.containerWidth = this.el.getBox(true).width;  //maybe use getComputedWidth
31878         
31879     },
31880     
31881     _getItemLayoutPosition : function( item )  // what is item?
31882     {
31883         // we resize the item to our columnWidth..
31884       
31885         item.setWidth(this.columnWidth);
31886         item.autoBoxAdjust  = false;
31887         
31888         var sz = item.getSize();
31889  
31890         // how many columns does this brick span
31891         var remainder = this.containerWidth % this.columnWidth;
31892         
31893         var mathMethod = remainder && remainder < 1 ? 'round' : 'ceil';
31894         // round if off by 1 pixel, otherwise use ceil
31895         var colSpan = Math[ mathMethod ]( sz.width  / this.columnWidth );
31896         colSpan = Math.min( colSpan, this.cols );
31897         
31898         // normally this should be '1' as we dont' currently allow multi width columns..
31899         
31900         var colGroup = this._getColGroup( colSpan );
31901         // get the minimum Y value from the columns
31902         var minimumY = Math.min.apply( Math, colGroup );
31903         Roo.log([ 'setHeight',  minimumY, sz.height, setHeight ]);
31904         
31905         var shortColIndex = colGroup.indexOf(  minimumY ); // broken on ie8..?? probably...
31906          
31907         // position the brick
31908         var position = {
31909             x: this.currentSize.x + (this.padWidth /2) + ((this.columnWidth + this.padWidth )* shortColIndex),
31910             y: this.currentSize.y + minimumY + this.padHeight
31911         };
31912         
31913         Roo.log(position);
31914         // apply setHeight to necessary columns
31915         var setHeight = minimumY + sz.height + this.padHeight;
31916         //Roo.log([ 'setHeight',  minimumY, sz.height, setHeight ]);
31917         
31918         var setSpan = this.cols + 1 - colGroup.length;
31919         for ( var i = 0; i < setSpan; i++ ) {
31920           this.colYs[ shortColIndex + i ] = setHeight ;
31921         }
31922       
31923         return position;
31924     },
31925     
31926     /**
31927      * @param {Number} colSpan - number of columns the element spans
31928      * @returns {Array} colGroup
31929      */
31930     _getColGroup : function( colSpan )
31931     {
31932         if ( colSpan < 2 ) {
31933           // if brick spans only one column, use all the column Ys
31934           return this.colYs;
31935         }
31936       
31937         var colGroup = [];
31938         // how many different places could this brick fit horizontally
31939         var groupCount = this.cols + 1 - colSpan;
31940         // for each group potential horizontal position
31941         for ( var i = 0; i < groupCount; i++ ) {
31942           // make an array of colY values for that one group
31943           var groupColYs = this.colYs.slice( i, i + colSpan );
31944           // and get the max value of the array
31945           colGroup[i] = Math.max.apply( Math, groupColYs );
31946         }
31947         return colGroup;
31948     },
31949     /*
31950     _manageStamp : function( stamp )
31951     {
31952         var stampSize =  stamp.getSize();
31953         var offset = stamp.getBox();
31954         // get the columns that this stamp affects
31955         var firstX = this.isOriginLeft ? offset.x : offset.right;
31956         var lastX = firstX + stampSize.width;
31957         var firstCol = Math.floor( firstX / this.columnWidth );
31958         firstCol = Math.max( 0, firstCol );
31959         
31960         var lastCol = Math.floor( lastX / this.columnWidth );
31961         // lastCol should not go over if multiple of columnWidth #425
31962         lastCol -= lastX % this.columnWidth ? 0 : 1;
31963         lastCol = Math.min( this.cols - 1, lastCol );
31964         
31965         // set colYs to bottom of the stamp
31966         var stampMaxY = ( this.isOriginTop ? offset.y : offset.bottom ) +
31967             stampSize.height;
31968             
31969         for ( var i = firstCol; i <= lastCol; i++ ) {
31970           this.colYs[i] = Math.max( stampMaxY, this.colYs[i] );
31971         }
31972     },
31973     */
31974     
31975     _getContainerSize : function()
31976     {
31977         this.maxY = Math.max.apply( Math, this.colYs );
31978         var size = {
31979             height: this.maxY
31980         };
31981       
31982         if ( this.isFitWidth ) {
31983             size.width = this._getContainerFitWidth();
31984         }
31985       
31986         return size;
31987     },
31988     
31989     _getContainerFitWidth : function()
31990     {
31991         var unusedCols = 0;
31992         // count unused columns
31993         var i = this.cols;
31994         while ( --i ) {
31995           if ( this.colYs[i] !== 0 ) {
31996             break;
31997           }
31998           unusedCols++;
31999         }
32000         // fit container to columns that have been used
32001         return ( this.cols - unusedCols ) * this.columnWidth - this.gutter;
32002     },
32003     
32004     needsResizeLayout : function()
32005     {
32006         var previousWidth = this.containerWidth;
32007         this.getContainerWidth();
32008         return previousWidth !== this.containerWidth;
32009     }
32010  
32011 });
32012
32013  
32014
32015  /*
32016  * - LGPL
32017  *
32018  * element
32019  * 
32020  */
32021
32022 /**
32023  * @class Roo.bootstrap.MasonryBrick
32024  * @extends Roo.bootstrap.Component
32025  * Bootstrap MasonryBrick class
32026  * 
32027  * @constructor
32028  * Create a new MasonryBrick
32029  * @param {Object} config The config object
32030  */
32031
32032 Roo.bootstrap.MasonryBrick = function(config){
32033     
32034     Roo.bootstrap.MasonryBrick.superclass.constructor.call(this, config);
32035     
32036     Roo.bootstrap.MasonryBrick.register(this);
32037     
32038     this.addEvents({
32039         // raw events
32040         /**
32041          * @event click
32042          * When a MasonryBrick is clcik
32043          * @param {Roo.bootstrap.MasonryBrick} this
32044          * @param {Roo.EventObject} e
32045          */
32046         "click" : true
32047     });
32048 };
32049
32050 Roo.extend(Roo.bootstrap.MasonryBrick, Roo.bootstrap.Component,  {
32051     
32052     /**
32053      * @cfg {String} title
32054      */   
32055     title : '',
32056     /**
32057      * @cfg {String} html
32058      */   
32059     html : '',
32060     /**
32061      * @cfg {String} bgimage
32062      */   
32063     bgimage : '',
32064     /**
32065      * @cfg {String} videourl
32066      */   
32067     videourl : '',
32068     /**
32069      * @cfg {String} cls
32070      */   
32071     cls : '',
32072     /**
32073      * @cfg {String} href
32074      */   
32075     href : '',
32076     /**
32077      * @cfg {String} size (xs|sm|md|md-left|md-right|tall|wide)
32078      */   
32079     size : 'xs',
32080     
32081     /**
32082      * @cfg {String} placetitle (center|bottom)
32083      */   
32084     placetitle : '',
32085     
32086     /**
32087      * @cfg {Boolean} isFitContainer defalut true
32088      */   
32089     isFitContainer : true, 
32090     
32091     /**
32092      * @cfg {Boolean} preventDefault defalut false
32093      */   
32094     preventDefault : false, 
32095     
32096     /**
32097      * @cfg {Boolean} inverse defalut false
32098      */   
32099     maskInverse : false, 
32100     
32101     getAutoCreate : function()
32102     {
32103         if(!this.isFitContainer){
32104             return this.getSplitAutoCreate();
32105         }
32106         
32107         var cls = 'masonry-brick masonry-brick-full';
32108         
32109         if(this.href.length){
32110             cls += ' masonry-brick-link';
32111         }
32112         
32113         if(this.bgimage.length){
32114             cls += ' masonry-brick-image';
32115         }
32116         
32117         if(this.maskInverse){
32118             cls += ' mask-inverse';
32119         }
32120         
32121         if(!this.html.length && !this.maskInverse && !this.videourl.length){
32122             cls += ' enable-mask';
32123         }
32124         
32125         if(this.size){
32126             cls += ' masonry-' + this.size + '-brick';
32127         }
32128         
32129         if(this.placetitle.length){
32130             
32131             switch (this.placetitle) {
32132                 case 'center' :
32133                     cls += ' masonry-center-title';
32134                     break;
32135                 case 'bottom' :
32136                     cls += ' masonry-bottom-title';
32137                     break;
32138                 default:
32139                     break;
32140             }
32141             
32142         } else {
32143             if(!this.html.length && !this.bgimage.length){
32144                 cls += ' masonry-center-title';
32145             }
32146
32147             if(!this.html.length && this.bgimage.length){
32148                 cls += ' masonry-bottom-title';
32149             }
32150         }
32151         
32152         if(this.cls){
32153             cls += ' ' + this.cls;
32154         }
32155         
32156         var cfg = {
32157             tag: (this.href.length) ? 'a' : 'div',
32158             cls: cls,
32159             cn: [
32160                 {
32161                     tag: 'div',
32162                     cls: 'masonry-brick-mask'
32163                 },
32164                 {
32165                     tag: 'div',
32166                     cls: 'masonry-brick-paragraph',
32167                     cn: []
32168                 }
32169             ]
32170         };
32171         
32172         if(this.href.length){
32173             cfg.href = this.href;
32174         }
32175         
32176         var cn = cfg.cn[1].cn;
32177         
32178         if(this.title.length){
32179             cn.push({
32180                 tag: 'h4',
32181                 cls: 'masonry-brick-title',
32182                 html: this.title
32183             });
32184         }
32185         
32186         if(this.html.length){
32187             cn.push({
32188                 tag: 'p',
32189                 cls: 'masonry-brick-text',
32190                 html: this.html
32191             });
32192         }
32193         
32194         if (!this.title.length && !this.html.length) {
32195             cfg.cn[1].cls += ' hide';
32196         }
32197         
32198         if(this.bgimage.length){
32199             cfg.cn.push({
32200                 tag: 'img',
32201                 cls: 'masonry-brick-image-view',
32202                 src: this.bgimage
32203             });
32204         }
32205         
32206         if(this.videourl.length){
32207             var vurl = this.videourl.replace(/https:\/\/youtu\.be/, 'https://www.youtube.com/embed/');
32208             // youtube support only?
32209             cfg.cn.push({
32210                 tag: 'iframe',
32211                 cls: 'masonry-brick-image-view',
32212                 src: vurl,
32213                 frameborder : 0,
32214                 allowfullscreen : true
32215             });
32216         }
32217         
32218         return cfg;
32219         
32220     },
32221     
32222     getSplitAutoCreate : function()
32223     {
32224         var cls = 'masonry-brick masonry-brick-split';
32225         
32226         if(this.href.length){
32227             cls += ' masonry-brick-link';
32228         }
32229         
32230         if(this.bgimage.length){
32231             cls += ' masonry-brick-image';
32232         }
32233         
32234         if(this.size){
32235             cls += ' masonry-' + this.size + '-brick';
32236         }
32237         
32238         switch (this.placetitle) {
32239             case 'center' :
32240                 cls += ' masonry-center-title';
32241                 break;
32242             case 'bottom' :
32243                 cls += ' masonry-bottom-title';
32244                 break;
32245             default:
32246                 if(!this.bgimage.length){
32247                     cls += ' masonry-center-title';
32248                 }
32249
32250                 if(this.bgimage.length){
32251                     cls += ' masonry-bottom-title';
32252                 }
32253                 break;
32254         }
32255         
32256         if(this.cls){
32257             cls += ' ' + this.cls;
32258         }
32259         
32260         var cfg = {
32261             tag: (this.href.length) ? 'a' : 'div',
32262             cls: cls,
32263             cn: [
32264                 {
32265                     tag: 'div',
32266                     cls: 'masonry-brick-split-head',
32267                     cn: [
32268                         {
32269                             tag: 'div',
32270                             cls: 'masonry-brick-paragraph',
32271                             cn: []
32272                         }
32273                     ]
32274                 },
32275                 {
32276                     tag: 'div',
32277                     cls: 'masonry-brick-split-body',
32278                     cn: []
32279                 }
32280             ]
32281         };
32282         
32283         if(this.href.length){
32284             cfg.href = this.href;
32285         }
32286         
32287         if(this.title.length){
32288             cfg.cn[0].cn[0].cn.push({
32289                 tag: 'h4',
32290                 cls: 'masonry-brick-title',
32291                 html: this.title
32292             });
32293         }
32294         
32295         if(this.html.length){
32296             cfg.cn[1].cn.push({
32297                 tag: 'p',
32298                 cls: 'masonry-brick-text',
32299                 html: this.html
32300             });
32301         }
32302
32303         if(this.bgimage.length){
32304             cfg.cn[0].cn.push({
32305                 tag: 'img',
32306                 cls: 'masonry-brick-image-view',
32307                 src: this.bgimage
32308             });
32309         }
32310         
32311         if(this.videourl.length){
32312             var vurl = this.videourl.replace(/https:\/\/youtu\.be/, 'https://www.youtube.com/embed/');
32313             // youtube support only?
32314             cfg.cn[0].cn.cn.push({
32315                 tag: 'iframe',
32316                 cls: 'masonry-brick-image-view',
32317                 src: vurl,
32318                 frameborder : 0,
32319                 allowfullscreen : true
32320             });
32321         }
32322         
32323         return cfg;
32324     },
32325     
32326     initEvents: function() 
32327     {
32328         switch (this.size) {
32329             case 'xs' :
32330                 this.x = 1;
32331                 this.y = 1;
32332                 break;
32333             case 'sm' :
32334                 this.x = 2;
32335                 this.y = 2;
32336                 break;
32337             case 'md' :
32338             case 'md-left' :
32339             case 'md-right' :
32340                 this.x = 3;
32341                 this.y = 3;
32342                 break;
32343             case 'tall' :
32344                 this.x = 2;
32345                 this.y = 3;
32346                 break;
32347             case 'wide' :
32348                 this.x = 3;
32349                 this.y = 2;
32350                 break;
32351             case 'wide-thin' :
32352                 this.x = 3;
32353                 this.y = 1;
32354                 break;
32355                         
32356             default :
32357                 break;
32358         }
32359         
32360         if(Roo.isTouch){
32361             this.el.on('touchstart', this.onTouchStart, this);
32362             this.el.on('touchmove', this.onTouchMove, this);
32363             this.el.on('touchend', this.onTouchEnd, this);
32364             this.el.on('contextmenu', this.onContextMenu, this);
32365         } else {
32366             this.el.on('mouseenter'  ,this.enter, this);
32367             this.el.on('mouseleave', this.leave, this);
32368             this.el.on('click', this.onClick, this);
32369         }
32370         
32371         if (typeof(this.parent().bricks) == 'object' && this.parent().bricks != null) {
32372             this.parent().bricks.push(this);   
32373         }
32374         
32375     },
32376     
32377     onClick: function(e, el)
32378     {
32379         var time = this.endTimer - this.startTimer;
32380         // Roo.log(e.preventDefault());
32381         if(Roo.isTouch){
32382             if(time > 1000){
32383                 e.preventDefault();
32384                 return;
32385             }
32386         }
32387         
32388         if(!this.preventDefault){
32389             return;
32390         }
32391         
32392         e.preventDefault();
32393         
32394         if (this.activcClass != '') {
32395             this.selectBrick();
32396         }
32397         
32398         this.fireEvent('click', this);
32399     },
32400     
32401     enter: function(e, el)
32402     {
32403         e.preventDefault();
32404         
32405         if(!this.isFitContainer || this.maskInverse || this.videourl.length){
32406             return;
32407         }
32408         
32409         if(this.bgimage.length && this.html.length){
32410             this.el.select('.masonry-brick-paragraph', true).first().setOpacity(0.9, true);
32411         }
32412     },
32413     
32414     leave: function(e, el)
32415     {
32416         e.preventDefault();
32417         
32418         if(!this.isFitContainer || this.maskInverse  || this.videourl.length){
32419             return;
32420         }
32421         
32422         if(this.bgimage.length && this.html.length){
32423             this.el.select('.masonry-brick-paragraph', true).first().setOpacity(0, true);
32424         }
32425     },
32426     
32427     onTouchStart: function(e, el)
32428     {
32429 //        e.preventDefault();
32430         
32431         this.touchmoved = false;
32432         
32433         if(!this.isFitContainer){
32434             return;
32435         }
32436         
32437         if(!this.bgimage.length || !this.html.length){
32438             return;
32439         }
32440         
32441         this.el.select('.masonry-brick-paragraph', true).first().setOpacity(0.9, true);
32442         
32443         this.timer = new Date().getTime();
32444         
32445     },
32446     
32447     onTouchMove: function(e, el)
32448     {
32449         this.touchmoved = true;
32450     },
32451     
32452     onContextMenu : function(e,el)
32453     {
32454         e.preventDefault();
32455         e.stopPropagation();
32456         return false;
32457     },
32458     
32459     onTouchEnd: function(e, el)
32460     {
32461 //        e.preventDefault();
32462         
32463         if((new Date().getTime() - this.timer > 1000) || !this.href.length || this.touchmoved){
32464         
32465             this.leave(e,el);
32466             
32467             return;
32468         }
32469         
32470         if(!this.bgimage.length || !this.html.length){
32471             
32472             if(this.href.length){
32473                 window.location.href = this.href;
32474             }
32475             
32476             return;
32477         }
32478         
32479         if(!this.isFitContainer){
32480             return;
32481         }
32482         
32483         this.el.select('.masonry-brick-paragraph', true).first().setOpacity(0, true);
32484         
32485         window.location.href = this.href;
32486     },
32487     
32488     //selection on single brick only
32489     selectBrick : function() {
32490         
32491         if (!this.parentId) {
32492             return;
32493         }
32494         
32495         var m = Roo.bootstrap.LayoutMasonry.get(this.parentId);
32496         var index = m.selectedBrick.indexOf(this.id);
32497         
32498         if ( index > -1) {
32499             m.selectedBrick.splice(index,1);
32500             this.el.removeClass(this.activeClass);
32501             return;
32502         }
32503         
32504         for(var i = 0; i < m.selectedBrick.length; i++) {
32505             var b = Roo.bootstrap.MasonryBrick.get(m.selectedBrick[i]);
32506             b.el.removeClass(b.activeClass);
32507         }
32508         
32509         m.selectedBrick = [];
32510         
32511         m.selectedBrick.push(this.id);
32512         this.el.addClass(this.activeClass);
32513         return;
32514     }
32515     
32516 });
32517
32518 Roo.apply(Roo.bootstrap.MasonryBrick, {
32519     
32520     //groups: {},
32521     groups : new Roo.util.MixedCollection(false, function(o) { return o.el.id; }),
32522      /**
32523     * register a Masonry Brick
32524     * @param {Roo.bootstrap.MasonryBrick} the masonry brick to add
32525     */
32526     
32527     register : function(brick)
32528     {
32529         //this.groups[brick.id] = brick;
32530         this.groups.add(brick.id, brick);
32531     },
32532     /**
32533     * fetch a  masonry brick based on the masonry brick ID
32534     * @param {string} the masonry brick to add
32535     * @returns {Roo.bootstrap.MasonryBrick} the masonry brick
32536     */
32537     
32538     get: function(brick_id) 
32539     {
32540         // if (typeof(this.groups[brick_id]) == 'undefined') {
32541         //     return false;
32542         // }
32543         // return this.groups[brick_id] ;
32544         
32545         if(this.groups.key(brick_id)) {
32546             return this.groups.key(brick_id);
32547         }
32548         
32549         return false;
32550     }
32551     
32552     
32553     
32554 });
32555
32556  /*
32557  * - LGPL
32558  *
32559  * element
32560  * 
32561  */
32562
32563 /**
32564  * @class Roo.bootstrap.Brick
32565  * @extends Roo.bootstrap.Component
32566  * Bootstrap Brick class
32567  * 
32568  * @constructor
32569  * Create a new Brick
32570  * @param {Object} config The config object
32571  */
32572
32573 Roo.bootstrap.Brick = function(config){
32574     Roo.bootstrap.Brick.superclass.constructor.call(this, config);
32575     
32576     this.addEvents({
32577         // raw events
32578         /**
32579          * @event click
32580          * When a Brick is click
32581          * @param {Roo.bootstrap.Brick} this
32582          * @param {Roo.EventObject} e
32583          */
32584         "click" : true
32585     });
32586 };
32587
32588 Roo.extend(Roo.bootstrap.Brick, Roo.bootstrap.Component,  {
32589     
32590     /**
32591      * @cfg {String} title
32592      */   
32593     title : '',
32594     /**
32595      * @cfg {String} html
32596      */   
32597     html : '',
32598     /**
32599      * @cfg {String} bgimage
32600      */   
32601     bgimage : '',
32602     /**
32603      * @cfg {String} cls
32604      */   
32605     cls : '',
32606     /**
32607      * @cfg {String} href
32608      */   
32609     href : '',
32610     /**
32611      * @cfg {String} video
32612      */   
32613     video : '',
32614     /**
32615      * @cfg {Boolean} square
32616      */   
32617     square : true,
32618     
32619     getAutoCreate : function()
32620     {
32621         var cls = 'roo-brick';
32622         
32623         if(this.href.length){
32624             cls += ' roo-brick-link';
32625         }
32626         
32627         if(this.bgimage.length){
32628             cls += ' roo-brick-image';
32629         }
32630         
32631         if(!this.html.length && !this.bgimage.length){
32632             cls += ' roo-brick-center-title';
32633         }
32634         
32635         if(!this.html.length && this.bgimage.length){
32636             cls += ' roo-brick-bottom-title';
32637         }
32638         
32639         if(this.cls){
32640             cls += ' ' + this.cls;
32641         }
32642         
32643         var cfg = {
32644             tag: (this.href.length) ? 'a' : 'div',
32645             cls: cls,
32646             cn: [
32647                 {
32648                     tag: 'div',
32649                     cls: 'roo-brick-paragraph',
32650                     cn: []
32651                 }
32652             ]
32653         };
32654         
32655         if(this.href.length){
32656             cfg.href = this.href;
32657         }
32658         
32659         var cn = cfg.cn[0].cn;
32660         
32661         if(this.title.length){
32662             cn.push({
32663                 tag: 'h4',
32664                 cls: 'roo-brick-title',
32665                 html: this.title
32666             });
32667         }
32668         
32669         if(this.html.length){
32670             cn.push({
32671                 tag: 'p',
32672                 cls: 'roo-brick-text',
32673                 html: this.html
32674             });
32675         } else {
32676             cn.cls += ' hide';
32677         }
32678         
32679         if(this.bgimage.length){
32680             cfg.cn.push({
32681                 tag: 'img',
32682                 cls: 'roo-brick-image-view',
32683                 src: this.bgimage
32684             });
32685         }
32686         
32687         return cfg;
32688     },
32689     
32690     initEvents: function() 
32691     {
32692         if(this.title.length || this.html.length){
32693             this.el.on('mouseenter'  ,this.enter, this);
32694             this.el.on('mouseleave', this.leave, this);
32695         }
32696         
32697         Roo.EventManager.onWindowResize(this.resize, this); 
32698         
32699         if(this.bgimage.length){
32700             this.imageEl = this.el.select('.roo-brick-image-view', true).first();
32701             this.imageEl.on('load', this.onImageLoad, this);
32702             return;
32703         }
32704         
32705         this.resize();
32706     },
32707     
32708     onImageLoad : function()
32709     {
32710         this.resize();
32711     },
32712     
32713     resize : function()
32714     {
32715         var paragraph = this.el.select('.roo-brick-paragraph', true).first();
32716         
32717         paragraph.setHeight(paragraph.getWidth() + paragraph.getPadding('tb'));
32718         
32719         if(this.bgimage.length){
32720             var image = this.el.select('.roo-brick-image-view', true).first();
32721             
32722             image.setWidth(paragraph.getWidth());
32723             
32724             if(this.square){
32725                 image.setHeight(paragraph.getWidth());
32726             }
32727             
32728             this.el.setHeight(image.getHeight());
32729             paragraph.setHeight(image.getHeight());
32730             
32731         }
32732         
32733     },
32734     
32735     enter: function(e, el)
32736     {
32737         e.preventDefault();
32738         
32739         if(this.bgimage.length){
32740             this.el.select('.roo-brick-paragraph', true).first().setOpacity(0.9, true);
32741             this.el.select('.roo-brick-image-view', true).first().setOpacity(0.1, true);
32742         }
32743     },
32744     
32745     leave: function(e, el)
32746     {
32747         e.preventDefault();
32748         
32749         if(this.bgimage.length){
32750             this.el.select('.roo-brick-paragraph', true).first().setOpacity(0, true);
32751             this.el.select('.roo-brick-image-view', true).first().setOpacity(1, true);
32752         }
32753     }
32754     
32755 });
32756
32757  
32758
32759  /*
32760  * - LGPL
32761  *
32762  * Input
32763  * 
32764  */
32765
32766 /**
32767  * @class Roo.bootstrap.NumberField
32768  * @extends Roo.bootstrap.Input
32769  * Bootstrap NumberField class
32770  * 
32771  * 
32772  * 
32773  * 
32774  * @constructor
32775  * Create a new NumberField
32776  * @param {Object} config The config object
32777  */
32778
32779 Roo.bootstrap.NumberField = function(config){
32780     Roo.bootstrap.NumberField.superclass.constructor.call(this, config);
32781 };
32782
32783 Roo.extend(Roo.bootstrap.NumberField, Roo.bootstrap.Input, {
32784     
32785     /**
32786      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
32787      */
32788     allowDecimals : true,
32789     /**
32790      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
32791      */
32792     decimalSeparator : ".",
32793     /**
32794      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
32795      */
32796     decimalPrecision : 2,
32797     /**
32798      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
32799      */
32800     allowNegative : true,
32801     /**
32802      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
32803      */
32804     minValue : Number.NEGATIVE_INFINITY,
32805     /**
32806      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
32807      */
32808     maxValue : Number.MAX_VALUE,
32809     /**
32810      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
32811      */
32812     minText : "The minimum value for this field is {0}",
32813     /**
32814      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
32815      */
32816     maxText : "The maximum value for this field is {0}",
32817     /**
32818      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
32819      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
32820      */
32821     nanText : "{0} is not a valid number",
32822     /**
32823      * @cfg {Boolean} castInt (true|false) cast int if true (defalut true)
32824      */
32825     castInt : true,
32826
32827     // private
32828     initEvents : function()
32829     {   
32830         Roo.bootstrap.NumberField.superclass.initEvents.call(this);
32831         
32832         var allowed = "0123456789";
32833         
32834         if(this.allowDecimals){
32835             allowed += this.decimalSeparator;
32836         }
32837         
32838         if(this.allowNegative){
32839             allowed += "-";
32840         }
32841         
32842         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
32843         
32844         var keyPress = function(e){
32845             
32846             var k = e.getKey();
32847             
32848             var c = e.getCharCode();
32849             
32850             if(
32851                     (String.fromCharCode(c) == '.' || String.fromCharCode(c) == '-') &&
32852                     allowed.indexOf(String.fromCharCode(c)) === -1
32853             ){
32854                 e.stopEvent();
32855                 return;
32856             }
32857             
32858             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
32859                 return;
32860             }
32861             
32862             if(allowed.indexOf(String.fromCharCode(c)) === -1){
32863                 e.stopEvent();
32864             }
32865         };
32866         
32867         this.el.on("keypress", keyPress, this);
32868     },
32869     
32870     validateValue : function(value)
32871     {
32872         
32873         if(!Roo.bootstrap.NumberField.superclass.validateValue.call(this, value)){
32874             return false;
32875         }
32876         
32877         var num = this.parseValue(value);
32878         
32879         if(isNaN(num)){
32880             this.markInvalid(String.format(this.nanText, value));
32881             return false;
32882         }
32883         
32884         if(num < this.minValue){
32885             this.markInvalid(String.format(this.minText, this.minValue));
32886             return false;
32887         }
32888         
32889         if(num > this.maxValue){
32890             this.markInvalid(String.format(this.maxText, this.maxValue));
32891             return false;
32892         }
32893         
32894         return true;
32895     },
32896
32897     getValue : function()
32898     {
32899         return this.fixPrecision(this.parseValue(Roo.bootstrap.NumberField.superclass.getValue.call(this)));
32900     },
32901
32902     parseValue : function(value)
32903     {
32904         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
32905         return isNaN(value) ? '' : value;
32906     },
32907
32908     fixPrecision : function(value)
32909     {
32910         var nan = isNaN(value);
32911         
32912         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
32913             return nan ? '' : value;
32914         }
32915         return parseFloat(value).toFixed(this.decimalPrecision);
32916     },
32917
32918     setValue : function(v)
32919     {
32920         v = this.fixPrecision(v);
32921         Roo.bootstrap.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
32922     },
32923
32924     decimalPrecisionFcn : function(v)
32925     {
32926         return Math.floor(v);
32927     },
32928
32929     beforeBlur : function()
32930     {
32931         if(!this.castInt){
32932             return;
32933         }
32934         
32935         var v = this.parseValue(this.getRawValue());
32936         if(v){
32937             this.setValue(v);
32938         }
32939     }
32940     
32941 });
32942
32943  
32944
32945 /*
32946 * Licence: LGPL
32947 */
32948
32949 /**
32950  * @class Roo.bootstrap.DocumentSlider
32951  * @extends Roo.bootstrap.Component
32952  * Bootstrap DocumentSlider class
32953  * 
32954  * @constructor
32955  * Create a new DocumentViewer
32956  * @param {Object} config The config object
32957  */
32958
32959 Roo.bootstrap.DocumentSlider = function(config){
32960     Roo.bootstrap.DocumentSlider.superclass.constructor.call(this, config);
32961     
32962     this.files = [];
32963     
32964     this.addEvents({
32965         /**
32966          * @event initial
32967          * Fire after initEvent
32968          * @param {Roo.bootstrap.DocumentSlider} this
32969          */
32970         "initial" : true,
32971         /**
32972          * @event update
32973          * Fire after update
32974          * @param {Roo.bootstrap.DocumentSlider} this
32975          */
32976         "update" : true,
32977         /**
32978          * @event click
32979          * Fire after click
32980          * @param {Roo.bootstrap.DocumentSlider} this
32981          */
32982         "click" : true
32983     });
32984 };
32985
32986 Roo.extend(Roo.bootstrap.DocumentSlider, Roo.bootstrap.Component,  {
32987     
32988     files : false,
32989     
32990     indicator : 0,
32991     
32992     getAutoCreate : function()
32993     {
32994         var cfg = {
32995             tag : 'div',
32996             cls : 'roo-document-slider',
32997             cn : [
32998                 {
32999                     tag : 'div',
33000                     cls : 'roo-document-slider-header',
33001                     cn : [
33002                         {
33003                             tag : 'div',
33004                             cls : 'roo-document-slider-header-title'
33005                         }
33006                     ]
33007                 },
33008                 {
33009                     tag : 'div',
33010                     cls : 'roo-document-slider-body',
33011                     cn : [
33012                         {
33013                             tag : 'div',
33014                             cls : 'roo-document-slider-prev',
33015                             cn : [
33016                                 {
33017                                     tag : 'i',
33018                                     cls : 'fa fa-chevron-left'
33019                                 }
33020                             ]
33021                         },
33022                         {
33023                             tag : 'div',
33024                             cls : 'roo-document-slider-thumb',
33025                             cn : [
33026                                 {
33027                                     tag : 'img',
33028                                     cls : 'roo-document-slider-image'
33029                                 }
33030                             ]
33031                         },
33032                         {
33033                             tag : 'div',
33034                             cls : 'roo-document-slider-next',
33035                             cn : [
33036                                 {
33037                                     tag : 'i',
33038                                     cls : 'fa fa-chevron-right'
33039                                 }
33040                             ]
33041                         }
33042                     ]
33043                 }
33044             ]
33045         };
33046         
33047         return cfg;
33048     },
33049     
33050     initEvents : function()
33051     {
33052         this.headerEl = this.el.select('.roo-document-slider-header', true).first();
33053         this.headerEl.setVisibilityMode(Roo.Element.DISPLAY);
33054         
33055         this.titleEl = this.el.select('.roo-document-slider-header .roo-document-slider-header-title', true).first();
33056         this.titleEl.setVisibilityMode(Roo.Element.DISPLAY);
33057         
33058         this.bodyEl = this.el.select('.roo-document-slider-body', true).first();
33059         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY);
33060         
33061         this.thumbEl = this.el.select('.roo-document-slider-thumb', true).first();
33062         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY);
33063         
33064         this.imageEl = this.el.select('.roo-document-slider-image', true).first();
33065         this.imageEl.setVisibilityMode(Roo.Element.DISPLAY);
33066         
33067         this.prevIndicator = this.el.select('.roo-document-slider-prev i', true).first();
33068         this.prevIndicator.setVisibilityMode(Roo.Element.DISPLAY);
33069         
33070         this.nextIndicator = this.el.select('.roo-document-slider-next i', true).first();
33071         this.nextIndicator.setVisibilityMode(Roo.Element.DISPLAY);
33072         
33073         this.thumbEl.on('click', this.onClick, this);
33074         
33075         this.prevIndicator.on('click', this.prev, this);
33076         
33077         this.nextIndicator.on('click', this.next, this);
33078         
33079     },
33080     
33081     initial : function()
33082     {
33083         if(this.files.length){
33084             this.indicator = 1;
33085             this.update()
33086         }
33087         
33088         this.fireEvent('initial', this);
33089     },
33090     
33091     update : function()
33092     {
33093         this.imageEl.attr('src', this.files[this.indicator - 1]);
33094         
33095         this.titleEl.dom.innerHTML = String.format('{0} / {1}', this.indicator, this.files.length);
33096         
33097         this.prevIndicator.show();
33098         
33099         if(this.indicator == 1){
33100             this.prevIndicator.hide();
33101         }
33102         
33103         this.nextIndicator.show();
33104         
33105         if(this.indicator == this.files.length){
33106             this.nextIndicator.hide();
33107         }
33108         
33109         this.thumbEl.scrollTo('top');
33110         
33111         this.fireEvent('update', this);
33112     },
33113     
33114     onClick : function(e)
33115     {
33116         e.preventDefault();
33117         
33118         this.fireEvent('click', this);
33119     },
33120     
33121     prev : function(e)
33122     {
33123         e.preventDefault();
33124         
33125         this.indicator = Math.max(1, this.indicator - 1);
33126         
33127         this.update();
33128     },
33129     
33130     next : function(e)
33131     {
33132         e.preventDefault();
33133         
33134         this.indicator = Math.min(this.files.length, this.indicator + 1);
33135         
33136         this.update();
33137     }
33138 });
33139 /*
33140  * - LGPL
33141  *
33142  * RadioSet
33143  *
33144  *
33145  */
33146
33147 /**
33148  * @class Roo.bootstrap.RadioSet
33149  * @extends Roo.bootstrap.Input
33150  * Bootstrap RadioSet class
33151  * @cfg {String} indicatorpos (left|right) default left
33152  * @cfg {Boolean} inline (true|false) inline the element (default true)
33153  * @cfg {String} weight (primary|warning|info|danger|success) The text that appears beside the radio
33154  * @constructor
33155  * Create a new RadioSet
33156  * @param {Object} config The config object
33157  */
33158
33159 Roo.bootstrap.RadioSet = function(config){
33160     
33161     Roo.bootstrap.RadioSet.superclass.constructor.call(this, config);
33162     
33163     this.radioes = [];
33164     
33165     Roo.bootstrap.RadioSet.register(this);
33166     
33167     this.addEvents({
33168         /**
33169         * @event check
33170         * Fires when the element is checked or unchecked.
33171         * @param {Roo.bootstrap.RadioSet} this This radio
33172         * @param {Roo.bootstrap.Radio} item The checked item
33173         */
33174        check : true
33175     });
33176     
33177 };
33178
33179 Roo.extend(Roo.bootstrap.RadioSet, Roo.bootstrap.Input,  {
33180
33181     radioes : false,
33182     
33183     inline : true,
33184     
33185     weight : '',
33186     
33187     indicatorpos : 'left',
33188     
33189     getAutoCreate : function()
33190     {
33191         var label = {
33192             tag : 'label',
33193             cls : 'roo-radio-set-label',
33194             cn : [
33195                 {
33196                     tag : 'span',
33197                     html : this.fieldLabel
33198                 }
33199             ]
33200         };
33201         
33202         if(this.indicatorpos == 'left'){
33203             label.cn.unshift({
33204                 tag : 'i',
33205                 cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
33206                 tooltip : 'This field is required'
33207             });
33208         } else {
33209             label.cn.push({
33210                 tag : 'i',
33211                 cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
33212                 tooltip : 'This field is required'
33213             });
33214         }
33215         
33216         var items = {
33217             tag : 'div',
33218             cls : 'roo-radio-set-items'
33219         };
33220         
33221         var align = (!this.labelAlign) ? this.parentLabelAlign() : this.labelAlign;
33222         
33223         if (align === 'left' && this.fieldLabel.length) {
33224             
33225             items = {
33226                 cls : "roo-radio-set-right", 
33227                 cn: [
33228                     items
33229                 ]
33230             };
33231             
33232             if(this.labelWidth > 12){
33233                 label.style = "width: " + this.labelWidth + 'px';
33234             }
33235             
33236             if(this.labelWidth < 13 && this.labelmd == 0){
33237                 this.labelmd = this.labelWidth;
33238             }
33239             
33240             if(this.labellg > 0){
33241                 label.cls += ' col-lg-' + this.labellg;
33242                 items.cls += ' col-lg-' + (12 - this.labellg);
33243             }
33244             
33245             if(this.labelmd > 0){
33246                 label.cls += ' col-md-' + this.labelmd;
33247                 items.cls += ' col-md-' + (12 - this.labelmd);
33248             }
33249             
33250             if(this.labelsm > 0){
33251                 label.cls += ' col-sm-' + this.labelsm;
33252                 items.cls += ' col-sm-' + (12 - this.labelsm);
33253             }
33254             
33255             if(this.labelxs > 0){
33256                 label.cls += ' col-xs-' + this.labelxs;
33257                 items.cls += ' col-xs-' + (12 - this.labelxs);
33258             }
33259         }
33260         
33261         var cfg = {
33262             tag : 'div',
33263             cls : 'roo-radio-set',
33264             cn : [
33265                 {
33266                     tag : 'input',
33267                     cls : 'roo-radio-set-input',
33268                     type : 'hidden',
33269                     name : this.name,
33270                     value : this.value ? this.value :  ''
33271                 },
33272                 label,
33273                 items
33274             ]
33275         };
33276         
33277         if(this.weight.length){
33278             cfg.cls += ' roo-radio-' + this.weight;
33279         }
33280         
33281         if(this.inline) {
33282             cfg.cls += ' roo-radio-set-inline';
33283         }
33284         
33285         return cfg;
33286         
33287     },
33288
33289     initEvents : function()
33290     {
33291         this.labelEl = this.el.select('.roo-radio-set-label', true).first();
33292         this.labelEl.setVisibilityMode(Roo.Element.DISPLAY);
33293         
33294         if(!this.fieldLabel.length){
33295             this.labelEl.hide();
33296         }
33297         
33298         this.itemsEl = this.el.select('.roo-radio-set-items', true).first();
33299         this.itemsEl.setVisibilityMode(Roo.Element.DISPLAY);
33300         
33301         this.indicatorEl().setVisibilityMode(Roo.Element.DISPLAY);
33302         this.indicatorEl().hide();
33303         
33304         this.originalValue = this.getValue();
33305         
33306     },
33307     
33308     inputEl: function ()
33309     {
33310         return this.el.select('.roo-radio-set-input', true).first();
33311     },
33312     
33313     getChildContainer : function()
33314     {
33315         return this.itemsEl;
33316     },
33317     
33318     register : function(item)
33319     {
33320         this.radioes.push(item);
33321         
33322     },
33323     
33324     validate : function()
33325     {   
33326         var valid = false;
33327         
33328         Roo.each(this.radioes, function(i){
33329             if(!i.checked){
33330                 return;
33331             }
33332             
33333             valid = true;
33334             return false;
33335         });
33336         
33337         if(this.allowBlank) {
33338             return true;
33339         }
33340         
33341         if(this.disabled || valid){
33342             this.markValid();
33343             return true;
33344         }
33345         
33346         this.markInvalid();
33347         return false;
33348         
33349     },
33350     
33351     markValid : function()
33352     {
33353         if(this.labelEl.isVisible(true)){
33354             this.indicatorEl().hide();
33355         }
33356         
33357         this.el.removeClass([this.invalidClass, this.validClass]);
33358         this.el.addClass(this.validClass);
33359         
33360         this.fireEvent('valid', this);
33361     },
33362     
33363     markInvalid : function(msg)
33364     {
33365         if(this.allowBlank || this.disabled){
33366             return;
33367         }
33368         
33369         if(this.labelEl.isVisible(true)){
33370             this.indicatorEl().show();
33371         }
33372         
33373         this.el.removeClass([this.invalidClass, this.validClass]);
33374         this.el.addClass(this.invalidClass);
33375         
33376         this.fireEvent('invalid', this, msg);
33377         
33378     },
33379     
33380     setValue : function(v, suppressEvent)
33381     {   
33382         this.value = v;
33383         if(this.rendered){
33384             this.inputEl().dom.value = (v === null || v === undefined ? '' : v);
33385         }
33386         
33387         Roo.each(this.radioes, function(i){
33388             
33389             i.checked = false;
33390             i.el.removeClass('checked');
33391             
33392             if(i.value === v || i.value.toString() === v.toString()){
33393                 i.checked = true;
33394                 i.el.addClass('checked');
33395                 
33396                 if(suppressEvent !== true){
33397                     this.fireEvent('check', this, i);
33398                 }
33399             }
33400             
33401         }, this);
33402         
33403         this.validate();
33404     },
33405     
33406     clearInvalid : function(){
33407         
33408         if(!this.el || this.preventMark){
33409             return;
33410         }
33411         
33412         this.el.removeClass([this.invalidClass]);
33413         
33414         this.fireEvent('valid', this);
33415     }
33416     
33417 });
33418
33419 Roo.apply(Roo.bootstrap.RadioSet, {
33420     
33421     groups: {},
33422     
33423     register : function(set)
33424     {
33425         this.groups[set.name] = set;
33426     },
33427     
33428     get: function(name) 
33429     {
33430         if (typeof(this.groups[name]) == 'undefined') {
33431             return false;
33432         }
33433         
33434         return this.groups[name] ;
33435     }
33436     
33437 });
33438 /*
33439  * Based on:
33440  * Ext JS Library 1.1.1
33441  * Copyright(c) 2006-2007, Ext JS, LLC.
33442  *
33443  * Originally Released Under LGPL - original licence link has changed is not relivant.
33444  *
33445  * Fork - LGPL
33446  * <script type="text/javascript">
33447  */
33448
33449
33450 /**
33451  * @class Roo.bootstrap.SplitBar
33452  * @extends Roo.util.Observable
33453  * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
33454  * <br><br>
33455  * Usage:
33456  * <pre><code>
33457 var split = new Roo.bootstrap.SplitBar("elementToDrag", "elementToSize",
33458                    Roo.bootstrap.SplitBar.HORIZONTAL, Roo.bootstrap.SplitBar.LEFT);
33459 split.setAdapter(new Roo.bootstrap.SplitBar.AbsoluteLayoutAdapter("container"));
33460 split.minSize = 100;
33461 split.maxSize = 600;
33462 split.animate = true;
33463 split.on('moved', splitterMoved);
33464 </code></pre>
33465  * @constructor
33466  * Create a new SplitBar
33467  * @config {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar. 
33468  * @config {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged 
33469  * @config {Number} orientation (optional) Either Roo.bootstrap.SplitBar.HORIZONTAL or Roo.bootstrap.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
33470  * @config {Number} placement (optional) Either Roo.bootstrap.SplitBar.LEFT or Roo.bootstrap.SplitBar.RIGHT for horizontal or  
33471                         Roo.bootstrap.SplitBar.TOP or Roo.bootstrap.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
33472                         position of the SplitBar).
33473  */
33474 Roo.bootstrap.SplitBar = function(cfg){
33475     
33476     /** @private */
33477     
33478     //{
33479     //  dragElement : elm
33480     //  resizingElement: el,
33481         // optional..
33482     //    orientation : Either Roo.bootstrap.SplitBar.HORIZONTAL
33483     //    placement : Roo.bootstrap.SplitBar.LEFT  ,
33484         // existingProxy ???
33485     //}
33486     
33487     this.el = Roo.get(cfg.dragElement, true);
33488     this.el.dom.unselectable = "on";
33489     /** @private */
33490     this.resizingEl = Roo.get(cfg.resizingElement, true);
33491
33492     /**
33493      * @private
33494      * The orientation of the split. Either Roo.bootstrap.SplitBar.HORIZONTAL or Roo.bootstrap.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
33495      * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
33496      * @type Number
33497      */
33498     this.orientation = cfg.orientation || Roo.bootstrap.SplitBar.HORIZONTAL;
33499     
33500     /**
33501      * The minimum size of the resizing element. (Defaults to 0)
33502      * @type Number
33503      */
33504     this.minSize = 0;
33505     
33506     /**
33507      * The maximum size of the resizing element. (Defaults to 2000)
33508      * @type Number
33509      */
33510     this.maxSize = 2000;
33511     
33512     /**
33513      * Whether to animate the transition to the new size
33514      * @type Boolean
33515      */
33516     this.animate = false;
33517     
33518     /**
33519      * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
33520      * @type Boolean
33521      */
33522     this.useShim = false;
33523     
33524     /** @private */
33525     this.shim = null;
33526     
33527     if(!cfg.existingProxy){
33528         /** @private */
33529         this.proxy = Roo.bootstrap.SplitBar.createProxy(this.orientation);
33530     }else{
33531         this.proxy = Roo.get(cfg.existingProxy).dom;
33532     }
33533     /** @private */
33534     this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
33535     
33536     /** @private */
33537     this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
33538     
33539     /** @private */
33540     this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
33541     
33542     /** @private */
33543     this.dragSpecs = {};
33544     
33545     /**
33546      * @private The adapter to use to positon and resize elements
33547      */
33548     this.adapter = new Roo.bootstrap.SplitBar.BasicLayoutAdapter();
33549     this.adapter.init(this);
33550     
33551     if(this.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
33552         /** @private */
33553         this.placement = cfg.placement || (this.el.getX() > this.resizingEl.getX() ? Roo.bootstrap.SplitBar.LEFT : Roo.bootstrap.SplitBar.RIGHT);
33554         this.el.addClass("roo-splitbar-h");
33555     }else{
33556         /** @private */
33557         this.placement = cfg.placement || (this.el.getY() > this.resizingEl.getY() ? Roo.bootstrap.SplitBar.TOP : Roo.bootstrap.SplitBar.BOTTOM);
33558         this.el.addClass("roo-splitbar-v");
33559     }
33560     
33561     this.addEvents({
33562         /**
33563          * @event resize
33564          * Fires when the splitter is moved (alias for {@link #event-moved})
33565          * @param {Roo.bootstrap.SplitBar} this
33566          * @param {Number} newSize the new width or height
33567          */
33568         "resize" : true,
33569         /**
33570          * @event moved
33571          * Fires when the splitter is moved
33572          * @param {Roo.bootstrap.SplitBar} this
33573          * @param {Number} newSize the new width or height
33574          */
33575         "moved" : true,
33576         /**
33577          * @event beforeresize
33578          * Fires before the splitter is dragged
33579          * @param {Roo.bootstrap.SplitBar} this
33580          */
33581         "beforeresize" : true,
33582
33583         "beforeapply" : true
33584     });
33585
33586     Roo.util.Observable.call(this);
33587 };
33588
33589 Roo.extend(Roo.bootstrap.SplitBar, Roo.util.Observable, {
33590     onStartProxyDrag : function(x, y){
33591         this.fireEvent("beforeresize", this);
33592         if(!this.overlay){
33593             var o = Roo.DomHelper.insertFirst(document.body,  {cls: "roo-drag-overlay", html: "&#160;"}, true);
33594             o.unselectable();
33595             o.enableDisplayMode("block");
33596             // all splitbars share the same overlay
33597             Roo.bootstrap.SplitBar.prototype.overlay = o;
33598         }
33599         this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
33600         this.overlay.show();
33601         Roo.get(this.proxy).setDisplayed("block");
33602         var size = this.adapter.getElementSize(this);
33603         this.activeMinSize = this.getMinimumSize();;
33604         this.activeMaxSize = this.getMaximumSize();;
33605         var c1 = size - this.activeMinSize;
33606         var c2 = Math.max(this.activeMaxSize - size, 0);
33607         if(this.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
33608             this.dd.resetConstraints();
33609             this.dd.setXConstraint(
33610                 this.placement == Roo.bootstrap.SplitBar.LEFT ? c1 : c2, 
33611                 this.placement == Roo.bootstrap.SplitBar.LEFT ? c2 : c1
33612             );
33613             this.dd.setYConstraint(0, 0);
33614         }else{
33615             this.dd.resetConstraints();
33616             this.dd.setXConstraint(0, 0);
33617             this.dd.setYConstraint(
33618                 this.placement == Roo.bootstrap.SplitBar.TOP ? c1 : c2, 
33619                 this.placement == Roo.bootstrap.SplitBar.TOP ? c2 : c1
33620             );
33621          }
33622         this.dragSpecs.startSize = size;
33623         this.dragSpecs.startPoint = [x, y];
33624         Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
33625     },
33626     
33627     /** 
33628      * @private Called after the drag operation by the DDProxy
33629      */
33630     onEndProxyDrag : function(e){
33631         Roo.get(this.proxy).setDisplayed(false);
33632         var endPoint = Roo.lib.Event.getXY(e);
33633         if(this.overlay){
33634             this.overlay.hide();
33635         }
33636         var newSize;
33637         if(this.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
33638             newSize = this.dragSpecs.startSize + 
33639                 (this.placement == Roo.bootstrap.SplitBar.LEFT ?
33640                     endPoint[0] - this.dragSpecs.startPoint[0] :
33641                     this.dragSpecs.startPoint[0] - endPoint[0]
33642                 );
33643         }else{
33644             newSize = this.dragSpecs.startSize + 
33645                 (this.placement == Roo.bootstrap.SplitBar.TOP ?
33646                     endPoint[1] - this.dragSpecs.startPoint[1] :
33647                     this.dragSpecs.startPoint[1] - endPoint[1]
33648                 );
33649         }
33650         newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
33651         if(newSize != this.dragSpecs.startSize){
33652             if(this.fireEvent('beforeapply', this, newSize) !== false){
33653                 this.adapter.setElementSize(this, newSize);
33654                 this.fireEvent("moved", this, newSize);
33655                 this.fireEvent("resize", this, newSize);
33656             }
33657         }
33658     },
33659     
33660     /**
33661      * Get the adapter this SplitBar uses
33662      * @return The adapter object
33663      */
33664     getAdapter : function(){
33665         return this.adapter;
33666     },
33667     
33668     /**
33669      * Set the adapter this SplitBar uses
33670      * @param {Object} adapter A SplitBar adapter object
33671      */
33672     setAdapter : function(adapter){
33673         this.adapter = adapter;
33674         this.adapter.init(this);
33675     },
33676     
33677     /**
33678      * Gets the minimum size for the resizing element
33679      * @return {Number} The minimum size
33680      */
33681     getMinimumSize : function(){
33682         return this.minSize;
33683     },
33684     
33685     /**
33686      * Sets the minimum size for the resizing element
33687      * @param {Number} minSize The minimum size
33688      */
33689     setMinimumSize : function(minSize){
33690         this.minSize = minSize;
33691     },
33692     
33693     /**
33694      * Gets the maximum size for the resizing element
33695      * @return {Number} The maximum size
33696      */
33697     getMaximumSize : function(){
33698         return this.maxSize;
33699     },
33700     
33701     /**
33702      * Sets the maximum size for the resizing element
33703      * @param {Number} maxSize The maximum size
33704      */
33705     setMaximumSize : function(maxSize){
33706         this.maxSize = maxSize;
33707     },
33708     
33709     /**
33710      * Sets the initialize size for the resizing element
33711      * @param {Number} size The initial size
33712      */
33713     setCurrentSize : function(size){
33714         var oldAnimate = this.animate;
33715         this.animate = false;
33716         this.adapter.setElementSize(this, size);
33717         this.animate = oldAnimate;
33718     },
33719     
33720     /**
33721      * Destroy this splitbar. 
33722      * @param {Boolean} removeEl True to remove the element
33723      */
33724     destroy : function(removeEl){
33725         if(this.shim){
33726             this.shim.remove();
33727         }
33728         this.dd.unreg();
33729         this.proxy.parentNode.removeChild(this.proxy);
33730         if(removeEl){
33731             this.el.remove();
33732         }
33733     }
33734 });
33735
33736 /**
33737  * @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.
33738  */
33739 Roo.bootstrap.SplitBar.createProxy = function(dir){
33740     var proxy = new Roo.Element(document.createElement("div"));
33741     proxy.unselectable();
33742     var cls = 'roo-splitbar-proxy';
33743     proxy.addClass(cls + ' ' + (dir == Roo.bootstrap.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
33744     document.body.appendChild(proxy.dom);
33745     return proxy.dom;
33746 };
33747
33748 /** 
33749  * @class Roo.bootstrap.SplitBar.BasicLayoutAdapter
33750  * Default Adapter. It assumes the splitter and resizing element are not positioned
33751  * elements and only gets/sets the width of the element. Generally used for table based layouts.
33752  */
33753 Roo.bootstrap.SplitBar.BasicLayoutAdapter = function(){
33754 };
33755
33756 Roo.bootstrap.SplitBar.BasicLayoutAdapter.prototype = {
33757     // do nothing for now
33758     init : function(s){
33759     
33760     },
33761     /**
33762      * Called before drag operations to get the current size of the resizing element. 
33763      * @param {Roo.bootstrap.SplitBar} s The SplitBar using this adapter
33764      */
33765      getElementSize : function(s){
33766         if(s.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
33767             return s.resizingEl.getWidth();
33768         }else{
33769             return s.resizingEl.getHeight();
33770         }
33771     },
33772     
33773     /**
33774      * Called after drag operations to set the size of the resizing element.
33775      * @param {Roo.bootstrap.SplitBar} s The SplitBar using this adapter
33776      * @param {Number} newSize The new size to set
33777      * @param {Function} onComplete A function to be invoked when resizing is complete
33778      */
33779     setElementSize : function(s, newSize, onComplete){
33780         if(s.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
33781             if(!s.animate){
33782                 s.resizingEl.setWidth(newSize);
33783                 if(onComplete){
33784                     onComplete(s, newSize);
33785                 }
33786             }else{
33787                 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
33788             }
33789         }else{
33790             
33791             if(!s.animate){
33792                 s.resizingEl.setHeight(newSize);
33793                 if(onComplete){
33794                     onComplete(s, newSize);
33795                 }
33796             }else{
33797                 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
33798             }
33799         }
33800     }
33801 };
33802
33803 /** 
33804  *@class Roo.bootstrap.SplitBar.AbsoluteLayoutAdapter
33805  * @extends Roo.bootstrap.SplitBar.BasicLayoutAdapter
33806  * Adapter that  moves the splitter element to align with the resized sizing element. 
33807  * Used with an absolute positioned SplitBar.
33808  * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
33809  * document.body, make sure you assign an id to the body element.
33810  */
33811 Roo.bootstrap.SplitBar.AbsoluteLayoutAdapter = function(container){
33812     this.basic = new Roo.bootstrap.SplitBar.BasicLayoutAdapter();
33813     this.container = Roo.get(container);
33814 };
33815
33816 Roo.bootstrap.SplitBar.AbsoluteLayoutAdapter.prototype = {
33817     init : function(s){
33818         this.basic.init(s);
33819     },
33820     
33821     getElementSize : function(s){
33822         return this.basic.getElementSize(s);
33823     },
33824     
33825     setElementSize : function(s, newSize, onComplete){
33826         this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
33827     },
33828     
33829     moveSplitter : function(s){
33830         var yes = Roo.bootstrap.SplitBar;
33831         switch(s.placement){
33832             case yes.LEFT:
33833                 s.el.setX(s.resizingEl.getRight());
33834                 break;
33835             case yes.RIGHT:
33836                 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
33837                 break;
33838             case yes.TOP:
33839                 s.el.setY(s.resizingEl.getBottom());
33840                 break;
33841             case yes.BOTTOM:
33842                 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
33843                 break;
33844         }
33845     }
33846 };
33847
33848 /**
33849  * Orientation constant - Create a vertical SplitBar
33850  * @static
33851  * @type Number
33852  */
33853 Roo.bootstrap.SplitBar.VERTICAL = 1;
33854
33855 /**
33856  * Orientation constant - Create a horizontal SplitBar
33857  * @static
33858  * @type Number
33859  */
33860 Roo.bootstrap.SplitBar.HORIZONTAL = 2;
33861
33862 /**
33863  * Placement constant - The resizing element is to the left of the splitter element
33864  * @static
33865  * @type Number
33866  */
33867 Roo.bootstrap.SplitBar.LEFT = 1;
33868
33869 /**
33870  * Placement constant - The resizing element is to the right of the splitter element
33871  * @static
33872  * @type Number
33873  */
33874 Roo.bootstrap.SplitBar.RIGHT = 2;
33875
33876 /**
33877  * Placement constant - The resizing element is positioned above the splitter element
33878  * @static
33879  * @type Number
33880  */
33881 Roo.bootstrap.SplitBar.TOP = 3;
33882
33883 /**
33884  * Placement constant - The resizing element is positioned under splitter element
33885  * @static
33886  * @type Number
33887  */
33888 Roo.bootstrap.SplitBar.BOTTOM = 4;
33889 Roo.namespace("Roo.bootstrap.layout");/*
33890  * Based on:
33891  * Ext JS Library 1.1.1
33892  * Copyright(c) 2006-2007, Ext JS, LLC.
33893  *
33894  * Originally Released Under LGPL - original licence link has changed is not relivant.
33895  *
33896  * Fork - LGPL
33897  * <script type="text/javascript">
33898  */
33899
33900 /**
33901  * @class Roo.bootstrap.layout.Manager
33902  * @extends Roo.bootstrap.Component
33903  * Base class for layout managers.
33904  */
33905 Roo.bootstrap.layout.Manager = function(config)
33906 {
33907     Roo.bootstrap.layout.Manager.superclass.constructor.call(this,config);
33908
33909
33910
33911
33912
33913     /** false to disable window resize monitoring @type Boolean */
33914     this.monitorWindowResize = true;
33915     this.regions = {};
33916     this.addEvents({
33917         /**
33918          * @event layout
33919          * Fires when a layout is performed.
33920          * @param {Roo.LayoutManager} this
33921          */
33922         "layout" : true,
33923         /**
33924          * @event regionresized
33925          * Fires when the user resizes a region.
33926          * @param {Roo.LayoutRegion} region The resized region
33927          * @param {Number} newSize The new size (width for east/west, height for north/south)
33928          */
33929         "regionresized" : true,
33930         /**
33931          * @event regioncollapsed
33932          * Fires when a region is collapsed.
33933          * @param {Roo.LayoutRegion} region The collapsed region
33934          */
33935         "regioncollapsed" : true,
33936         /**
33937          * @event regionexpanded
33938          * Fires when a region is expanded.
33939          * @param {Roo.LayoutRegion} region The expanded region
33940          */
33941         "regionexpanded" : true
33942     });
33943     this.updating = false;
33944
33945     if (config.el) {
33946         this.el = Roo.get(config.el);
33947         this.initEvents();
33948     }
33949
33950 };
33951
33952 Roo.extend(Roo.bootstrap.layout.Manager, Roo.bootstrap.Component, {
33953
33954
33955     regions : null,
33956
33957     monitorWindowResize : true,
33958
33959
33960     updating : false,
33961
33962
33963     onRender : function(ct, position)
33964     {
33965         if(!this.el){
33966             this.el = Roo.get(ct);
33967             this.initEvents();
33968         }
33969         //this.fireEvent('render',this);
33970     },
33971
33972
33973     initEvents: function()
33974     {
33975
33976
33977         // ie scrollbar fix
33978         if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
33979             document.body.scroll = "no";
33980         }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
33981             this.el.position('relative');
33982         }
33983         this.id = this.el.id;
33984         this.el.addClass("roo-layout-container");
33985         Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
33986         if(this.el.dom != document.body ) {
33987             this.el.on('resize', this.layout,this);
33988             this.el.on('show', this.layout,this);
33989         }
33990
33991     },
33992
33993     /**
33994      * Returns true if this layout is currently being updated
33995      * @return {Boolean}
33996      */
33997     isUpdating : function(){
33998         return this.updating;
33999     },
34000
34001     /**
34002      * Suspend the LayoutManager from doing auto-layouts while
34003      * making multiple add or remove calls
34004      */
34005     beginUpdate : function(){
34006         this.updating = true;
34007     },
34008
34009     /**
34010      * Restore auto-layouts and optionally disable the manager from performing a layout
34011      * @param {Boolean} noLayout true to disable a layout update
34012      */
34013     endUpdate : function(noLayout){
34014         this.updating = false;
34015         if(!noLayout){
34016             this.layout();
34017         }
34018     },
34019
34020     layout: function(){
34021         // abstract...
34022     },
34023
34024     onRegionResized : function(region, newSize){
34025         this.fireEvent("regionresized", region, newSize);
34026         this.layout();
34027     },
34028
34029     onRegionCollapsed : function(region){
34030         this.fireEvent("regioncollapsed", region);
34031     },
34032
34033     onRegionExpanded : function(region){
34034         this.fireEvent("regionexpanded", region);
34035     },
34036
34037     /**
34038      * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
34039      * performs box-model adjustments.
34040      * @return {Object} The size as an object {width: (the width), height: (the height)}
34041      */
34042     getViewSize : function()
34043     {
34044         var size;
34045         if(this.el.dom != document.body){
34046             size = this.el.getSize();
34047         }else{
34048             size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
34049         }
34050         size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
34051         size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
34052         return size;
34053     },
34054
34055     /**
34056      * Returns the Element this layout is bound to.
34057      * @return {Roo.Element}
34058      */
34059     getEl : function(){
34060         return this.el;
34061     },
34062
34063     /**
34064      * Returns the specified region.
34065      * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
34066      * @return {Roo.LayoutRegion}
34067      */
34068     getRegion : function(target){
34069         return this.regions[target.toLowerCase()];
34070     },
34071
34072     onWindowResize : function(){
34073         if(this.monitorWindowResize){
34074             this.layout();
34075         }
34076     }
34077 });
34078 /*
34079  * Based on:
34080  * Ext JS Library 1.1.1
34081  * Copyright(c) 2006-2007, Ext JS, LLC.
34082  *
34083  * Originally Released Under LGPL - original licence link has changed is not relivant.
34084  *
34085  * Fork - LGPL
34086  * <script type="text/javascript">
34087  */
34088 /**
34089  * @class Roo.bootstrap.layout.Border
34090  * @extends Roo.bootstrap.layout.Manager
34091  * This class represents a common layout manager used in desktop applications. For screenshots and more details,
34092  * please see: examples/bootstrap/nested.html<br><br>
34093  
34094 <b>The container the layout is rendered into can be either the body element or any other element.
34095 If it is not the body element, the container needs to either be an absolute positioned element,
34096 or you will need to add "position:relative" to the css of the container.  You will also need to specify
34097 the container size if it is not the body element.</b>
34098
34099 * @constructor
34100 * Create a new Border
34101 * @param {Object} config Configuration options
34102  */
34103 Roo.bootstrap.layout.Border = function(config){
34104     config = config || {};
34105     Roo.bootstrap.layout.Border.superclass.constructor.call(this, config);
34106     
34107     
34108     
34109     Roo.each(Roo.bootstrap.layout.Border.regions, function(region) {
34110         if(config[region]){
34111             config[region].region = region;
34112             this.addRegion(config[region]);
34113         }
34114     },this);
34115     
34116 };
34117
34118 Roo.bootstrap.layout.Border.regions =  ["north","south","east","west","center"];
34119
34120 Roo.extend(Roo.bootstrap.layout.Border, Roo.bootstrap.layout.Manager, {
34121     /**
34122      * Creates and adds a new region if it doesn't already exist.
34123      * @param {String} target The target region key (north, south, east, west or center).
34124      * @param {Object} config The regions config object
34125      * @return {BorderLayoutRegion} The new region
34126      */
34127     addRegion : function(config)
34128     {
34129         if(!this.regions[config.region]){
34130             var r = this.factory(config);
34131             this.bindRegion(r);
34132         }
34133         return this.regions[config.region];
34134     },
34135
34136     // private (kinda)
34137     bindRegion : function(r){
34138         this.regions[r.config.region] = r;
34139         
34140         r.on("visibilitychange",    this.layout, this);
34141         r.on("paneladded",          this.layout, this);
34142         r.on("panelremoved",        this.layout, this);
34143         r.on("invalidated",         this.layout, this);
34144         r.on("resized",             this.onRegionResized, this);
34145         r.on("collapsed",           this.onRegionCollapsed, this);
34146         r.on("expanded",            this.onRegionExpanded, this);
34147     },
34148
34149     /**
34150      * Performs a layout update.
34151      */
34152     layout : function()
34153     {
34154         if(this.updating) {
34155             return;
34156         }
34157         
34158         // render all the rebions if they have not been done alreayd?
34159         Roo.each(Roo.bootstrap.layout.Border.regions, function(region) {
34160             if(this.regions[region] && !this.regions[region].bodyEl){
34161                 this.regions[region].onRender(this.el)
34162             }
34163         },this);
34164         
34165         var size = this.getViewSize();
34166         var w = size.width;
34167         var h = size.height;
34168         var centerW = w;
34169         var centerH = h;
34170         var centerY = 0;
34171         var centerX = 0;
34172         //var x = 0, y = 0;
34173
34174         var rs = this.regions;
34175         var north = rs["north"];
34176         var south = rs["south"]; 
34177         var west = rs["west"];
34178         var east = rs["east"];
34179         var center = rs["center"];
34180         //if(this.hideOnLayout){ // not supported anymore
34181             //c.el.setStyle("display", "none");
34182         //}
34183         if(north && north.isVisible()){
34184             var b = north.getBox();
34185             var m = north.getMargins();
34186             b.width = w - (m.left+m.right);
34187             b.x = m.left;
34188             b.y = m.top;
34189             centerY = b.height + b.y + m.bottom;
34190             centerH -= centerY;
34191             north.updateBox(this.safeBox(b));
34192         }
34193         if(south && south.isVisible()){
34194             var b = south.getBox();
34195             var m = south.getMargins();
34196             b.width = w - (m.left+m.right);
34197             b.x = m.left;
34198             var totalHeight = (b.height + m.top + m.bottom);
34199             b.y = h - totalHeight + m.top;
34200             centerH -= totalHeight;
34201             south.updateBox(this.safeBox(b));
34202         }
34203         if(west && west.isVisible()){
34204             var b = west.getBox();
34205             var m = west.getMargins();
34206             b.height = centerH - (m.top+m.bottom);
34207             b.x = m.left;
34208             b.y = centerY + m.top;
34209             var totalWidth = (b.width + m.left + m.right);
34210             centerX += totalWidth;
34211             centerW -= totalWidth;
34212             west.updateBox(this.safeBox(b));
34213         }
34214         if(east && east.isVisible()){
34215             var b = east.getBox();
34216             var m = east.getMargins();
34217             b.height = centerH - (m.top+m.bottom);
34218             var totalWidth = (b.width + m.left + m.right);
34219             b.x = w - totalWidth + m.left;
34220             b.y = centerY + m.top;
34221             centerW -= totalWidth;
34222             east.updateBox(this.safeBox(b));
34223         }
34224         if(center){
34225             var m = center.getMargins();
34226             var centerBox = {
34227                 x: centerX + m.left,
34228                 y: centerY + m.top,
34229                 width: centerW - (m.left+m.right),
34230                 height: centerH - (m.top+m.bottom)
34231             };
34232             //if(this.hideOnLayout){
34233                 //center.el.setStyle("display", "block");
34234             //}
34235             center.updateBox(this.safeBox(centerBox));
34236         }
34237         this.el.repaint();
34238         this.fireEvent("layout", this);
34239     },
34240
34241     // private
34242     safeBox : function(box){
34243         box.width = Math.max(0, box.width);
34244         box.height = Math.max(0, box.height);
34245         return box;
34246     },
34247
34248     /**
34249      * Adds a ContentPanel (or subclass) to this layout.
34250      * @param {String} target The target region key (north, south, east, west or center).
34251      * @param {Roo.ContentPanel} panel The panel to add
34252      * @return {Roo.ContentPanel} The added panel
34253      */
34254     add : function(target, panel){
34255          
34256         target = target.toLowerCase();
34257         return this.regions[target].add(panel);
34258     },
34259
34260     /**
34261      * Remove a ContentPanel (or subclass) to this layout.
34262      * @param {String} target The target region key (north, south, east, west or center).
34263      * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
34264      * @return {Roo.ContentPanel} The removed panel
34265      */
34266     remove : function(target, panel){
34267         target = target.toLowerCase();
34268         return this.regions[target].remove(panel);
34269     },
34270
34271     /**
34272      * Searches all regions for a panel with the specified id
34273      * @param {String} panelId
34274      * @return {Roo.ContentPanel} The panel or null if it wasn't found
34275      */
34276     findPanel : function(panelId){
34277         var rs = this.regions;
34278         for(var target in rs){
34279             if(typeof rs[target] != "function"){
34280                 var p = rs[target].getPanel(panelId);
34281                 if(p){
34282                     return p;
34283                 }
34284             }
34285         }
34286         return null;
34287     },
34288
34289     /**
34290      * Searches all regions for a panel with the specified id and activates (shows) it.
34291      * @param {String/ContentPanel} panelId The panels id or the panel itself
34292      * @return {Roo.ContentPanel} The shown panel or null
34293      */
34294     showPanel : function(panelId) {
34295       var rs = this.regions;
34296       for(var target in rs){
34297          var r = rs[target];
34298          if(typeof r != "function"){
34299             if(r.hasPanel(panelId)){
34300                return r.showPanel(panelId);
34301             }
34302          }
34303       }
34304       return null;
34305    },
34306
34307    /**
34308      * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
34309      * @param {Roo.state.Provider} provider (optional) An alternate state provider
34310      */
34311    /*
34312     restoreState : function(provider){
34313         if(!provider){
34314             provider = Roo.state.Manager;
34315         }
34316         var sm = new Roo.LayoutStateManager();
34317         sm.init(this, provider);
34318     },
34319 */
34320  
34321  
34322     /**
34323      * Adds a xtype elements to the layout.
34324      * <pre><code>
34325
34326 layout.addxtype({
34327        xtype : 'ContentPanel',
34328        region: 'west',
34329        items: [ .... ]
34330    }
34331 );
34332
34333 layout.addxtype({
34334         xtype : 'NestedLayoutPanel',
34335         region: 'west',
34336         layout: {
34337            center: { },
34338            west: { }   
34339         },
34340         items : [ ... list of content panels or nested layout panels.. ]
34341    }
34342 );
34343 </code></pre>
34344      * @param {Object} cfg Xtype definition of item to add.
34345      */
34346     addxtype : function(cfg)
34347     {
34348         // basically accepts a pannel...
34349         // can accept a layout region..!?!?
34350         //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
34351         
34352         
34353         // theory?  children can only be panels??
34354         
34355         //if (!cfg.xtype.match(/Panel$/)) {
34356         //    return false;
34357         //}
34358         var ret = false;
34359         
34360         if (typeof(cfg.region) == 'undefined') {
34361             Roo.log("Failed to add Panel, region was not set");
34362             Roo.log(cfg);
34363             return false;
34364         }
34365         var region = cfg.region;
34366         delete cfg.region;
34367         
34368           
34369         var xitems = [];
34370         if (cfg.items) {
34371             xitems = cfg.items;
34372             delete cfg.items;
34373         }
34374         var nb = false;
34375         
34376         switch(cfg.xtype) 
34377         {
34378             case 'Content':  // ContentPanel (el, cfg)
34379             case 'Scroll':  // ContentPanel (el, cfg)
34380             case 'View': 
34381                 cfg.autoCreate = true;
34382                 ret = new cfg.xns[cfg.xtype](cfg); // new panel!!!!!
34383                 //} else {
34384                 //    var el = this.el.createChild();
34385                 //    ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
34386                 //}
34387                 
34388                 this.add(region, ret);
34389                 break;
34390             
34391             /*
34392             case 'TreePanel': // our new panel!
34393                 cfg.el = this.el.createChild();
34394                 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
34395                 this.add(region, ret);
34396                 break;
34397             */
34398             
34399             case 'Nest': 
34400                 // create a new Layout (which is  a Border Layout...
34401                 
34402                 var clayout = cfg.layout;
34403                 clayout.el  = this.el.createChild();
34404                 clayout.items   = clayout.items  || [];
34405                 
34406                 delete cfg.layout;
34407                 
34408                 // replace this exitems with the clayout ones..
34409                 xitems = clayout.items;
34410                  
34411                 // force background off if it's in center...
34412                 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
34413                     cfg.background = false;
34414                 }
34415                 cfg.layout  = new Roo.bootstrap.layout.Border(clayout);
34416                 
34417                 
34418                 ret = new cfg.xns[cfg.xtype](cfg); // new panel!!!!!
34419                 //console.log('adding nested layout panel '  + cfg.toSource());
34420                 this.add(region, ret);
34421                 nb = {}; /// find first...
34422                 break;
34423             
34424             case 'Grid':
34425                 
34426                 // needs grid and region
34427                 
34428                 //var el = this.getRegion(region).el.createChild();
34429                 /*
34430                  *var el = this.el.createChild();
34431                 // create the grid first...
34432                 cfg.grid.container = el;
34433                 cfg.grid = new cfg.grid.xns[cfg.grid.xtype](cfg.grid);
34434                 */
34435                 
34436                 if (region == 'center' && this.active ) {
34437                     cfg.background = false;
34438                 }
34439                 
34440                 ret = new cfg.xns[cfg.xtype](cfg); // new panel!!!!!
34441                 
34442                 this.add(region, ret);
34443                 /*
34444                 if (cfg.background) {
34445                     // render grid on panel activation (if panel background)
34446                     ret.on('activate', function(gp) {
34447                         if (!gp.grid.rendered) {
34448                     //        gp.grid.render(el);
34449                         }
34450                     });
34451                 } else {
34452                   //  cfg.grid.render(el);
34453                 }
34454                 */
34455                 break;
34456            
34457            
34458             case 'Border': // it can get called on it'self... - might need to check if this is fixed?
34459                 // it was the old xcomponent building that caused this before.
34460                 // espeically if border is the top element in the tree.
34461                 ret = this;
34462                 break; 
34463                 
34464                     
34465                 
34466                 
34467                 
34468             default:
34469                 /*
34470                 if (typeof(Roo[cfg.xtype]) != 'undefined') {
34471                     
34472                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
34473                     this.add(region, ret);
34474                 } else {
34475                 */
34476                     Roo.log(cfg);
34477                     throw "Can not add '" + cfg.xtype + "' to Border";
34478                     return null;
34479              
34480                                 
34481              
34482         }
34483         this.beginUpdate();
34484         // add children..
34485         var region = '';
34486         var abn = {};
34487         Roo.each(xitems, function(i)  {
34488             region = nb && i.region ? i.region : false;
34489             
34490             var add = ret.addxtype(i);
34491            
34492             if (region) {
34493                 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
34494                 if (!i.background) {
34495                     abn[region] = nb[region] ;
34496                 }
34497             }
34498             
34499         });
34500         this.endUpdate();
34501
34502         // make the last non-background panel active..
34503         //if (nb) { Roo.log(abn); }
34504         if (nb) {
34505             
34506             for(var r in abn) {
34507                 region = this.getRegion(r);
34508                 if (region) {
34509                     // tried using nb[r], but it does not work..
34510                      
34511                     region.showPanel(abn[r]);
34512                    
34513                 }
34514             }
34515         }
34516         return ret;
34517         
34518     },
34519     
34520     
34521 // private
34522     factory : function(cfg)
34523     {
34524         
34525         var validRegions = Roo.bootstrap.layout.Border.regions;
34526
34527         var target = cfg.region;
34528         cfg.mgr = this;
34529         
34530         var r = Roo.bootstrap.layout;
34531         Roo.log(target);
34532         switch(target){
34533             case "north":
34534                 return new r.North(cfg);
34535             case "south":
34536                 return new r.South(cfg);
34537             case "east":
34538                 return new r.East(cfg);
34539             case "west":
34540                 return new r.West(cfg);
34541             case "center":
34542                 return new r.Center(cfg);
34543         }
34544         throw 'Layout region "'+target+'" not supported.';
34545     }
34546     
34547     
34548 });
34549  /*
34550  * Based on:
34551  * Ext JS Library 1.1.1
34552  * Copyright(c) 2006-2007, Ext JS, LLC.
34553  *
34554  * Originally Released Under LGPL - original licence link has changed is not relivant.
34555  *
34556  * Fork - LGPL
34557  * <script type="text/javascript">
34558  */
34559  
34560 /**
34561  * @class Roo.bootstrap.layout.Basic
34562  * @extends Roo.util.Observable
34563  * This class represents a lightweight region in a layout manager. This region does not move dom nodes
34564  * and does not have a titlebar, tabs or any other features. All it does is size and position 
34565  * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
34566  * @cfg {Roo.bootstrap.layout.Manager}   mgr The manager
34567  * @cfg {string}   region  the region that it inhabits..
34568  * @cfg {bool}   skipConfig skip config?
34569  * 
34570
34571  */
34572 Roo.bootstrap.layout.Basic = function(config){
34573     
34574     this.mgr = config.mgr;
34575     
34576     this.position = config.region;
34577     
34578     var skipConfig = config.skipConfig;
34579     
34580     this.events = {
34581         /**
34582          * @scope Roo.BasicLayoutRegion
34583          */
34584         
34585         /**
34586          * @event beforeremove
34587          * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
34588          * @param {Roo.LayoutRegion} this
34589          * @param {Roo.ContentPanel} panel The panel
34590          * @param {Object} e The cancel event object
34591          */
34592         "beforeremove" : true,
34593         /**
34594          * @event invalidated
34595          * Fires when the layout for this region is changed.
34596          * @param {Roo.LayoutRegion} this
34597          */
34598         "invalidated" : true,
34599         /**
34600          * @event visibilitychange
34601          * Fires when this region is shown or hidden 
34602          * @param {Roo.LayoutRegion} this
34603          * @param {Boolean} visibility true or false
34604          */
34605         "visibilitychange" : true,
34606         /**
34607          * @event paneladded
34608          * Fires when a panel is added. 
34609          * @param {Roo.LayoutRegion} this
34610          * @param {Roo.ContentPanel} panel The panel
34611          */
34612         "paneladded" : true,
34613         /**
34614          * @event panelremoved
34615          * Fires when a panel is removed. 
34616          * @param {Roo.LayoutRegion} this
34617          * @param {Roo.ContentPanel} panel The panel
34618          */
34619         "panelremoved" : true,
34620         /**
34621          * @event beforecollapse
34622          * Fires when this region before collapse.
34623          * @param {Roo.LayoutRegion} this
34624          */
34625         "beforecollapse" : true,
34626         /**
34627          * @event collapsed
34628          * Fires when this region is collapsed.
34629          * @param {Roo.LayoutRegion} this
34630          */
34631         "collapsed" : true,
34632         /**
34633          * @event expanded
34634          * Fires when this region is expanded.
34635          * @param {Roo.LayoutRegion} this
34636          */
34637         "expanded" : true,
34638         /**
34639          * @event slideshow
34640          * Fires when this region is slid into view.
34641          * @param {Roo.LayoutRegion} this
34642          */
34643         "slideshow" : true,
34644         /**
34645          * @event slidehide
34646          * Fires when this region slides out of view. 
34647          * @param {Roo.LayoutRegion} this
34648          */
34649         "slidehide" : true,
34650         /**
34651          * @event panelactivated
34652          * Fires when a panel is activated. 
34653          * @param {Roo.LayoutRegion} this
34654          * @param {Roo.ContentPanel} panel The activated panel
34655          */
34656         "panelactivated" : true,
34657         /**
34658          * @event resized
34659          * Fires when the user resizes this region. 
34660          * @param {Roo.LayoutRegion} this
34661          * @param {Number} newSize The new size (width for east/west, height for north/south)
34662          */
34663         "resized" : true
34664     };
34665     /** A collection of panels in this region. @type Roo.util.MixedCollection */
34666     this.panels = new Roo.util.MixedCollection();
34667     this.panels.getKey = this.getPanelId.createDelegate(this);
34668     this.box = null;
34669     this.activePanel = null;
34670     // ensure listeners are added...
34671     
34672     if (config.listeners || config.events) {
34673         Roo.bootstrap.layout.Basic.superclass.constructor.call(this, {
34674             listeners : config.listeners || {},
34675             events : config.events || {}
34676         });
34677     }
34678     
34679     if(skipConfig !== true){
34680         this.applyConfig(config);
34681     }
34682 };
34683
34684 Roo.extend(Roo.bootstrap.layout.Basic, Roo.util.Observable,
34685 {
34686     getPanelId : function(p){
34687         return p.getId();
34688     },
34689     
34690     applyConfig : function(config){
34691         this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
34692         this.config = config;
34693         
34694     },
34695     
34696     /**
34697      * Resizes the region to the specified size. For vertical regions (west, east) this adjusts 
34698      * the width, for horizontal (north, south) the height.
34699      * @param {Number} newSize The new width or height
34700      */
34701     resizeTo : function(newSize){
34702         var el = this.el ? this.el :
34703                  (this.activePanel ? this.activePanel.getEl() : null);
34704         if(el){
34705             switch(this.position){
34706                 case "east":
34707                 case "west":
34708                     el.setWidth(newSize);
34709                     this.fireEvent("resized", this, newSize);
34710                 break;
34711                 case "north":
34712                 case "south":
34713                     el.setHeight(newSize);
34714                     this.fireEvent("resized", this, newSize);
34715                 break;                
34716             }
34717         }
34718     },
34719     
34720     getBox : function(){
34721         return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
34722     },
34723     
34724     getMargins : function(){
34725         return this.margins;
34726     },
34727     
34728     updateBox : function(box){
34729         this.box = box;
34730         var el = this.activePanel.getEl();
34731         el.dom.style.left = box.x + "px";
34732         el.dom.style.top = box.y + "px";
34733         this.activePanel.setSize(box.width, box.height);
34734     },
34735     
34736     /**
34737      * Returns the container element for this region.
34738      * @return {Roo.Element}
34739      */
34740     getEl : function(){
34741         return this.activePanel;
34742     },
34743     
34744     /**
34745      * Returns true if this region is currently visible.
34746      * @return {Boolean}
34747      */
34748     isVisible : function(){
34749         return this.activePanel ? true : false;
34750     },
34751     
34752     setActivePanel : function(panel){
34753         panel = this.getPanel(panel);
34754         if(this.activePanel && this.activePanel != panel){
34755             this.activePanel.setActiveState(false);
34756             this.activePanel.getEl().setLeftTop(-10000,-10000);
34757         }
34758         this.activePanel = panel;
34759         panel.setActiveState(true);
34760         if(this.box){
34761             panel.setSize(this.box.width, this.box.height);
34762         }
34763         this.fireEvent("panelactivated", this, panel);
34764         this.fireEvent("invalidated");
34765     },
34766     
34767     /**
34768      * Show the specified panel.
34769      * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
34770      * @return {Roo.ContentPanel} The shown panel or null
34771      */
34772     showPanel : function(panel){
34773         panel = this.getPanel(panel);
34774         if(panel){
34775             this.setActivePanel(panel);
34776         }
34777         return panel;
34778     },
34779     
34780     /**
34781      * Get the active panel for this region.
34782      * @return {Roo.ContentPanel} The active panel or null
34783      */
34784     getActivePanel : function(){
34785         return this.activePanel;
34786     },
34787     
34788     /**
34789      * Add the passed ContentPanel(s)
34790      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
34791      * @return {Roo.ContentPanel} The panel added (if only one was added)
34792      */
34793     add : function(panel){
34794         if(arguments.length > 1){
34795             for(var i = 0, len = arguments.length; i < len; i++) {
34796                 this.add(arguments[i]);
34797             }
34798             return null;
34799         }
34800         if(this.hasPanel(panel)){
34801             this.showPanel(panel);
34802             return panel;
34803         }
34804         var el = panel.getEl();
34805         if(el.dom.parentNode != this.mgr.el.dom){
34806             this.mgr.el.dom.appendChild(el.dom);
34807         }
34808         if(panel.setRegion){
34809             panel.setRegion(this);
34810         }
34811         this.panels.add(panel);
34812         el.setStyle("position", "absolute");
34813         if(!panel.background){
34814             this.setActivePanel(panel);
34815             if(this.config.initialSize && this.panels.getCount()==1){
34816                 this.resizeTo(this.config.initialSize);
34817             }
34818         }
34819         this.fireEvent("paneladded", this, panel);
34820         return panel;
34821     },
34822     
34823     /**
34824      * Returns true if the panel is in this region.
34825      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
34826      * @return {Boolean}
34827      */
34828     hasPanel : function(panel){
34829         if(typeof panel == "object"){ // must be panel obj
34830             panel = panel.getId();
34831         }
34832         return this.getPanel(panel) ? true : false;
34833     },
34834     
34835     /**
34836      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
34837      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
34838      * @param {Boolean} preservePanel Overrides the config preservePanel option
34839      * @return {Roo.ContentPanel} The panel that was removed
34840      */
34841     remove : function(panel, preservePanel){
34842         panel = this.getPanel(panel);
34843         if(!panel){
34844             return null;
34845         }
34846         var e = {};
34847         this.fireEvent("beforeremove", this, panel, e);
34848         if(e.cancel === true){
34849             return null;
34850         }
34851         var panelId = panel.getId();
34852         this.panels.removeKey(panelId);
34853         return panel;
34854     },
34855     
34856     /**
34857      * Returns the panel specified or null if it's not in this region.
34858      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
34859      * @return {Roo.ContentPanel}
34860      */
34861     getPanel : function(id){
34862         if(typeof id == "object"){ // must be panel obj
34863             return id;
34864         }
34865         return this.panels.get(id);
34866     },
34867     
34868     /**
34869      * Returns this regions position (north/south/east/west/center).
34870      * @return {String} 
34871      */
34872     getPosition: function(){
34873         return this.position;    
34874     }
34875 });/*
34876  * Based on:
34877  * Ext JS Library 1.1.1
34878  * Copyright(c) 2006-2007, Ext JS, LLC.
34879  *
34880  * Originally Released Under LGPL - original licence link has changed is not relivant.
34881  *
34882  * Fork - LGPL
34883  * <script type="text/javascript">
34884  */
34885  
34886 /**
34887  * @class Roo.bootstrap.layout.Region
34888  * @extends Roo.bootstrap.layout.Basic
34889  * This class represents a region in a layout manager.
34890  
34891  * @cfg {Object}    margins         Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
34892  * @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})
34893  * @cfg {String}    tabPosition     (top|bottom) "top" or "bottom" (defaults to "bottom")
34894  * @cfg {Boolean}   alwaysShowTabs  True to always display tabs even when there is only 1 panel (defaults to false)
34895  * @cfg {Boolean}   autoScroll      True to enable overflow scrolling (defaults to false)
34896  * @cfg {Boolean}   titlebar        True to display a title bar (defaults to true)
34897  * @cfg {String}    title           The title for the region (overrides panel titles)
34898  * @cfg {Boolean}   animate         True to animate expand/collapse (defaults to false)
34899  * @cfg {Boolean}   autoHide        False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
34900  * @cfg {Boolean}   preservePanels  True to preserve removed panels so they can be readded later (defaults to false)
34901  * @cfg {Boolean}   closeOnTab      True to place the close icon on the tabs instead of the region titlebar (defaults to false)
34902  * @cfg {Boolean}   hideTabs        True to hide the tab strip (defaults to false)
34903  * @cfg {Boolean}   resizeTabs      True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
34904  *                      the space available, similar to FireFox 1.5 tabs (defaults to false)
34905  * @cfg {Number}    minTabWidth     The minimum tab width (defaults to 40)
34906  * @cfg {Number}    preferredTabWidth The preferred tab width (defaults to 150)
34907  * @cfg {String}    overflow       (hidden|visible) if you have menus in the region, then you need to set this to visible.
34908
34909  * @cfg {Boolean}   hidden          True to start the region hidden (defaults to false)
34910  * @cfg {Boolean}   hideWhenEmpty   True to hide the region when it has no panels
34911  * @cfg {Boolean}   disableTabTips  True to disable tab tooltips
34912  * @cfg {Number}    width           For East/West panels
34913  * @cfg {Number}    height          For North/South panels
34914  * @cfg {Boolean}   split           To show the splitter
34915  * @cfg {Boolean}   toolbar         xtype configuration for a toolbar - shows on right of tabbar
34916  * 
34917  * @cfg {string}   cls             Extra CSS classes to add to region
34918  * 
34919  * @cfg {Roo.bootstrap.layout.Manager}   mgr The manager
34920  * @cfg {string}   region  the region that it inhabits..
34921  *
34922
34923  * @xxxcfg {Boolean}   collapsible     DISABLED False to disable collapsing (defaults to true)
34924  * @xxxcfg {Boolean}   collapsed       DISABLED True to set the initial display to collapsed (defaults to false)
34925
34926  * @xxxcfg {String}    collapsedTitle  DISABLED Optional string message to display in the collapsed block of a north or south region
34927  * @xxxxcfg {Boolean}   floatable       DISABLED False to disable floating (defaults to true)
34928  * @xxxxcfg {Boolean}   showPin         True to show a pin button NOT SUPPORTED YET
34929  */
34930 Roo.bootstrap.layout.Region = function(config)
34931 {
34932     this.applyConfig(config);
34933
34934     var mgr = config.mgr;
34935     var pos = config.region;
34936     config.skipConfig = true;
34937     Roo.bootstrap.layout.Region.superclass.constructor.call(this, config);
34938     
34939     if (mgr.el) {
34940         this.onRender(mgr.el);   
34941     }
34942      
34943     this.visible = true;
34944     this.collapsed = false;
34945     this.unrendered_panels = [];
34946 };
34947
34948 Roo.extend(Roo.bootstrap.layout.Region, Roo.bootstrap.layout.Basic, {
34949
34950     position: '', // set by wrapper (eg. north/south etc..)
34951     unrendered_panels : null,  // unrendered panels.
34952     createBody : function(){
34953         /** This region's body element 
34954         * @type Roo.Element */
34955         this.bodyEl = this.el.createChild({
34956                 tag: "div",
34957                 cls: "roo-layout-panel-body tab-content" // bootstrap added...
34958         });
34959     },
34960
34961     onRender: function(ctr, pos)
34962     {
34963         var dh = Roo.DomHelper;
34964         /** This region's container element 
34965         * @type Roo.Element */
34966         this.el = dh.append(ctr.dom, {
34967                 tag: "div",
34968                 cls: (this.config.cls || '') + " roo-layout-region roo-layout-panel roo-layout-panel-" + this.position
34969             }, true);
34970         /** This region's title element 
34971         * @type Roo.Element */
34972     
34973         this.titleEl = dh.append(this.el.dom,
34974             {
34975                     tag: "div",
34976                     unselectable: "on",
34977                     cls: "roo-unselectable roo-layout-panel-hd breadcrumb roo-layout-title-" + this.position,
34978                     children:[
34979                         {tag: "span", cls: "roo-unselectable roo-layout-panel-hd-text", unselectable: "on", html: "&#160;"},
34980                         {tag: "div", cls: "roo-unselectable roo-layout-panel-hd-tools", unselectable: "on"}
34981                     ]}, true);
34982         
34983         this.titleEl.enableDisplayMode();
34984         /** This region's title text element 
34985         * @type HTMLElement */
34986         this.titleTextEl = this.titleEl.dom.firstChild;
34987         this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
34988         /*
34989         this.closeBtn = this.createTool(this.tools.dom, "roo-layout-close");
34990         this.closeBtn.enableDisplayMode();
34991         this.closeBtn.on("click", this.closeClicked, this);
34992         this.closeBtn.hide();
34993     */
34994         this.createBody(this.config);
34995         if(this.config.hideWhenEmpty){
34996             this.hide();
34997             this.on("paneladded", this.validateVisibility, this);
34998             this.on("panelremoved", this.validateVisibility, this);
34999         }
35000         if(this.autoScroll){
35001             this.bodyEl.setStyle("overflow", "auto");
35002         }else{
35003             this.bodyEl.setStyle("overflow", this.config.overflow || 'hidden');
35004         }
35005         //if(c.titlebar !== false){
35006             if((!this.config.titlebar && !this.config.title) || this.config.titlebar === false){
35007                 this.titleEl.hide();
35008             }else{
35009                 this.titleEl.show();
35010                 if(this.config.title){
35011                     this.titleTextEl.innerHTML = this.config.title;
35012                 }
35013             }
35014         //}
35015         if(this.config.collapsed){
35016             this.collapse(true);
35017         }
35018         if(this.config.hidden){
35019             this.hide();
35020         }
35021         
35022         if (this.unrendered_panels && this.unrendered_panels.length) {
35023             for (var i =0;i< this.unrendered_panels.length; i++) {
35024                 this.add(this.unrendered_panels[i]);
35025             }
35026             this.unrendered_panels = null;
35027             
35028         }
35029         
35030     },
35031     
35032     applyConfig : function(c)
35033     {
35034         /*
35035          *if(c.collapsible && this.position != "center" && !this.collapsedEl){
35036             var dh = Roo.DomHelper;
35037             if(c.titlebar !== false){
35038                 this.collapseBtn = this.createTool(this.tools.dom, "roo-layout-collapse-"+this.position);
35039                 this.collapseBtn.on("click", this.collapse, this);
35040                 this.collapseBtn.enableDisplayMode();
35041                 /*
35042                 if(c.showPin === true || this.showPin){
35043                     this.stickBtn = this.createTool(this.tools.dom, "roo-layout-stick");
35044                     this.stickBtn.enableDisplayMode();
35045                     this.stickBtn.on("click", this.expand, this);
35046                     this.stickBtn.hide();
35047                 }
35048                 
35049             }
35050             */
35051             /** This region's collapsed element
35052             * @type Roo.Element */
35053             /*
35054              *
35055             this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
35056                 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
35057             ]}, true);
35058             
35059             if(c.floatable !== false){
35060                this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
35061                this.collapsedEl.on("click", this.collapseClick, this);
35062             }
35063
35064             if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
35065                 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
35066                    id: "message", unselectable: "on", style:{"float":"left"}});
35067                this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
35068              }
35069             this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
35070             this.expandBtn.on("click", this.expand, this);
35071             
35072         }
35073         
35074         if(this.collapseBtn){
35075             this.collapseBtn.setVisible(c.collapsible == true);
35076         }
35077         
35078         this.cmargins = c.cmargins || this.cmargins ||
35079                          (this.position == "west" || this.position == "east" ?
35080                              {top: 0, left: 2, right:2, bottom: 0} :
35081                              {top: 2, left: 0, right:0, bottom: 2});
35082         */
35083         this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
35084         
35085         
35086         this.bottomTabs = c.tabPosition != "top";
35087         
35088         this.autoScroll = c.autoScroll || false;
35089         
35090         
35091        
35092         
35093         this.duration = c.duration || .30;
35094         this.slideDuration = c.slideDuration || .45;
35095         this.config = c;
35096        
35097     },
35098     /**
35099      * Returns true if this region is currently visible.
35100      * @return {Boolean}
35101      */
35102     isVisible : function(){
35103         return this.visible;
35104     },
35105
35106     /**
35107      * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
35108      * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&amp;#160;")
35109      */
35110     //setCollapsedTitle : function(title){
35111     //    title = title || "&#160;";
35112      //   if(this.collapsedTitleTextEl){
35113       //      this.collapsedTitleTextEl.innerHTML = title;
35114        // }
35115     //},
35116
35117     getBox : function(){
35118         var b;
35119       //  if(!this.collapsed){
35120             b = this.el.getBox(false, true);
35121        // }else{
35122           //  b = this.collapsedEl.getBox(false, true);
35123         //}
35124         return b;
35125     },
35126
35127     getMargins : function(){
35128         return this.margins;
35129         //return this.collapsed ? this.cmargins : this.margins;
35130     },
35131 /*
35132     highlight : function(){
35133         this.el.addClass("x-layout-panel-dragover");
35134     },
35135
35136     unhighlight : function(){
35137         this.el.removeClass("x-layout-panel-dragover");
35138     },
35139 */
35140     updateBox : function(box)
35141     {
35142         if (!this.bodyEl) {
35143             return; // not rendered yet..
35144         }
35145         
35146         this.box = box;
35147         if(!this.collapsed){
35148             this.el.dom.style.left = box.x + "px";
35149             this.el.dom.style.top = box.y + "px";
35150             this.updateBody(box.width, box.height);
35151         }else{
35152             this.collapsedEl.dom.style.left = box.x + "px";
35153             this.collapsedEl.dom.style.top = box.y + "px";
35154             this.collapsedEl.setSize(box.width, box.height);
35155         }
35156         if(this.tabs){
35157             this.tabs.autoSizeTabs();
35158         }
35159     },
35160
35161     updateBody : function(w, h)
35162     {
35163         if(w !== null){
35164             this.el.setWidth(w);
35165             w -= this.el.getBorderWidth("rl");
35166             if(this.config.adjustments){
35167                 w += this.config.adjustments[0];
35168             }
35169         }
35170         if(h !== null && h > 0){
35171             this.el.setHeight(h);
35172             h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
35173             h -= this.el.getBorderWidth("tb");
35174             if(this.config.adjustments){
35175                 h += this.config.adjustments[1];
35176             }
35177             this.bodyEl.setHeight(h);
35178             if(this.tabs){
35179                 h = this.tabs.syncHeight(h);
35180             }
35181         }
35182         if(this.panelSize){
35183             w = w !== null ? w : this.panelSize.width;
35184             h = h !== null ? h : this.panelSize.height;
35185         }
35186         if(this.activePanel){
35187             var el = this.activePanel.getEl();
35188             w = w !== null ? w : el.getWidth();
35189             h = h !== null ? h : el.getHeight();
35190             this.panelSize = {width: w, height: h};
35191             this.activePanel.setSize(w, h);
35192         }
35193         if(Roo.isIE && this.tabs){
35194             this.tabs.el.repaint();
35195         }
35196     },
35197
35198     /**
35199      * Returns the container element for this region.
35200      * @return {Roo.Element}
35201      */
35202     getEl : function(){
35203         return this.el;
35204     },
35205
35206     /**
35207      * Hides this region.
35208      */
35209     hide : function(){
35210         //if(!this.collapsed){
35211             this.el.dom.style.left = "-2000px";
35212             this.el.hide();
35213         //}else{
35214          //   this.collapsedEl.dom.style.left = "-2000px";
35215          //   this.collapsedEl.hide();
35216        // }
35217         this.visible = false;
35218         this.fireEvent("visibilitychange", this, false);
35219     },
35220
35221     /**
35222      * Shows this region if it was previously hidden.
35223      */
35224     show : function(){
35225         //if(!this.collapsed){
35226             this.el.show();
35227         //}else{
35228         //    this.collapsedEl.show();
35229        // }
35230         this.visible = true;
35231         this.fireEvent("visibilitychange", this, true);
35232     },
35233 /*
35234     closeClicked : function(){
35235         if(this.activePanel){
35236             this.remove(this.activePanel);
35237         }
35238     },
35239
35240     collapseClick : function(e){
35241         if(this.isSlid){
35242            e.stopPropagation();
35243            this.slideIn();
35244         }else{
35245            e.stopPropagation();
35246            this.slideOut();
35247         }
35248     },
35249 */
35250     /**
35251      * Collapses this region.
35252      * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
35253      */
35254     /*
35255     collapse : function(skipAnim, skipCheck = false){
35256         if(this.collapsed) {
35257             return;
35258         }
35259         
35260         if(skipCheck || this.fireEvent("beforecollapse", this) != false){
35261             
35262             this.collapsed = true;
35263             if(this.split){
35264                 this.split.el.hide();
35265             }
35266             if(this.config.animate && skipAnim !== true){
35267                 this.fireEvent("invalidated", this);
35268                 this.animateCollapse();
35269             }else{
35270                 this.el.setLocation(-20000,-20000);
35271                 this.el.hide();
35272                 this.collapsedEl.show();
35273                 this.fireEvent("collapsed", this);
35274                 this.fireEvent("invalidated", this);
35275             }
35276         }
35277         
35278     },
35279 */
35280     animateCollapse : function(){
35281         // overridden
35282     },
35283
35284     /**
35285      * Expands this region if it was previously collapsed.
35286      * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
35287      * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
35288      */
35289     /*
35290     expand : function(e, skipAnim){
35291         if(e) {
35292             e.stopPropagation();
35293         }
35294         if(!this.collapsed || this.el.hasActiveFx()) {
35295             return;
35296         }
35297         if(this.isSlid){
35298             this.afterSlideIn();
35299             skipAnim = true;
35300         }
35301         this.collapsed = false;
35302         if(this.config.animate && skipAnim !== true){
35303             this.animateExpand();
35304         }else{
35305             this.el.show();
35306             if(this.split){
35307                 this.split.el.show();
35308             }
35309             this.collapsedEl.setLocation(-2000,-2000);
35310             this.collapsedEl.hide();
35311             this.fireEvent("invalidated", this);
35312             this.fireEvent("expanded", this);
35313         }
35314     },
35315 */
35316     animateExpand : function(){
35317         // overridden
35318     },
35319
35320     initTabs : function()
35321     {
35322         //this.bodyEl.setStyle("overflow", "hidden"); -- this is set in render?
35323         
35324         var ts = new Roo.bootstrap.panel.Tabs({
35325                 el: this.bodyEl.dom,
35326                 tabPosition: this.bottomTabs ? 'bottom' : 'top',
35327                 disableTooltips: this.config.disableTabTips,
35328                 toolbar : this.config.toolbar
35329             });
35330         
35331         if(this.config.hideTabs){
35332             ts.stripWrap.setDisplayed(false);
35333         }
35334         this.tabs = ts;
35335         ts.resizeTabs = this.config.resizeTabs === true;
35336         ts.minTabWidth = this.config.minTabWidth || 40;
35337         ts.maxTabWidth = this.config.maxTabWidth || 250;
35338         ts.preferredTabWidth = this.config.preferredTabWidth || 150;
35339         ts.monitorResize = false;
35340         //ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden"); // this is set in render?
35341         ts.bodyEl.addClass('roo-layout-tabs-body');
35342         this.panels.each(this.initPanelAsTab, this);
35343     },
35344
35345     initPanelAsTab : function(panel){
35346         var ti = this.tabs.addTab(
35347             panel.getEl().id,
35348             panel.getTitle(),
35349             null,
35350             this.config.closeOnTab && panel.isClosable(),
35351             panel.tpl
35352         );
35353         if(panel.tabTip !== undefined){
35354             ti.setTooltip(panel.tabTip);
35355         }
35356         ti.on("activate", function(){
35357               this.setActivePanel(panel);
35358         }, this);
35359         
35360         if(this.config.closeOnTab){
35361             ti.on("beforeclose", function(t, e){
35362                 e.cancel = true;
35363                 this.remove(panel);
35364             }, this);
35365         }
35366         
35367         panel.tabItem = ti;
35368         
35369         return ti;
35370     },
35371
35372     updatePanelTitle : function(panel, title)
35373     {
35374         if(this.activePanel == panel){
35375             this.updateTitle(title);
35376         }
35377         if(this.tabs){
35378             var ti = this.tabs.getTab(panel.getEl().id);
35379             ti.setText(title);
35380             if(panel.tabTip !== undefined){
35381                 ti.setTooltip(panel.tabTip);
35382             }
35383         }
35384     },
35385
35386     updateTitle : function(title){
35387         if(this.titleTextEl && !this.config.title){
35388             this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : "&#160;");
35389         }
35390     },
35391
35392     setActivePanel : function(panel)
35393     {
35394         panel = this.getPanel(panel);
35395         if(this.activePanel && this.activePanel != panel){
35396             this.activePanel.setActiveState(false);
35397         }
35398         this.activePanel = panel;
35399         panel.setActiveState(true);
35400         if(this.panelSize){
35401             panel.setSize(this.panelSize.width, this.panelSize.height);
35402         }
35403         if(this.closeBtn){
35404             this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
35405         }
35406         this.updateTitle(panel.getTitle());
35407         if(this.tabs){
35408             this.fireEvent("invalidated", this);
35409         }
35410         this.fireEvent("panelactivated", this, panel);
35411     },
35412
35413     /**
35414      * Shows the specified panel.
35415      * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
35416      * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
35417      */
35418     showPanel : function(panel)
35419     {
35420         panel = this.getPanel(panel);
35421         if(panel){
35422             if(this.tabs){
35423                 var tab = this.tabs.getTab(panel.getEl().id);
35424                 if(tab.isHidden()){
35425                     this.tabs.unhideTab(tab.id);
35426                 }
35427                 tab.activate();
35428             }else{
35429                 this.setActivePanel(panel);
35430             }
35431         }
35432         return panel;
35433     },
35434
35435     /**
35436      * Get the active panel for this region.
35437      * @return {Roo.ContentPanel} The active panel or null
35438      */
35439     getActivePanel : function(){
35440         return this.activePanel;
35441     },
35442
35443     validateVisibility : function(){
35444         if(this.panels.getCount() < 1){
35445             this.updateTitle("&#160;");
35446             this.closeBtn.hide();
35447             this.hide();
35448         }else{
35449             if(!this.isVisible()){
35450                 this.show();
35451             }
35452         }
35453     },
35454
35455     /**
35456      * Adds the passed ContentPanel(s) to this region.
35457      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
35458      * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
35459      */
35460     add : function(panel)
35461     {
35462         if(arguments.length > 1){
35463             for(var i = 0, len = arguments.length; i < len; i++) {
35464                 this.add(arguments[i]);
35465             }
35466             return null;
35467         }
35468         
35469         // if we have not been rendered yet, then we can not really do much of this..
35470         if (!this.bodyEl) {
35471             this.unrendered_panels.push(panel);
35472             return panel;
35473         }
35474         
35475         
35476         
35477         
35478         if(this.hasPanel(panel)){
35479             this.showPanel(panel);
35480             return panel;
35481         }
35482         panel.setRegion(this);
35483         this.panels.add(panel);
35484        /* if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
35485             // sinle panel - no tab...?? would it not be better to render it with the tabs,
35486             // and hide them... ???
35487             this.bodyEl.dom.appendChild(panel.getEl().dom);
35488             if(panel.background !== true){
35489                 this.setActivePanel(panel);
35490             }
35491             this.fireEvent("paneladded", this, panel);
35492             return panel;
35493         }
35494         */
35495         if(!this.tabs){
35496             this.initTabs();
35497         }else{
35498             this.initPanelAsTab(panel);
35499         }
35500         
35501         
35502         if(panel.background !== true){
35503             this.tabs.activate(panel.getEl().id);
35504         }
35505         this.fireEvent("paneladded", this, panel);
35506         return panel;
35507     },
35508
35509     /**
35510      * Hides the tab for the specified panel.
35511      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
35512      */
35513     hidePanel : function(panel){
35514         if(this.tabs && (panel = this.getPanel(panel))){
35515             this.tabs.hideTab(panel.getEl().id);
35516         }
35517     },
35518
35519     /**
35520      * Unhides the tab for a previously hidden panel.
35521      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
35522      */
35523     unhidePanel : function(panel){
35524         if(this.tabs && (panel = this.getPanel(panel))){
35525             this.tabs.unhideTab(panel.getEl().id);
35526         }
35527     },
35528
35529     clearPanels : function(){
35530         while(this.panels.getCount() > 0){
35531              this.remove(this.panels.first());
35532         }
35533     },
35534
35535     /**
35536      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
35537      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
35538      * @param {Boolean} preservePanel Overrides the config preservePanel option
35539      * @return {Roo.ContentPanel} The panel that was removed
35540      */
35541     remove : function(panel, preservePanel)
35542     {
35543         panel = this.getPanel(panel);
35544         if(!panel){
35545             return null;
35546         }
35547         var e = {};
35548         this.fireEvent("beforeremove", this, panel, e);
35549         if(e.cancel === true){
35550             return null;
35551         }
35552         preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
35553         var panelId = panel.getId();
35554         this.panels.removeKey(panelId);
35555         if(preservePanel){
35556             document.body.appendChild(panel.getEl().dom);
35557         }
35558         if(this.tabs){
35559             this.tabs.removeTab(panel.getEl().id);
35560         }else if (!preservePanel){
35561             this.bodyEl.dom.removeChild(panel.getEl().dom);
35562         }
35563         if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
35564             var p = this.panels.first();
35565             var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
35566             tempEl.appendChild(p.getEl().dom);
35567             this.bodyEl.update("");
35568             this.bodyEl.dom.appendChild(p.getEl().dom);
35569             tempEl = null;
35570             this.updateTitle(p.getTitle());
35571             this.tabs = null;
35572             this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
35573             this.setActivePanel(p);
35574         }
35575         panel.setRegion(null);
35576         if(this.activePanel == panel){
35577             this.activePanel = null;
35578         }
35579         if(this.config.autoDestroy !== false && preservePanel !== true){
35580             try{panel.destroy();}catch(e){}
35581         }
35582         this.fireEvent("panelremoved", this, panel);
35583         return panel;
35584     },
35585
35586     /**
35587      * Returns the TabPanel component used by this region
35588      * @return {Roo.TabPanel}
35589      */
35590     getTabs : function(){
35591         return this.tabs;
35592     },
35593
35594     createTool : function(parentEl, className){
35595         var btn = Roo.DomHelper.append(parentEl, {
35596             tag: "div",
35597             cls: "x-layout-tools-button",
35598             children: [ {
35599                 tag: "div",
35600                 cls: "roo-layout-tools-button-inner " + className,
35601                 html: "&#160;"
35602             }]
35603         }, true);
35604         btn.addClassOnOver("roo-layout-tools-button-over");
35605         return btn;
35606     }
35607 });/*
35608  * Based on:
35609  * Ext JS Library 1.1.1
35610  * Copyright(c) 2006-2007, Ext JS, LLC.
35611  *
35612  * Originally Released Under LGPL - original licence link has changed is not relivant.
35613  *
35614  * Fork - LGPL
35615  * <script type="text/javascript">
35616  */
35617  
35618
35619
35620 /**
35621  * @class Roo.SplitLayoutRegion
35622  * @extends Roo.LayoutRegion
35623  * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
35624  */
35625 Roo.bootstrap.layout.Split = function(config){
35626     this.cursor = config.cursor;
35627     Roo.bootstrap.layout.Split.superclass.constructor.call(this, config);
35628 };
35629
35630 Roo.extend(Roo.bootstrap.layout.Split, Roo.bootstrap.layout.Region,
35631 {
35632     splitTip : "Drag to resize.",
35633     collapsibleSplitTip : "Drag to resize. Double click to hide.",
35634     useSplitTips : false,
35635
35636     applyConfig : function(config){
35637         Roo.bootstrap.layout.Split.superclass.applyConfig.call(this, config);
35638     },
35639     
35640     onRender : function(ctr,pos) {
35641         
35642         Roo.bootstrap.layout.Split.superclass.onRender.call(this, ctr,pos);
35643         if(!this.config.split){
35644             return;
35645         }
35646         if(!this.split){
35647             
35648             var splitEl = Roo.DomHelper.append(ctr.dom,  {
35649                             tag: "div",
35650                             id: this.el.id + "-split",
35651                             cls: "roo-layout-split roo-layout-split-"+this.position,
35652                             html: "&#160;"
35653             });
35654             /** The SplitBar for this region 
35655             * @type Roo.SplitBar */
35656             // does not exist yet...
35657             Roo.log([this.position, this.orientation]);
35658             
35659             this.split = new Roo.bootstrap.SplitBar({
35660                 dragElement : splitEl,
35661                 resizingElement: this.el,
35662                 orientation : this.orientation
35663             });
35664             
35665             this.split.on("moved", this.onSplitMove, this);
35666             this.split.useShim = this.config.useShim === true;
35667             this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
35668             if(this.useSplitTips){
35669                 this.split.el.dom.title = this.config.collapsible ? this.collapsibleSplitTip : this.splitTip;
35670             }
35671             //if(config.collapsible){
35672             //    this.split.el.on("dblclick", this.collapse,  this);
35673             //}
35674         }
35675         if(typeof this.config.minSize != "undefined"){
35676             this.split.minSize = this.config.minSize;
35677         }
35678         if(typeof this.config.maxSize != "undefined"){
35679             this.split.maxSize = this.config.maxSize;
35680         }
35681         if(this.config.hideWhenEmpty || this.config.hidden || this.config.collapsed){
35682             this.hideSplitter();
35683         }
35684         
35685     },
35686
35687     getHMaxSize : function(){
35688          var cmax = this.config.maxSize || 10000;
35689          var center = this.mgr.getRegion("center");
35690          return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
35691     },
35692
35693     getVMaxSize : function(){
35694          var cmax = this.config.maxSize || 10000;
35695          var center = this.mgr.getRegion("center");
35696          return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
35697     },
35698
35699     onSplitMove : function(split, newSize){
35700         this.fireEvent("resized", this, newSize);
35701     },
35702     
35703     /** 
35704      * Returns the {@link Roo.SplitBar} for this region.
35705      * @return {Roo.SplitBar}
35706      */
35707     getSplitBar : function(){
35708         return this.split;
35709     },
35710     
35711     hide : function(){
35712         this.hideSplitter();
35713         Roo.bootstrap.layout.Split.superclass.hide.call(this);
35714     },
35715
35716     hideSplitter : function(){
35717         if(this.split){
35718             this.split.el.setLocation(-2000,-2000);
35719             this.split.el.hide();
35720         }
35721     },
35722
35723     show : function(){
35724         if(this.split){
35725             this.split.el.show();
35726         }
35727         Roo.bootstrap.layout.Split.superclass.show.call(this);
35728     },
35729     
35730     beforeSlide: function(){
35731         if(Roo.isGecko){// firefox overflow auto bug workaround
35732             this.bodyEl.clip();
35733             if(this.tabs) {
35734                 this.tabs.bodyEl.clip();
35735             }
35736             if(this.activePanel){
35737                 this.activePanel.getEl().clip();
35738                 
35739                 if(this.activePanel.beforeSlide){
35740                     this.activePanel.beforeSlide();
35741                 }
35742             }
35743         }
35744     },
35745     
35746     afterSlide : function(){
35747         if(Roo.isGecko){// firefox overflow auto bug workaround
35748             this.bodyEl.unclip();
35749             if(this.tabs) {
35750                 this.tabs.bodyEl.unclip();
35751             }
35752             if(this.activePanel){
35753                 this.activePanel.getEl().unclip();
35754                 if(this.activePanel.afterSlide){
35755                     this.activePanel.afterSlide();
35756                 }
35757             }
35758         }
35759     },
35760
35761     initAutoHide : function(){
35762         if(this.autoHide !== false){
35763             if(!this.autoHideHd){
35764                 var st = new Roo.util.DelayedTask(this.slideIn, this);
35765                 this.autoHideHd = {
35766                     "mouseout": function(e){
35767                         if(!e.within(this.el, true)){
35768                             st.delay(500);
35769                         }
35770                     },
35771                     "mouseover" : function(e){
35772                         st.cancel();
35773                     },
35774                     scope : this
35775                 };
35776             }
35777             this.el.on(this.autoHideHd);
35778         }
35779     },
35780
35781     clearAutoHide : function(){
35782         if(this.autoHide !== false){
35783             this.el.un("mouseout", this.autoHideHd.mouseout);
35784             this.el.un("mouseover", this.autoHideHd.mouseover);
35785         }
35786     },
35787
35788     clearMonitor : function(){
35789         Roo.get(document).un("click", this.slideInIf, this);
35790     },
35791
35792     // these names are backwards but not changed for compat
35793     slideOut : function(){
35794         if(this.isSlid || this.el.hasActiveFx()){
35795             return;
35796         }
35797         this.isSlid = true;
35798         if(this.collapseBtn){
35799             this.collapseBtn.hide();
35800         }
35801         this.closeBtnState = this.closeBtn.getStyle('display');
35802         this.closeBtn.hide();
35803         if(this.stickBtn){
35804             this.stickBtn.show();
35805         }
35806         this.el.show();
35807         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
35808         this.beforeSlide();
35809         this.el.setStyle("z-index", 10001);
35810         this.el.slideIn(this.getSlideAnchor(), {
35811             callback: function(){
35812                 this.afterSlide();
35813                 this.initAutoHide();
35814                 Roo.get(document).on("click", this.slideInIf, this);
35815                 this.fireEvent("slideshow", this);
35816             },
35817             scope: this,
35818             block: true
35819         });
35820     },
35821
35822     afterSlideIn : function(){
35823         this.clearAutoHide();
35824         this.isSlid = false;
35825         this.clearMonitor();
35826         this.el.setStyle("z-index", "");
35827         if(this.collapseBtn){
35828             this.collapseBtn.show();
35829         }
35830         this.closeBtn.setStyle('display', this.closeBtnState);
35831         if(this.stickBtn){
35832             this.stickBtn.hide();
35833         }
35834         this.fireEvent("slidehide", this);
35835     },
35836
35837     slideIn : function(cb){
35838         if(!this.isSlid || this.el.hasActiveFx()){
35839             Roo.callback(cb);
35840             return;
35841         }
35842         this.isSlid = false;
35843         this.beforeSlide();
35844         this.el.slideOut(this.getSlideAnchor(), {
35845             callback: function(){
35846                 this.el.setLeftTop(-10000, -10000);
35847                 this.afterSlide();
35848                 this.afterSlideIn();
35849                 Roo.callback(cb);
35850             },
35851             scope: this,
35852             block: true
35853         });
35854     },
35855     
35856     slideInIf : function(e){
35857         if(!e.within(this.el)){
35858             this.slideIn();
35859         }
35860     },
35861
35862     animateCollapse : function(){
35863         this.beforeSlide();
35864         this.el.setStyle("z-index", 20000);
35865         var anchor = this.getSlideAnchor();
35866         this.el.slideOut(anchor, {
35867             callback : function(){
35868                 this.el.setStyle("z-index", "");
35869                 this.collapsedEl.slideIn(anchor, {duration:.3});
35870                 this.afterSlide();
35871                 this.el.setLocation(-10000,-10000);
35872                 this.el.hide();
35873                 this.fireEvent("collapsed", this);
35874             },
35875             scope: this,
35876             block: true
35877         });
35878     },
35879
35880     animateExpand : function(){
35881         this.beforeSlide();
35882         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
35883         this.el.setStyle("z-index", 20000);
35884         this.collapsedEl.hide({
35885             duration:.1
35886         });
35887         this.el.slideIn(this.getSlideAnchor(), {
35888             callback : function(){
35889                 this.el.setStyle("z-index", "");
35890                 this.afterSlide();
35891                 if(this.split){
35892                     this.split.el.show();
35893                 }
35894                 this.fireEvent("invalidated", this);
35895                 this.fireEvent("expanded", this);
35896             },
35897             scope: this,
35898             block: true
35899         });
35900     },
35901
35902     anchors : {
35903         "west" : "left",
35904         "east" : "right",
35905         "north" : "top",
35906         "south" : "bottom"
35907     },
35908
35909     sanchors : {
35910         "west" : "l",
35911         "east" : "r",
35912         "north" : "t",
35913         "south" : "b"
35914     },
35915
35916     canchors : {
35917         "west" : "tl-tr",
35918         "east" : "tr-tl",
35919         "north" : "tl-bl",
35920         "south" : "bl-tl"
35921     },
35922
35923     getAnchor : function(){
35924         return this.anchors[this.position];
35925     },
35926
35927     getCollapseAnchor : function(){
35928         return this.canchors[this.position];
35929     },
35930
35931     getSlideAnchor : function(){
35932         return this.sanchors[this.position];
35933     },
35934
35935     getAlignAdj : function(){
35936         var cm = this.cmargins;
35937         switch(this.position){
35938             case "west":
35939                 return [0, 0];
35940             break;
35941             case "east":
35942                 return [0, 0];
35943             break;
35944             case "north":
35945                 return [0, 0];
35946             break;
35947             case "south":
35948                 return [0, 0];
35949             break;
35950         }
35951     },
35952
35953     getExpandAdj : function(){
35954         var c = this.collapsedEl, cm = this.cmargins;
35955         switch(this.position){
35956             case "west":
35957                 return [-(cm.right+c.getWidth()+cm.left), 0];
35958             break;
35959             case "east":
35960                 return [cm.right+c.getWidth()+cm.left, 0];
35961             break;
35962             case "north":
35963                 return [0, -(cm.top+cm.bottom+c.getHeight())];
35964             break;
35965             case "south":
35966                 return [0, cm.top+cm.bottom+c.getHeight()];
35967             break;
35968         }
35969     }
35970 });/*
35971  * Based on:
35972  * Ext JS Library 1.1.1
35973  * Copyright(c) 2006-2007, Ext JS, LLC.
35974  *
35975  * Originally Released Under LGPL - original licence link has changed is not relivant.
35976  *
35977  * Fork - LGPL
35978  * <script type="text/javascript">
35979  */
35980 /*
35981  * These classes are private internal classes
35982  */
35983 Roo.bootstrap.layout.Center = function(config){
35984     config.region = "center";
35985     Roo.bootstrap.layout.Region.call(this, config);
35986     this.visible = true;
35987     this.minWidth = config.minWidth || 20;
35988     this.minHeight = config.minHeight || 20;
35989 };
35990
35991 Roo.extend(Roo.bootstrap.layout.Center, Roo.bootstrap.layout.Region, {
35992     hide : function(){
35993         // center panel can't be hidden
35994     },
35995     
35996     show : function(){
35997         // center panel can't be hidden
35998     },
35999     
36000     getMinWidth: function(){
36001         return this.minWidth;
36002     },
36003     
36004     getMinHeight: function(){
36005         return this.minHeight;
36006     }
36007 });
36008
36009
36010
36011
36012  
36013
36014
36015
36016
36017
36018 Roo.bootstrap.layout.North = function(config)
36019 {
36020     config.region = 'north';
36021     config.cursor = 'n-resize';
36022     
36023     Roo.bootstrap.layout.Split.call(this, config);
36024     
36025     
36026     if(this.split){
36027         this.split.placement = Roo.bootstrap.SplitBar.TOP;
36028         this.split.orientation = Roo.bootstrap.SplitBar.VERTICAL;
36029         this.split.el.addClass("roo-layout-split-v");
36030     }
36031     var size = config.initialSize || config.height;
36032     if(typeof size != "undefined"){
36033         this.el.setHeight(size);
36034     }
36035 };
36036 Roo.extend(Roo.bootstrap.layout.North, Roo.bootstrap.layout.Split,
36037 {
36038     orientation: Roo.bootstrap.SplitBar.VERTICAL,
36039     
36040     
36041     
36042     getBox : function(){
36043         if(this.collapsed){
36044             return this.collapsedEl.getBox();
36045         }
36046         var box = this.el.getBox();
36047         if(this.split){
36048             box.height += this.split.el.getHeight();
36049         }
36050         return box;
36051     },
36052     
36053     updateBox : function(box){
36054         if(this.split && !this.collapsed){
36055             box.height -= this.split.el.getHeight();
36056             this.split.el.setLeft(box.x);
36057             this.split.el.setTop(box.y+box.height);
36058             this.split.el.setWidth(box.width);
36059         }
36060         if(this.collapsed){
36061             this.updateBody(box.width, null);
36062         }
36063         Roo.bootstrap.layout.Region.prototype.updateBox.call(this, box);
36064     }
36065 });
36066
36067
36068
36069
36070
36071 Roo.bootstrap.layout.South = function(config){
36072     config.region = 'south';
36073     config.cursor = 's-resize';
36074     Roo.bootstrap.layout.Split.call(this, config);
36075     if(this.split){
36076         this.split.placement = Roo.bootstrap.SplitBar.BOTTOM;
36077         this.split.orientation = Roo.bootstrap.SplitBar.VERTICAL;
36078         this.split.el.addClass("roo-layout-split-v");
36079     }
36080     var size = config.initialSize || config.height;
36081     if(typeof size != "undefined"){
36082         this.el.setHeight(size);
36083     }
36084 };
36085
36086 Roo.extend(Roo.bootstrap.layout.South, Roo.bootstrap.layout.Split, {
36087     orientation: Roo.bootstrap.SplitBar.VERTICAL,
36088     getBox : function(){
36089         if(this.collapsed){
36090             return this.collapsedEl.getBox();
36091         }
36092         var box = this.el.getBox();
36093         if(this.split){
36094             var sh = this.split.el.getHeight();
36095             box.height += sh;
36096             box.y -= sh;
36097         }
36098         return box;
36099     },
36100     
36101     updateBox : function(box){
36102         if(this.split && !this.collapsed){
36103             var sh = this.split.el.getHeight();
36104             box.height -= sh;
36105             box.y += sh;
36106             this.split.el.setLeft(box.x);
36107             this.split.el.setTop(box.y-sh);
36108             this.split.el.setWidth(box.width);
36109         }
36110         if(this.collapsed){
36111             this.updateBody(box.width, null);
36112         }
36113         Roo.bootstrap.layout.Region.prototype.updateBox.call(this, box);
36114     }
36115 });
36116
36117 Roo.bootstrap.layout.East = function(config){
36118     config.region = "east";
36119     config.cursor = "e-resize";
36120     Roo.bootstrap.layout.Split.call(this, config);
36121     if(this.split){
36122         this.split.placement = Roo.bootstrap.SplitBar.RIGHT;
36123         this.split.orientation = Roo.bootstrap.SplitBar.HORIZONTAL;
36124         this.split.el.addClass("roo-layout-split-h");
36125     }
36126     var size = config.initialSize || config.width;
36127     if(typeof size != "undefined"){
36128         this.el.setWidth(size);
36129     }
36130 };
36131 Roo.extend(Roo.bootstrap.layout.East, Roo.bootstrap.layout.Split, {
36132     orientation: Roo.bootstrap.SplitBar.HORIZONTAL,
36133     getBox : function(){
36134         if(this.collapsed){
36135             return this.collapsedEl.getBox();
36136         }
36137         var box = this.el.getBox();
36138         if(this.split){
36139             var sw = this.split.el.getWidth();
36140             box.width += sw;
36141             box.x -= sw;
36142         }
36143         return box;
36144     },
36145
36146     updateBox : function(box){
36147         if(this.split && !this.collapsed){
36148             var sw = this.split.el.getWidth();
36149             box.width -= sw;
36150             this.split.el.setLeft(box.x);
36151             this.split.el.setTop(box.y);
36152             this.split.el.setHeight(box.height);
36153             box.x += sw;
36154         }
36155         if(this.collapsed){
36156             this.updateBody(null, box.height);
36157         }
36158         Roo.bootstrap.layout.Region.prototype.updateBox.call(this, box);
36159     }
36160 });
36161
36162 Roo.bootstrap.layout.West = function(config){
36163     config.region = "west";
36164     config.cursor = "w-resize";
36165     
36166     Roo.bootstrap.layout.Split.call(this, config);
36167     if(this.split){
36168         this.split.placement = Roo.bootstrap.SplitBar.LEFT;
36169         this.split.orientation = Roo.bootstrap.SplitBar.HORIZONTAL;
36170         this.split.el.addClass("roo-layout-split-h");
36171     }
36172     
36173 };
36174 Roo.extend(Roo.bootstrap.layout.West, Roo.bootstrap.layout.Split, {
36175     orientation: Roo.bootstrap.SplitBar.HORIZONTAL,
36176     
36177     onRender: function(ctr, pos)
36178     {
36179         Roo.bootstrap.layout.West.superclass.onRender.call(this, ctr,pos);
36180         var size = this.config.initialSize || this.config.width;
36181         if(typeof size != "undefined"){
36182             this.el.setWidth(size);
36183         }
36184     },
36185     
36186     getBox : function(){
36187         if(this.collapsed){
36188             return this.collapsedEl.getBox();
36189         }
36190         var box = this.el.getBox();
36191         if(this.split){
36192             box.width += this.split.el.getWidth();
36193         }
36194         return box;
36195     },
36196     
36197     updateBox : function(box){
36198         if(this.split && !this.collapsed){
36199             var sw = this.split.el.getWidth();
36200             box.width -= sw;
36201             this.split.el.setLeft(box.x+box.width);
36202             this.split.el.setTop(box.y);
36203             this.split.el.setHeight(box.height);
36204         }
36205         if(this.collapsed){
36206             this.updateBody(null, box.height);
36207         }
36208         Roo.bootstrap.layout.Region.prototype.updateBox.call(this, box);
36209     }
36210 });
36211 Roo.namespace("Roo.bootstrap.panel");/*
36212  * Based on:
36213  * Ext JS Library 1.1.1
36214  * Copyright(c) 2006-2007, Ext JS, LLC.
36215  *
36216  * Originally Released Under LGPL - original licence link has changed is not relivant.
36217  *
36218  * Fork - LGPL
36219  * <script type="text/javascript">
36220  */
36221 /**
36222  * @class Roo.ContentPanel
36223  * @extends Roo.util.Observable
36224  * A basic ContentPanel element.
36225  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
36226  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
36227  * @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
36228  * @cfg {Boolean}   closable      True if the panel can be closed/removed
36229  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
36230  * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
36231  * @cfg {Toolbar}   toolbar       A toolbar for this panel
36232  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
36233  * @cfg {String} title          The title for this panel
36234  * @cfg {Array} adjustments     Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
36235  * @cfg {String} url            Calls {@link #setUrl} with this value
36236  * @cfg {String} region         (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
36237  * @cfg {String/Object} params  When used with {@link #url}, calls {@link #setUrl} with this value
36238  * @cfg {Boolean} loadOnce      When used with {@link #url}, calls {@link #setUrl} with this value
36239  * @cfg {String}    content        Raw content to fill content panel with (uses setContent on construction.)
36240  * @cfg {Boolean} badges render the badges
36241
36242  * @constructor
36243  * Create a new ContentPanel.
36244  * @param {String/HTMLElement/Roo.Element} el The container element for this panel
36245  * @param {String/Object} config A string to set only the title or a config object
36246  * @param {String} content (optional) Set the HTML content for this panel
36247  * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
36248  */
36249 Roo.bootstrap.panel.Content = function( config){
36250     
36251     this.tpl = config.tpl || false;
36252     
36253     var el = config.el;
36254     var content = config.content;
36255
36256     if(config.autoCreate){ // xtype is available if this is called from factory
36257         el = Roo.id();
36258     }
36259     this.el = Roo.get(el);
36260     if(!this.el && config && config.autoCreate){
36261         if(typeof config.autoCreate == "object"){
36262             if(!config.autoCreate.id){
36263                 config.autoCreate.id = config.id||el;
36264             }
36265             this.el = Roo.DomHelper.append(document.body,
36266                         config.autoCreate, true);
36267         }else{
36268             var elcfg =  {   tag: "div",
36269                             cls: "roo-layout-inactive-content",
36270                             id: config.id||el
36271                             };
36272             if (config.html) {
36273                 elcfg.html = config.html;
36274                 
36275             }
36276                         
36277             this.el = Roo.DomHelper.append(document.body, elcfg , true);
36278         }
36279     } 
36280     this.closable = false;
36281     this.loaded = false;
36282     this.active = false;
36283    
36284       
36285     if (config.toolbar && !config.toolbar.el && config.toolbar.xtype) {
36286         
36287         this.toolbar = new config.toolbar.xns[config.toolbar.xtype](config.toolbar);
36288         
36289         this.wrapEl = this.el; //this.el.wrap();
36290         var ti = [];
36291         if (config.toolbar.items) {
36292             ti = config.toolbar.items ;
36293             delete config.toolbar.items ;
36294         }
36295         
36296         var nitems = [];
36297         this.toolbar.render(this.wrapEl, 'before');
36298         for(var i =0;i < ti.length;i++) {
36299           //  Roo.log(['add child', items[i]]);
36300             nitems.push(this.toolbar.addxtype(Roo.apply({}, ti[i])));
36301         }
36302         this.toolbar.items = nitems;
36303         this.toolbar.el.insertBefore(this.wrapEl.dom.firstChild);
36304         delete config.toolbar;
36305         
36306     }
36307     /*
36308     // xtype created footer. - not sure if will work as we normally have to render first..
36309     if (this.footer && !this.footer.el && this.footer.xtype) {
36310         if (!this.wrapEl) {
36311             this.wrapEl = this.el.wrap();
36312         }
36313     
36314         this.footer.container = this.wrapEl.createChild();
36315          
36316         this.footer = Roo.factory(this.footer, Roo);
36317         
36318     }
36319     */
36320     
36321      if(typeof config == "string"){
36322         this.title = config;
36323     }else{
36324         Roo.apply(this, config);
36325     }
36326     
36327     if(this.resizeEl){
36328         this.resizeEl = Roo.get(this.resizeEl, true);
36329     }else{
36330         this.resizeEl = this.el;
36331     }
36332     // handle view.xtype
36333     
36334  
36335     
36336     
36337     this.addEvents({
36338         /**
36339          * @event activate
36340          * Fires when this panel is activated. 
36341          * @param {Roo.ContentPanel} this
36342          */
36343         "activate" : true,
36344         /**
36345          * @event deactivate
36346          * Fires when this panel is activated. 
36347          * @param {Roo.ContentPanel} this
36348          */
36349         "deactivate" : true,
36350
36351         /**
36352          * @event resize
36353          * Fires when this panel is resized if fitToFrame is true.
36354          * @param {Roo.ContentPanel} this
36355          * @param {Number} width The width after any component adjustments
36356          * @param {Number} height The height after any component adjustments
36357          */
36358         "resize" : true,
36359         
36360          /**
36361          * @event render
36362          * Fires when this tab is created
36363          * @param {Roo.ContentPanel} this
36364          */
36365         "render" : true
36366         
36367         
36368         
36369     });
36370     
36371
36372     
36373     
36374     if(this.autoScroll){
36375         this.resizeEl.setStyle("overflow", "auto");
36376     } else {
36377         // fix randome scrolling
36378         //this.el.on('scroll', function() {
36379         //    Roo.log('fix random scolling');
36380         //    this.scrollTo('top',0); 
36381         //});
36382     }
36383     content = content || this.content;
36384     if(content){
36385         this.setContent(content);
36386     }
36387     if(config && config.url){
36388         this.setUrl(this.url, this.params, this.loadOnce);
36389     }
36390     
36391     
36392     
36393     Roo.bootstrap.panel.Content.superclass.constructor.call(this);
36394     
36395     if (this.view && typeof(this.view.xtype) != 'undefined') {
36396         this.view.el = this.el.appendChild(document.createElement("div"));
36397         this.view = Roo.factory(this.view); 
36398         this.view.render  &&  this.view.render(false, '');  
36399     }
36400     
36401     
36402     this.fireEvent('render', this);
36403 };
36404
36405 Roo.extend(Roo.bootstrap.panel.Content, Roo.bootstrap.Component, {
36406     
36407     tabTip : '',
36408     
36409     setRegion : function(region){
36410         this.region = region;
36411         this.setActiveClass(region && !this.background);
36412     },
36413     
36414     
36415     setActiveClass: function(state)
36416     {
36417         if(state){
36418            this.el.replaceClass("roo-layout-inactive-content", "roo-layout-active-content");
36419            this.el.setStyle('position','relative');
36420         }else{
36421            this.el.replaceClass("roo-layout-active-content", "roo-layout-inactive-content");
36422            this.el.setStyle('position', 'absolute');
36423         } 
36424     },
36425     
36426     /**
36427      * Returns the toolbar for this Panel if one was configured. 
36428      * @return {Roo.Toolbar} 
36429      */
36430     getToolbar : function(){
36431         return this.toolbar;
36432     },
36433     
36434     setActiveState : function(active)
36435     {
36436         this.active = active;
36437         this.setActiveClass(active);
36438         if(!active){
36439             this.fireEvent("deactivate", this);
36440         }else{
36441             this.fireEvent("activate", this);
36442         }
36443     },
36444     /**
36445      * Updates this panel's element
36446      * @param {String} content The new content
36447      * @param {Boolean} loadScripts (optional) true to look for and process scripts
36448     */
36449     setContent : function(content, loadScripts){
36450         this.el.update(content, loadScripts);
36451     },
36452
36453     ignoreResize : function(w, h){
36454         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
36455             return true;
36456         }else{
36457             this.lastSize = {width: w, height: h};
36458             return false;
36459         }
36460     },
36461     /**
36462      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
36463      * @return {Roo.UpdateManager} The UpdateManager
36464      */
36465     getUpdateManager : function(){
36466         return this.el.getUpdateManager();
36467     },
36468      /**
36469      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
36470      * @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:
36471 <pre><code>
36472 panel.load({
36473     url: "your-url.php",
36474     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
36475     callback: yourFunction,
36476     scope: yourObject, //(optional scope)
36477     discardUrl: false,
36478     nocache: false,
36479     text: "Loading...",
36480     timeout: 30,
36481     scripts: false
36482 });
36483 </code></pre>
36484      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
36485      * 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.
36486      * @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}
36487      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
36488      * @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.
36489      * @return {Roo.ContentPanel} this
36490      */
36491     load : function(){
36492         var um = this.el.getUpdateManager();
36493         um.update.apply(um, arguments);
36494         return this;
36495     },
36496
36497
36498     /**
36499      * 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.
36500      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
36501      * @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)
36502      * @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)
36503      * @return {Roo.UpdateManager} The UpdateManager
36504      */
36505     setUrl : function(url, params, loadOnce){
36506         if(this.refreshDelegate){
36507             this.removeListener("activate", this.refreshDelegate);
36508         }
36509         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
36510         this.on("activate", this.refreshDelegate);
36511         return this.el.getUpdateManager();
36512     },
36513     
36514     _handleRefresh : function(url, params, loadOnce){
36515         if(!loadOnce || !this.loaded){
36516             var updater = this.el.getUpdateManager();
36517             updater.update(url, params, this._setLoaded.createDelegate(this));
36518         }
36519     },
36520     
36521     _setLoaded : function(){
36522         this.loaded = true;
36523     }, 
36524     
36525     /**
36526      * Returns this panel's id
36527      * @return {String} 
36528      */
36529     getId : function(){
36530         return this.el.id;
36531     },
36532     
36533     /** 
36534      * Returns this panel's element - used by regiosn to add.
36535      * @return {Roo.Element} 
36536      */
36537     getEl : function(){
36538         return this.wrapEl || this.el;
36539     },
36540     
36541    
36542     
36543     adjustForComponents : function(width, height)
36544     {
36545         //Roo.log('adjustForComponents ');
36546         if(this.resizeEl != this.el){
36547             width -= this.el.getFrameWidth('lr');
36548             height -= this.el.getFrameWidth('tb');
36549         }
36550         if(this.toolbar){
36551             var te = this.toolbar.getEl();
36552             te.setWidth(width);
36553             height -= te.getHeight();
36554         }
36555         if(this.footer){
36556             var te = this.footer.getEl();
36557             te.setWidth(width);
36558             height -= te.getHeight();
36559         }
36560         
36561         
36562         if(this.adjustments){
36563             width += this.adjustments[0];
36564             height += this.adjustments[1];
36565         }
36566         return {"width": width, "height": height};
36567     },
36568     
36569     setSize : function(width, height){
36570         if(this.fitToFrame && !this.ignoreResize(width, height)){
36571             if(this.fitContainer && this.resizeEl != this.el){
36572                 this.el.setSize(width, height);
36573             }
36574             var size = this.adjustForComponents(width, height);
36575             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
36576             this.fireEvent('resize', this, size.width, size.height);
36577         }
36578     },
36579     
36580     /**
36581      * Returns this panel's title
36582      * @return {String} 
36583      */
36584     getTitle : function(){
36585         
36586         if (typeof(this.title) != 'object') {
36587             return this.title;
36588         }
36589         
36590         var t = '';
36591         for (var k in this.title) {
36592             if (!this.title.hasOwnProperty(k)) {
36593                 continue;
36594             }
36595             
36596             if (k.indexOf('-') >= 0) {
36597                 var s = k.split('-');
36598                 for (var i = 0; i<s.length; i++) {
36599                     t += "<span class='visible-"+s[i]+"'>"+this.title[k]+"</span>";
36600                 }
36601             } else {
36602                 t += "<span class='visible-"+k+"'>"+this.title[k]+"</span>";
36603             }
36604         }
36605         return t;
36606     },
36607     
36608     /**
36609      * Set this panel's title
36610      * @param {String} title
36611      */
36612     setTitle : function(title){
36613         this.title = title;
36614         if(this.region){
36615             this.region.updatePanelTitle(this, title);
36616         }
36617     },
36618     
36619     /**
36620      * Returns true is this panel was configured to be closable
36621      * @return {Boolean} 
36622      */
36623     isClosable : function(){
36624         return this.closable;
36625     },
36626     
36627     beforeSlide : function(){
36628         this.el.clip();
36629         this.resizeEl.clip();
36630     },
36631     
36632     afterSlide : function(){
36633         this.el.unclip();
36634         this.resizeEl.unclip();
36635     },
36636     
36637     /**
36638      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
36639      *   Will fail silently if the {@link #setUrl} method has not been called.
36640      *   This does not activate the panel, just updates its content.
36641      */
36642     refresh : function(){
36643         if(this.refreshDelegate){
36644            this.loaded = false;
36645            this.refreshDelegate();
36646         }
36647     },
36648     
36649     /**
36650      * Destroys this panel
36651      */
36652     destroy : function(){
36653         this.el.removeAllListeners();
36654         var tempEl = document.createElement("span");
36655         tempEl.appendChild(this.el.dom);
36656         tempEl.innerHTML = "";
36657         this.el.remove();
36658         this.el = null;
36659     },
36660     
36661     /**
36662      * form - if the content panel contains a form - this is a reference to it.
36663      * @type {Roo.form.Form}
36664      */
36665     form : false,
36666     /**
36667      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
36668      *    This contains a reference to it.
36669      * @type {Roo.View}
36670      */
36671     view : false,
36672     
36673       /**
36674      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
36675      * <pre><code>
36676
36677 layout.addxtype({
36678        xtype : 'Form',
36679        items: [ .... ]
36680    }
36681 );
36682
36683 </code></pre>
36684      * @param {Object} cfg Xtype definition of item to add.
36685      */
36686     
36687     
36688     getChildContainer: function () {
36689         return this.getEl();
36690     }
36691     
36692     
36693     /*
36694         var  ret = new Roo.factory(cfg);
36695         return ret;
36696         
36697         
36698         // add form..
36699         if (cfg.xtype.match(/^Form$/)) {
36700             
36701             var el;
36702             //if (this.footer) {
36703             //    el = this.footer.container.insertSibling(false, 'before');
36704             //} else {
36705                 el = this.el.createChild();
36706             //}
36707
36708             this.form = new  Roo.form.Form(cfg);
36709             
36710             
36711             if ( this.form.allItems.length) {
36712                 this.form.render(el.dom);
36713             }
36714             return this.form;
36715         }
36716         // should only have one of theses..
36717         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
36718             // views.. should not be just added - used named prop 'view''
36719             
36720             cfg.el = this.el.appendChild(document.createElement("div"));
36721             // factory?
36722             
36723             var ret = new Roo.factory(cfg);
36724              
36725              ret.render && ret.render(false, ''); // render blank..
36726             this.view = ret;
36727             return ret;
36728         }
36729         return false;
36730     }
36731     \*/
36732 });
36733  
36734 /**
36735  * @class Roo.bootstrap.panel.Grid
36736  * @extends Roo.bootstrap.panel.Content
36737  * @constructor
36738  * Create a new GridPanel.
36739  * @cfg {Roo.bootstrap.Table} grid The grid for this panel
36740  * @param {Object} config A the config object
36741   
36742  */
36743
36744
36745
36746 Roo.bootstrap.panel.Grid = function(config)
36747 {
36748     
36749       
36750     this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
36751         {tag: "div", cls: "roo-layout-grid-wrapper roo-layout-inactive-content"}, true);
36752
36753     config.el = this.wrapper;
36754     //this.el = this.wrapper;
36755     
36756       if (config.container) {
36757         // ctor'ed from a Border/panel.grid
36758         
36759         
36760         this.wrapper.setStyle("overflow", "hidden");
36761         this.wrapper.addClass('roo-grid-container');
36762
36763     }
36764     
36765     
36766     if(config.toolbar){
36767         var tool_el = this.wrapper.createChild();    
36768         this.toolbar = Roo.factory(config.toolbar);
36769         var ti = [];
36770         if (config.toolbar.items) {
36771             ti = config.toolbar.items ;
36772             delete config.toolbar.items ;
36773         }
36774         
36775         var nitems = [];
36776         this.toolbar.render(tool_el);
36777         for(var i =0;i < ti.length;i++) {
36778           //  Roo.log(['add child', items[i]]);
36779             nitems.push(this.toolbar.addxtype(Roo.apply({}, ti[i])));
36780         }
36781         this.toolbar.items = nitems;
36782         
36783         delete config.toolbar;
36784     }
36785     
36786     Roo.bootstrap.panel.Grid.superclass.constructor.call(this, config);
36787     config.grid.scrollBody = true;;
36788     config.grid.monitorWindowResize = false; // turn off autosizing
36789     config.grid.autoHeight = false;
36790     config.grid.autoWidth = false;
36791     
36792     this.grid = new config.grid.xns[config.grid.xtype](config.grid);
36793     
36794     if (config.background) {
36795         // render grid on panel activation (if panel background)
36796         this.on('activate', function(gp) {
36797             if (!gp.grid.rendered) {
36798                 gp.grid.render(this.wrapper);
36799                 gp.grid.getGridEl().replaceClass("roo-layout-inactive-content", "roo-layout-component-panel");   
36800             }
36801         });
36802             
36803     } else {
36804         this.grid.render(this.wrapper);
36805         this.grid.getGridEl().replaceClass("roo-layout-inactive-content", "roo-layout-component-panel");               
36806
36807     }
36808     //this.wrapper.dom.appendChild(config.grid.getGridEl().dom);
36809     // ??? needed ??? config.el = this.wrapper;
36810     
36811     
36812     
36813   
36814     // xtype created footer. - not sure if will work as we normally have to render first..
36815     if (this.footer && !this.footer.el && this.footer.xtype) {
36816         
36817         var ctr = this.grid.getView().getFooterPanel(true);
36818         this.footer.dataSource = this.grid.dataSource;
36819         this.footer = Roo.factory(this.footer, Roo);
36820         this.footer.render(ctr);
36821         
36822     }
36823     
36824     
36825     
36826     
36827      
36828 };
36829
36830 Roo.extend(Roo.bootstrap.panel.Grid, Roo.bootstrap.panel.Content, {
36831     getId : function(){
36832         return this.grid.id;
36833     },
36834     
36835     /**
36836      * Returns the grid for this panel
36837      * @return {Roo.bootstrap.Table} 
36838      */
36839     getGrid : function(){
36840         return this.grid;    
36841     },
36842     
36843     setSize : function(width, height){
36844         if(!this.ignoreResize(width, height)){
36845             var grid = this.grid;
36846             var size = this.adjustForComponents(width, height);
36847             var gridel = grid.getGridEl();
36848             gridel.setSize(size.width, size.height);
36849             /*
36850             var thd = grid.getGridEl().select('thead',true).first();
36851             var tbd = grid.getGridEl().select('tbody', true).first();
36852             if (tbd) {
36853                 tbd.setSize(width, height - thd.getHeight());
36854             }
36855             */
36856             grid.autoSize();
36857         }
36858     },
36859      
36860     
36861     
36862     beforeSlide : function(){
36863         this.grid.getView().scroller.clip();
36864     },
36865     
36866     afterSlide : function(){
36867         this.grid.getView().scroller.unclip();
36868     },
36869     
36870     destroy : function(){
36871         this.grid.destroy();
36872         delete this.grid;
36873         Roo.bootstrap.panel.Grid.superclass.destroy.call(this); 
36874     }
36875 });
36876
36877 /**
36878  * @class Roo.bootstrap.panel.Nest
36879  * @extends Roo.bootstrap.panel.Content
36880  * @constructor
36881  * Create a new Panel, that can contain a layout.Border.
36882  * 
36883  * 
36884  * @param {Roo.BorderLayout} layout The layout for this panel
36885  * @param {String/Object} config A string to set only the title or a config object
36886  */
36887 Roo.bootstrap.panel.Nest = function(config)
36888 {
36889     // construct with only one argument..
36890     /* FIXME - implement nicer consturctors
36891     if (layout.layout) {
36892         config = layout;
36893         layout = config.layout;
36894         delete config.layout;
36895     }
36896     if (layout.xtype && !layout.getEl) {
36897         // then layout needs constructing..
36898         layout = Roo.factory(layout, Roo);
36899     }
36900     */
36901     
36902     config.el =  config.layout.getEl();
36903     
36904     Roo.bootstrap.panel.Nest.superclass.constructor.call(this, config);
36905     
36906     config.layout.monitorWindowResize = false; // turn off autosizing
36907     this.layout = config.layout;
36908     this.layout.getEl().addClass("roo-layout-nested-layout");
36909     
36910     
36911     
36912     
36913 };
36914
36915 Roo.extend(Roo.bootstrap.panel.Nest, Roo.bootstrap.panel.Content, {
36916
36917     setSize : function(width, height){
36918         if(!this.ignoreResize(width, height)){
36919             var size = this.adjustForComponents(width, height);
36920             var el = this.layout.getEl();
36921             if (size.height < 1) {
36922                 el.setWidth(size.width);   
36923             } else {
36924                 el.setSize(size.width, size.height);
36925             }
36926             var touch = el.dom.offsetWidth;
36927             this.layout.layout();
36928             // ie requires a double layout on the first pass
36929             if(Roo.isIE && !this.initialized){
36930                 this.initialized = true;
36931                 this.layout.layout();
36932             }
36933         }
36934     },
36935     
36936     // activate all subpanels if not currently active..
36937     
36938     setActiveState : function(active){
36939         this.active = active;
36940         this.setActiveClass(active);
36941         
36942         if(!active){
36943             this.fireEvent("deactivate", this);
36944             return;
36945         }
36946         
36947         this.fireEvent("activate", this);
36948         // not sure if this should happen before or after..
36949         if (!this.layout) {
36950             return; // should not happen..
36951         }
36952         var reg = false;
36953         for (var r in this.layout.regions) {
36954             reg = this.layout.getRegion(r);
36955             if (reg.getActivePanel()) {
36956                 //reg.showPanel(reg.getActivePanel()); // force it to activate.. 
36957                 reg.setActivePanel(reg.getActivePanel());
36958                 continue;
36959             }
36960             if (!reg.panels.length) {
36961                 continue;
36962             }
36963             reg.showPanel(reg.getPanel(0));
36964         }
36965         
36966         
36967         
36968         
36969     },
36970     
36971     /**
36972      * Returns the nested BorderLayout for this panel
36973      * @return {Roo.BorderLayout} 
36974      */
36975     getLayout : function(){
36976         return this.layout;
36977     },
36978     
36979      /**
36980      * Adds a xtype elements to the layout of the nested panel
36981      * <pre><code>
36982
36983 panel.addxtype({
36984        xtype : 'ContentPanel',
36985        region: 'west',
36986        items: [ .... ]
36987    }
36988 );
36989
36990 panel.addxtype({
36991         xtype : 'NestedLayoutPanel',
36992         region: 'west',
36993         layout: {
36994            center: { },
36995            west: { }   
36996         },
36997         items : [ ... list of content panels or nested layout panels.. ]
36998    }
36999 );
37000 </code></pre>
37001      * @param {Object} cfg Xtype definition of item to add.
37002      */
37003     addxtype : function(cfg) {
37004         return this.layout.addxtype(cfg);
37005     
37006     }
37007 });        /*
37008  * Based on:
37009  * Ext JS Library 1.1.1
37010  * Copyright(c) 2006-2007, Ext JS, LLC.
37011  *
37012  * Originally Released Under LGPL - original licence link has changed is not relivant.
37013  *
37014  * Fork - LGPL
37015  * <script type="text/javascript">
37016  */
37017 /**
37018  * @class Roo.TabPanel
37019  * @extends Roo.util.Observable
37020  * A lightweight tab container.
37021  * <br><br>
37022  * Usage:
37023  * <pre><code>
37024 // basic tabs 1, built from existing content
37025 var tabs = new Roo.TabPanel("tabs1");
37026 tabs.addTab("script", "View Script");
37027 tabs.addTab("markup", "View Markup");
37028 tabs.activate("script");
37029
37030 // more advanced tabs, built from javascript
37031 var jtabs = new Roo.TabPanel("jtabs");
37032 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
37033
37034 // set up the UpdateManager
37035 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
37036 var updater = tab2.getUpdateManager();
37037 updater.setDefaultUrl("ajax1.htm");
37038 tab2.on('activate', updater.refresh, updater, true);
37039
37040 // Use setUrl for Ajax loading
37041 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
37042 tab3.setUrl("ajax2.htm", null, true);
37043
37044 // Disabled tab
37045 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
37046 tab4.disable();
37047
37048 jtabs.activate("jtabs-1");
37049  * </code></pre>
37050  * @constructor
37051  * Create a new TabPanel.
37052  * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
37053  * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
37054  */
37055 Roo.bootstrap.panel.Tabs = function(config){
37056     /**
37057     * The container element for this TabPanel.
37058     * @type Roo.Element
37059     */
37060     this.el = Roo.get(config.el);
37061     delete config.el;
37062     if(config){
37063         if(typeof config == "boolean"){
37064             this.tabPosition = config ? "bottom" : "top";
37065         }else{
37066             Roo.apply(this, config);
37067         }
37068     }
37069     
37070     if(this.tabPosition == "bottom"){
37071         this.bodyEl = Roo.get(this.createBody(this.el.dom));
37072         this.el.addClass("roo-tabs-bottom");
37073     }
37074     this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
37075     this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
37076     this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
37077     if(Roo.isIE){
37078         Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
37079     }
37080     if(this.tabPosition != "bottom"){
37081         /** The body element that contains {@link Roo.TabPanelItem} bodies. +
37082          * @type Roo.Element
37083          */
37084         this.bodyEl = Roo.get(this.createBody(this.el.dom));
37085         this.el.addClass("roo-tabs-top");
37086     }
37087     this.items = [];
37088
37089     this.bodyEl.setStyle("position", "relative");
37090
37091     this.active = null;
37092     this.activateDelegate = this.activate.createDelegate(this);
37093
37094     this.addEvents({
37095         /**
37096          * @event tabchange
37097          * Fires when the active tab changes
37098          * @param {Roo.TabPanel} this
37099          * @param {Roo.TabPanelItem} activePanel The new active tab
37100          */
37101         "tabchange": true,
37102         /**
37103          * @event beforetabchange
37104          * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
37105          * @param {Roo.TabPanel} this
37106          * @param {Object} e Set cancel to true on this object to cancel the tab change
37107          * @param {Roo.TabPanelItem} tab The tab being changed to
37108          */
37109         "beforetabchange" : true
37110     });
37111
37112     Roo.EventManager.onWindowResize(this.onResize, this);
37113     this.cpad = this.el.getPadding("lr");
37114     this.hiddenCount = 0;
37115
37116
37117     // toolbar on the tabbar support...
37118     if (this.toolbar) {
37119         alert("no toolbar support yet");
37120         this.toolbar  = false;
37121         /*
37122         var tcfg = this.toolbar;
37123         tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');  
37124         this.toolbar = new Roo.Toolbar(tcfg);
37125         if (Roo.isSafari) {
37126             var tbl = tcfg.container.child('table', true);
37127             tbl.setAttribute('width', '100%');
37128         }
37129         */
37130         
37131     }
37132    
37133
37134
37135     Roo.bootstrap.panel.Tabs.superclass.constructor.call(this);
37136 };
37137
37138 Roo.extend(Roo.bootstrap.panel.Tabs, Roo.util.Observable, {
37139     /*
37140      *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
37141      */
37142     tabPosition : "top",
37143     /*
37144      *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
37145      */
37146     currentTabWidth : 0,
37147     /*
37148      *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
37149      */
37150     minTabWidth : 40,
37151     /*
37152      *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
37153      */
37154     maxTabWidth : 250,
37155     /*
37156      *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
37157      */
37158     preferredTabWidth : 175,
37159     /*
37160      *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
37161      */
37162     resizeTabs : false,
37163     /*
37164      *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
37165      */
37166     monitorResize : true,
37167     /*
37168      *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar. 
37169      */
37170     toolbar : false,
37171
37172     /**
37173      * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
37174      * @param {String} id The id of the div to use <b>or create</b>
37175      * @param {String} text The text for the tab
37176      * @param {String} content (optional) Content to put in the TabPanelItem body
37177      * @param {Boolean} closable (optional) True to create a close icon on the tab
37178      * @return {Roo.TabPanelItem} The created TabPanelItem
37179      */
37180     addTab : function(id, text, content, closable, tpl)
37181     {
37182         var item = new Roo.bootstrap.panel.TabItem({
37183             panel: this,
37184             id : id,
37185             text : text,
37186             closable : closable,
37187             tpl : tpl
37188         });
37189         this.addTabItem(item);
37190         if(content){
37191             item.setContent(content);
37192         }
37193         return item;
37194     },
37195
37196     /**
37197      * Returns the {@link Roo.TabPanelItem} with the specified id/index
37198      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
37199      * @return {Roo.TabPanelItem}
37200      */
37201     getTab : function(id){
37202         return this.items[id];
37203     },
37204
37205     /**
37206      * Hides the {@link Roo.TabPanelItem} with the specified id/index
37207      * @param {String/Number} id The id or index of the TabPanelItem to hide.
37208      */
37209     hideTab : function(id){
37210         var t = this.items[id];
37211         if(!t.isHidden()){
37212            t.setHidden(true);
37213            this.hiddenCount++;
37214            this.autoSizeTabs();
37215         }
37216     },
37217
37218     /**
37219      * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
37220      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
37221      */
37222     unhideTab : function(id){
37223         var t = this.items[id];
37224         if(t.isHidden()){
37225            t.setHidden(false);
37226            this.hiddenCount--;
37227            this.autoSizeTabs();
37228         }
37229     },
37230
37231     /**
37232      * Adds an existing {@link Roo.TabPanelItem}.
37233      * @param {Roo.TabPanelItem} item The TabPanelItem to add
37234      */
37235     addTabItem : function(item){
37236         this.items[item.id] = item;
37237         this.items.push(item);
37238       //  if(this.resizeTabs){
37239     //       item.setWidth(this.currentTabWidth || this.preferredTabWidth);
37240   //         this.autoSizeTabs();
37241 //        }else{
37242 //            item.autoSize();
37243        // }
37244     },
37245
37246     /**
37247      * Removes a {@link Roo.TabPanelItem}.
37248      * @param {String/Number} id The id or index of the TabPanelItem to remove.
37249      */
37250     removeTab : function(id){
37251         var items = this.items;
37252         var tab = items[id];
37253         if(!tab) { return; }
37254         var index = items.indexOf(tab);
37255         if(this.active == tab && items.length > 1){
37256             var newTab = this.getNextAvailable(index);
37257             if(newTab) {
37258                 newTab.activate();
37259             }
37260         }
37261         this.stripEl.dom.removeChild(tab.pnode.dom);
37262         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
37263             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
37264         }
37265         items.splice(index, 1);
37266         delete this.items[tab.id];
37267         tab.fireEvent("close", tab);
37268         tab.purgeListeners();
37269         this.autoSizeTabs();
37270     },
37271
37272     getNextAvailable : function(start){
37273         var items = this.items;
37274         var index = start;
37275         // look for a next tab that will slide over to
37276         // replace the one being removed
37277         while(index < items.length){
37278             var item = items[++index];
37279             if(item && !item.isHidden()){
37280                 return item;
37281             }
37282         }
37283         // if one isn't found select the previous tab (on the left)
37284         index = start;
37285         while(index >= 0){
37286             var item = items[--index];
37287             if(item && !item.isHidden()){
37288                 return item;
37289             }
37290         }
37291         return null;
37292     },
37293
37294     /**
37295      * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
37296      * @param {String/Number} id The id or index of the TabPanelItem to disable.
37297      */
37298     disableTab : function(id){
37299         var tab = this.items[id];
37300         if(tab && this.active != tab){
37301             tab.disable();
37302         }
37303     },
37304
37305     /**
37306      * Enables a {@link Roo.TabPanelItem} that is disabled.
37307      * @param {String/Number} id The id or index of the TabPanelItem to enable.
37308      */
37309     enableTab : function(id){
37310         var tab = this.items[id];
37311         tab.enable();
37312     },
37313
37314     /**
37315      * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
37316      * @param {String/Number} id The id or index of the TabPanelItem to activate.
37317      * @return {Roo.TabPanelItem} The TabPanelItem.
37318      */
37319     activate : function(id){
37320         var tab = this.items[id];
37321         if(!tab){
37322             return null;
37323         }
37324         if(tab == this.active || tab.disabled){
37325             return tab;
37326         }
37327         var e = {};
37328         this.fireEvent("beforetabchange", this, e, tab);
37329         if(e.cancel !== true && !tab.disabled){
37330             if(this.active){
37331                 this.active.hide();
37332             }
37333             this.active = this.items[id];
37334             this.active.show();
37335             this.fireEvent("tabchange", this, this.active);
37336         }
37337         return tab;
37338     },
37339
37340     /**
37341      * Gets the active {@link Roo.TabPanelItem}.
37342      * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
37343      */
37344     getActiveTab : function(){
37345         return this.active;
37346     },
37347
37348     /**
37349      * Updates the tab body element to fit the height of the container element
37350      * for overflow scrolling
37351      * @param {Number} targetHeight (optional) Override the starting height from the elements height
37352      */
37353     syncHeight : function(targetHeight){
37354         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
37355         var bm = this.bodyEl.getMargins();
37356         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
37357         this.bodyEl.setHeight(newHeight);
37358         return newHeight;
37359     },
37360
37361     onResize : function(){
37362         if(this.monitorResize){
37363             this.autoSizeTabs();
37364         }
37365     },
37366
37367     /**
37368      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
37369      */
37370     beginUpdate : function(){
37371         this.updating = true;
37372     },
37373
37374     /**
37375      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
37376      */
37377     endUpdate : function(){
37378         this.updating = false;
37379         this.autoSizeTabs();
37380     },
37381
37382     /**
37383      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
37384      */
37385     autoSizeTabs : function(){
37386         var count = this.items.length;
37387         var vcount = count - this.hiddenCount;
37388         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
37389             return;
37390         }
37391         var w = Math.max(this.el.getWidth() - this.cpad, 10);
37392         var availWidth = Math.floor(w / vcount);
37393         var b = this.stripBody;
37394         if(b.getWidth() > w){
37395             var tabs = this.items;
37396             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
37397             if(availWidth < this.minTabWidth){
37398                 /*if(!this.sleft){    // incomplete scrolling code
37399                     this.createScrollButtons();
37400                 }
37401                 this.showScroll();
37402                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
37403             }
37404         }else{
37405             if(this.currentTabWidth < this.preferredTabWidth){
37406                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
37407             }
37408         }
37409     },
37410
37411     /**
37412      * Returns the number of tabs in this TabPanel.
37413      * @return {Number}
37414      */
37415      getCount : function(){
37416          return this.items.length;
37417      },
37418
37419     /**
37420      * Resizes all the tabs to the passed width
37421      * @param {Number} The new width
37422      */
37423     setTabWidth : function(width){
37424         this.currentTabWidth = width;
37425         for(var i = 0, len = this.items.length; i < len; i++) {
37426                 if(!this.items[i].isHidden()) {
37427                 this.items[i].setWidth(width);
37428             }
37429         }
37430     },
37431
37432     /**
37433      * Destroys this TabPanel
37434      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
37435      */
37436     destroy : function(removeEl){
37437         Roo.EventManager.removeResizeListener(this.onResize, this);
37438         for(var i = 0, len = this.items.length; i < len; i++){
37439             this.items[i].purgeListeners();
37440         }
37441         if(removeEl === true){
37442             this.el.update("");
37443             this.el.remove();
37444         }
37445     },
37446     
37447     createStrip : function(container)
37448     {
37449         var strip = document.createElement("nav");
37450         strip.className = "navbar navbar-default"; //"x-tabs-wrap";
37451         container.appendChild(strip);
37452         return strip;
37453     },
37454     
37455     createStripList : function(strip)
37456     {
37457         // div wrapper for retard IE
37458         // returns the "tr" element.
37459         strip.innerHTML = '<ul class="nav nav-tabs" role="tablist"></ul>';
37460         //'<div class="x-tabs-strip-wrap">'+
37461           //  '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
37462           //  '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
37463         return strip.firstChild; //.firstChild.firstChild.firstChild;
37464     },
37465     createBody : function(container)
37466     {
37467         var body = document.createElement("div");
37468         Roo.id(body, "tab-body");
37469         //Roo.fly(body).addClass("x-tabs-body");
37470         Roo.fly(body).addClass("tab-content");
37471         container.appendChild(body);
37472         return body;
37473     },
37474     createItemBody :function(bodyEl, id){
37475         var body = Roo.getDom(id);
37476         if(!body){
37477             body = document.createElement("div");
37478             body.id = id;
37479         }
37480         //Roo.fly(body).addClass("x-tabs-item-body");
37481         Roo.fly(body).addClass("tab-pane");
37482          bodyEl.insertBefore(body, bodyEl.firstChild);
37483         return body;
37484     },
37485     /** @private */
37486     createStripElements :  function(stripEl, text, closable, tpl)
37487     {
37488         var td = document.createElement("li"); // was td..
37489         
37490         
37491         //stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
37492         
37493         
37494         stripEl.appendChild(td);
37495         /*if(closable){
37496             td.className = "x-tabs-closable";
37497             if(!this.closeTpl){
37498                 this.closeTpl = new Roo.Template(
37499                    '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
37500                    '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
37501                    '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
37502                 );
37503             }
37504             var el = this.closeTpl.overwrite(td, {"text": text});
37505             var close = el.getElementsByTagName("div")[0];
37506             var inner = el.getElementsByTagName("em")[0];
37507             return {"el": el, "close": close, "inner": inner};
37508         } else {
37509         */
37510         // not sure what this is..
37511 //            if(!this.tabTpl){
37512                 //this.tabTpl = new Roo.Template(
37513                 //   '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
37514                 //   '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
37515                 //);
37516 //                this.tabTpl = new Roo.Template(
37517 //                   '<a href="#">' +
37518 //                   '<span unselectable="on"' +
37519 //                            (this.disableTooltips ? '' : ' title="{text}"') +
37520 //                            ' >{text}</span></a>'
37521 //                );
37522 //                
37523 //            }
37524
37525
37526             var template = tpl || this.tabTpl || false;
37527             
37528             if(!template){
37529                 
37530                 template = new Roo.Template(
37531                    '<a href="#">' +
37532                    '<span unselectable="on"' +
37533                             (this.disableTooltips ? '' : ' title="{text}"') +
37534                             ' >{text}</span></a>'
37535                 );
37536             }
37537             
37538             switch (typeof(template)) {
37539                 case 'object' :
37540                     break;
37541                 case 'string' :
37542                     template = new Roo.Template(template);
37543                     break;
37544                 default :
37545                     break;
37546             }
37547             
37548             var el = template.overwrite(td, {"text": text});
37549             
37550             var inner = el.getElementsByTagName("span")[0];
37551             
37552             return {"el": el, "inner": inner};
37553             
37554     }
37555         
37556     
37557 });
37558
37559 /**
37560  * @class Roo.TabPanelItem
37561  * @extends Roo.util.Observable
37562  * Represents an individual item (tab plus body) in a TabPanel.
37563  * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
37564  * @param {String} id The id of this TabPanelItem
37565  * @param {String} text The text for the tab of this TabPanelItem
37566  * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
37567  */
37568 Roo.bootstrap.panel.TabItem = function(config){
37569     /**
37570      * The {@link Roo.TabPanel} this TabPanelItem belongs to
37571      * @type Roo.TabPanel
37572      */
37573     this.tabPanel = config.panel;
37574     /**
37575      * The id for this TabPanelItem
37576      * @type String
37577      */
37578     this.id = config.id;
37579     /** @private */
37580     this.disabled = false;
37581     /** @private */
37582     this.text = config.text;
37583     /** @private */
37584     this.loaded = false;
37585     this.closable = config.closable;
37586
37587     /**
37588      * The body element for this TabPanelItem.
37589      * @type Roo.Element
37590      */
37591     this.bodyEl = Roo.get(this.tabPanel.createItemBody(this.tabPanel.bodyEl.dom, config.id));
37592     this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
37593     this.bodyEl.setStyle("display", "block");
37594     this.bodyEl.setStyle("zoom", "1");
37595     //this.hideAction();
37596
37597     var els = this.tabPanel.createStripElements(this.tabPanel.stripEl.dom, config.text, config.closable, config.tpl);
37598     /** @private */
37599     this.el = Roo.get(els.el);
37600     this.inner = Roo.get(els.inner, true);
37601     this.textEl = Roo.get(this.el.dom.firstChild, true);
37602     this.pnode = Roo.get(els.el.parentNode, true);
37603     this.el.on("mousedown", this.onTabMouseDown, this);
37604     this.el.on("click", this.onTabClick, this);
37605     /** @private */
37606     if(config.closable){
37607         var c = Roo.get(els.close, true);
37608         c.dom.title = this.closeText;
37609         c.addClassOnOver("close-over");
37610         c.on("click", this.closeClick, this);
37611      }
37612
37613     this.addEvents({
37614          /**
37615          * @event activate
37616          * Fires when this tab becomes the active tab.
37617          * @param {Roo.TabPanel} tabPanel The parent TabPanel
37618          * @param {Roo.TabPanelItem} this
37619          */
37620         "activate": true,
37621         /**
37622          * @event beforeclose
37623          * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
37624          * @param {Roo.TabPanelItem} this
37625          * @param {Object} e Set cancel to true on this object to cancel the close.
37626          */
37627         "beforeclose": true,
37628         /**
37629          * @event close
37630          * Fires when this tab is closed.
37631          * @param {Roo.TabPanelItem} this
37632          */
37633          "close": true,
37634         /**
37635          * @event deactivate
37636          * Fires when this tab is no longer the active tab.
37637          * @param {Roo.TabPanel} tabPanel The parent TabPanel
37638          * @param {Roo.TabPanelItem} this
37639          */
37640          "deactivate" : true
37641     });
37642     this.hidden = false;
37643
37644     Roo.bootstrap.panel.TabItem.superclass.constructor.call(this);
37645 };
37646
37647 Roo.extend(Roo.bootstrap.panel.TabItem, Roo.util.Observable,
37648            {
37649     purgeListeners : function(){
37650        Roo.util.Observable.prototype.purgeListeners.call(this);
37651        this.el.removeAllListeners();
37652     },
37653     /**
37654      * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
37655      */
37656     show : function(){
37657         this.pnode.addClass("active");
37658         this.showAction();
37659         if(Roo.isOpera){
37660             this.tabPanel.stripWrap.repaint();
37661         }
37662         this.fireEvent("activate", this.tabPanel, this);
37663     },
37664
37665     /**
37666      * Returns true if this tab is the active tab.
37667      * @return {Boolean}
37668      */
37669     isActive : function(){
37670         return this.tabPanel.getActiveTab() == this;
37671     },
37672
37673     /**
37674      * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
37675      */
37676     hide : function(){
37677         this.pnode.removeClass("active");
37678         this.hideAction();
37679         this.fireEvent("deactivate", this.tabPanel, this);
37680     },
37681
37682     hideAction : function(){
37683         this.bodyEl.hide();
37684         this.bodyEl.setStyle("position", "absolute");
37685         this.bodyEl.setLeft("-20000px");
37686         this.bodyEl.setTop("-20000px");
37687     },
37688
37689     showAction : function(){
37690         this.bodyEl.setStyle("position", "relative");
37691         this.bodyEl.setTop("");
37692         this.bodyEl.setLeft("");
37693         this.bodyEl.show();
37694     },
37695
37696     /**
37697      * Set the tooltip for the tab.
37698      * @param {String} tooltip The tab's tooltip
37699      */
37700     setTooltip : function(text){
37701         if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
37702             this.textEl.dom.qtip = text;
37703             this.textEl.dom.removeAttribute('title');
37704         }else{
37705             this.textEl.dom.title = text;
37706         }
37707     },
37708
37709     onTabClick : function(e){
37710         e.preventDefault();
37711         this.tabPanel.activate(this.id);
37712     },
37713
37714     onTabMouseDown : function(e){
37715         e.preventDefault();
37716         this.tabPanel.activate(this.id);
37717     },
37718 /*
37719     getWidth : function(){
37720         return this.inner.getWidth();
37721     },
37722
37723     setWidth : function(width){
37724         var iwidth = width - this.pnode.getPadding("lr");
37725         this.inner.setWidth(iwidth);
37726         this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
37727         this.pnode.setWidth(width);
37728     },
37729 */
37730     /**
37731      * Show or hide the tab
37732      * @param {Boolean} hidden True to hide or false to show.
37733      */
37734     setHidden : function(hidden){
37735         this.hidden = hidden;
37736         this.pnode.setStyle("display", hidden ? "none" : "");
37737     },
37738
37739     /**
37740      * Returns true if this tab is "hidden"
37741      * @return {Boolean}
37742      */
37743     isHidden : function(){
37744         return this.hidden;
37745     },
37746
37747     /**
37748      * Returns the text for this tab
37749      * @return {String}
37750      */
37751     getText : function(){
37752         return this.text;
37753     },
37754     /*
37755     autoSize : function(){
37756         //this.el.beginMeasure();
37757         this.textEl.setWidth(1);
37758         /*
37759          *  #2804 [new] Tabs in Roojs
37760          *  increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
37761          */
37762         //this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
37763         //this.el.endMeasure();
37764     //},
37765
37766     /**
37767      * Sets the text for the tab (Note: this also sets the tooltip text)
37768      * @param {String} text The tab's text and tooltip
37769      */
37770     setText : function(text){
37771         this.text = text;
37772         this.textEl.update(text);
37773         this.setTooltip(text);
37774         //if(!this.tabPanel.resizeTabs){
37775         //    this.autoSize();
37776         //}
37777     },
37778     /**
37779      * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
37780      */
37781     activate : function(){
37782         this.tabPanel.activate(this.id);
37783     },
37784
37785     /**
37786      * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
37787      */
37788     disable : function(){
37789         if(this.tabPanel.active != this){
37790             this.disabled = true;
37791             this.pnode.addClass("disabled");
37792         }
37793     },
37794
37795     /**
37796      * Enables this TabPanelItem if it was previously disabled.
37797      */
37798     enable : function(){
37799         this.disabled = false;
37800         this.pnode.removeClass("disabled");
37801     },
37802
37803     /**
37804      * Sets the content for this TabPanelItem.
37805      * @param {String} content The content
37806      * @param {Boolean} loadScripts true to look for and load scripts
37807      */
37808     setContent : function(content, loadScripts){
37809         this.bodyEl.update(content, loadScripts);
37810     },
37811
37812     /**
37813      * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
37814      * @return {Roo.UpdateManager} The UpdateManager
37815      */
37816     getUpdateManager : function(){
37817         return this.bodyEl.getUpdateManager();
37818     },
37819
37820     /**
37821      * Set a URL to be used to load the content for this TabPanelItem.
37822      * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
37823      * @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)
37824      * @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)
37825      * @return {Roo.UpdateManager} The UpdateManager
37826      */
37827     setUrl : function(url, params, loadOnce){
37828         if(this.refreshDelegate){
37829             this.un('activate', this.refreshDelegate);
37830         }
37831         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
37832         this.on("activate", this.refreshDelegate);
37833         return this.bodyEl.getUpdateManager();
37834     },
37835
37836     /** @private */
37837     _handleRefresh : function(url, params, loadOnce){
37838         if(!loadOnce || !this.loaded){
37839             var updater = this.bodyEl.getUpdateManager();
37840             updater.update(url, params, this._setLoaded.createDelegate(this));
37841         }
37842     },
37843
37844     /**
37845      *   Forces a content refresh from the URL specified in the {@link #setUrl} method.
37846      *   Will fail silently if the setUrl method has not been called.
37847      *   This does not activate the panel, just updates its content.
37848      */
37849     refresh : function(){
37850         if(this.refreshDelegate){
37851            this.loaded = false;
37852            this.refreshDelegate();
37853         }
37854     },
37855
37856     /** @private */
37857     _setLoaded : function(){
37858         this.loaded = true;
37859     },
37860
37861     /** @private */
37862     closeClick : function(e){
37863         var o = {};
37864         e.stopEvent();
37865         this.fireEvent("beforeclose", this, o);
37866         if(o.cancel !== true){
37867             this.tabPanel.removeTab(this.id);
37868         }
37869     },
37870     /**
37871      * The text displayed in the tooltip for the close icon.
37872      * @type String
37873      */
37874     closeText : "Close this tab"
37875 });
37876 /*
37877  * - LGPL
37878  *
37879  * element
37880  * 
37881  */
37882
37883 /**
37884  * @class Roo.bootstrap.PhoneInput
37885  * @extends Roo.bootstrap.TriggerField
37886  * Bootstrap PhoneInput class
37887  * 
37888  * @constructor
37889  * Create a new PhoneInput
37890  * @param {Object} config The config object
37891 */
37892
37893 Roo.bootstrap.PhoneInput = function(config){
37894     
37895     Roo.bootstrap.PhoneInput.superclass.constructor.call(this, config);
37896     
37897     this.addEvents({
37898         /**
37899          * @event expand
37900          * Fires when the dropdown list is expanded
37901              * @param {Roo.bootstrap.ComboBox} combo This combo box
37902              */
37903         'expand' : true,
37904         /**
37905          * @event collapse
37906          * Fires when the dropdown list is collapsed
37907              * @param {Roo.bootstrap.ComboBox} combo This combo box
37908              */
37909         'collapse' : true,
37910         /**
37911          * @event beforeselect
37912          * Fires before a list item is selected. Return false to cancel the selection.
37913              * @param {Roo.bootstrap.ComboBox} combo This combo box
37914              * @param {Roo.data.Record} record The data record returned from the underlying store
37915              * @param {Number} index The index of the selected item in the dropdown list
37916              */
37917         'beforeselect' : true,
37918         /**
37919          * @event select
37920          * Fires when a list item is selected
37921              * @param {Roo.bootstrap.ComboBox} combo This combo box
37922              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
37923              * @param {Number} index The index of the selected item in the dropdown list
37924              */
37925         'select' : true,
37926         /**
37927          * @event beforequery
37928          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
37929          * The event object passed has these properties:
37930              * @param {Roo.bootstrap.ComboBox} combo This combo box
37931              * @param {String} query The query
37932              * @param {Boolean} forceAll true to force "all" query
37933              * @param {Boolean} cancel true to cancel the query
37934              * @param {Object} e The query event object
37935              */
37936         'beforequery': true,
37937          /**
37938          * @event add
37939          * Fires when the 'add' icon is pressed (add a listener to enable add button)
37940              * @param {Roo.bootstrap.ComboBox} combo This combo box
37941              */
37942         'add' : true,
37943         /**
37944          * @event edit
37945          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
37946              * @param {Roo.bootstrap.ComboBox} combo This combo box
37947              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
37948              */
37949         'edit' : true,
37950         /**
37951          * @event remove
37952          * Fires when the remove value from the combobox array
37953              * @param {Roo.bootstrap.ComboBox} combo This combo box
37954              */
37955         'remove' : true,
37956         /**
37957          * @event afterremove
37958          * Fires when the remove value from the combobox array
37959              * @param {Roo.bootstrap.ComboBox} combo This combo box
37960              */
37961         'afterremove' : true,
37962         /**
37963          * @event specialfilter
37964          * Fires when specialfilter
37965             * @param {Roo.bootstrap.ComboBox} combo This combo box
37966             */
37967         'touchviewdisplay' : true
37968     });
37969     
37970     this.country = []; //fetch country JSON
37971 };
37972
37973 Roo.extend(Roo.bootstrap.PhoneInput, Roo.bootstrap.TriggerField, {
37974      
37975      listWidth: undefined,
37976      
37977      modalTitle : '', 
37978      
37979      selectedClass: 'active',
37980      
37981      maxHeight: 300,
37982      
37983      minListWidth : 70,
37984      
37985      triggerAction: 'query',
37986      
37987      validClass : "has-success",
37988      
37989      invalidClass: "has-warning",
37990      
37991      //new settings
37992      defaultCountry: 'hk',
37993      
37994      preferedCountries: undefined, //array
37995      
37996      filterCountries: undefined, //array
37997      
37998      displayMode: undefined, //string
37999      
38000      getAutoCreate : function(){
38001     
38002          this.list = Roo.bootstrap.PhoneInput.List;
38003     
38004         if(this.filterCountries) {
38005             for(var i = 0; i < this.filterCountries.length; i++) {
38006                 delete this.list[this.filterCountries[i]];
38007             }
38008         }
38009         
38010         if (this.preferedCountries) {
38011             //another list??
38012         }
38013         
38014          var align = this.labelAlign || this.parentLabelAlign();
38015          
38016          var id = Roo.id(); //all el??
38017          
38018          var cfg = {
38019              cls: 'form-group'
38020          };
38021          
38022          var input =  {
38023              tag: 'input',
38024              id : id,
38025              type : this.inputType,
38026              cls : 'form-control',
38027              style: 'padding-left: 60px;',
38028              placeholder : this.placeholder || ''
38029          };
38030          
38031          if (this.name) {
38032              input.name = this.name;
38033          }
38034          if (this.size) {
38035              input.cls += ' input-' + this.size;
38036          }
38037          
38038          if (this.disabled) {
38039              input.disabled=true;
38040          }
38041          
38042          var inputblock = input;
38043          
38044          if(this.hasFeedback && !this.allowBlank){
38045              var feedback = {
38046                  tag: 'span',
38047                  cls: 'glyphicon form-control-feedback'
38048              };
38049          }
38050          
38051          inputblock = {
38052              cn :  []
38053          };
38054          
38055          inputblock.cn.push(input);
38056          
38057          if(this.hasFeedback && !this.allowBlank){
38058              inputblock.cls += 'has-feedback';
38059              inputblock.cn.push(feedback);
38060          }
38061          
38062          var box = {
38063              tag: 'div',
38064              cn: [
38065                  {
38066                      tag: 'input',
38067                      type : 'hidden',
38068                      cls: 'form-hidden-field'
38069                  },
38070                  inputblock
38071              ]
38072          };
38073          
38074          var flag = {
38075              tag: 'span',
38076              html: 'flag',
38077              style: 'margin-right:5px',
38078              cls: 'roo-selected-region',
38079              cn: [] //flag position ... (iti-flag-us)
38080          };
38081          
38082          var caret = {
38083              tag: 'span',
38084              cls: 'caret'
38085           };
38086           
38087          if (this.caret != false) {
38088              caret = {
38089                   tag: 'i',
38090                   cls: 'fa fa-' + this.caret
38091              };
38092          }
38093          
38094          var combobox = {
38095              cls: 'roo-select2-container input-group',
38096              cn: []
38097          };
38098          
38099          combobox.cn.push({
38100              tag :'span',
38101              cls : 'input-group-addon btn dropdown-toggle',
38102              style : 'position: absolute; z-index: 4;background: none;border: none; margin-top: 4px; margin-left: 3px; margin-right: 3px;',
38103              cn : [
38104                  flag,
38105                  caret,
38106                  {
38107                      tag: 'span',
38108                      cls: 'combobox-clear',
38109                      cn  : [
38110                          {
38111                              tag : 'i',
38112                              cls: 'icon-remove'
38113                          }
38114                      ]
38115                  }
38116              ]
38117          });
38118          
38119          combobox.cn.push(box);
38120          
38121          if (align ==='left' && this.fieldLabel.length) {
38122              
38123              cfg.cls += ' roo-form-group-label-left';
38124
38125              cfg.cn = [
38126                  {
38127                      tag : 'i',
38128                      cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
38129                      tooltip : 'This field is required'
38130                  },
38131                  {
38132                      tag: 'label',
38133                      'for' :  id,
38134                      cls : 'control-label',
38135                      html : this.fieldLabel
38136
38137                  },
38138                  {
38139                      cls : "", 
38140                      cn: [
38141                          combobox
38142                      ]
38143                  }
38144              ];
38145              
38146              var labelCfg = cfg.cn[1];
38147              var contentCfg = cfg.cn[2];
38148              
38149              if(this.indicatorpos == 'right'){
38150                  cfg.cn = [
38151                      {
38152                          tag: 'label',
38153                          'for' :  id,
38154                          cls : 'control-label',
38155                          cn : [
38156                              {
38157                                  tag : 'span',
38158                                  html : this.fieldLabel
38159                              },
38160                              {
38161                                  tag : 'i',
38162                                  cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
38163                                  tooltip : 'This field is required'
38164                              }
38165                          ]
38166                      },
38167                      {
38168                          cls : "", 
38169                          cn: [
38170                              combobox
38171                          ]
38172                      }
38173
38174                  ];
38175                  
38176                  labelCfg = cfg.cn[0];
38177                  contentCfg = cfg.cn[1];
38178              }
38179              
38180              if(this.labelWidth > 12){
38181                  labelCfg.style = "width: " + this.labelWidth + 'px';
38182              }
38183              
38184              if(this.labelWidth < 13 && this.labelmd == 0){
38185                  this.labelmd = this.labelWidth;
38186              }
38187              
38188              if(this.labellg > 0){
38189                  labelCfg.cls += ' col-lg-' + this.labellg;
38190                  contentCfg.cls += ' col-lg-' + (12 - this.labellg);
38191              }
38192              
38193              if(this.labelmd > 0){
38194                  labelCfg.cls += ' col-md-' + this.labelmd;
38195                  contentCfg.cls += ' col-md-' + (12 - this.labelmd);
38196              }
38197              
38198              if(this.labelsm > 0){
38199                  labelCfg.cls += ' col-sm-' + this.labelsm;
38200                  contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
38201              }
38202              
38203              if(this.labelxs > 0){
38204                  labelCfg.cls += ' col-xs-' + this.labelxs;
38205                  contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
38206              }
38207              
38208          } else if ( this.fieldLabel.length) {
38209  //                Roo.log(" label");
38210              cfg.cn = [
38211                  {
38212                     tag : 'i',
38213                     cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
38214                     tooltip : 'This field is required'
38215                 },
38216                 {
38217                     tag: 'label',
38218                     //cls : 'input-group-addon',
38219                     html : this.fieldLabel
38220
38221                 },
38222
38223                 combobox
38224
38225              ];
38226              
38227              if(this.indicatorpos == 'right'){
38228                  
38229                  cfg.cn = [
38230                      {
38231                         tag: 'label',
38232                         cn : [
38233                             {
38234                                 tag : 'span',
38235                                 html : this.fieldLabel
38236                             },
38237                             {
38238                                tag : 'i',
38239                                cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
38240                                tooltip : 'This field is required'
38241                             }
38242                         ]
38243                      },
38244                      combobox
38245                  ];
38246              }
38247          } else {
38248                  cfg = combobox
38249          }
38250          
38251          var settings=this;
38252          ['xs','sm','md','lg'].map(function(size){
38253              if (settings[size]) {
38254                  cfg.cls += ' col-' + size + '-' + settings[size];
38255              }
38256          });
38257          
38258          return cfg;
38259      },
38260      
38261      _initEventsCalled : false,
38262      
38263      initEvents: function()
38264      {   
38265          if (this._initEventsCalled) {
38266              return;
38267          }
38268          
38269          this._initEventsCalled = true;
38270          
38271          this.store =  new Roo.data.SimpleStore({
38272              data : this.list,
38273              fields : ['name','iso','dial_code','order','area_code']
38274          });
38275          
38276          this.store = Roo.factory(this.store, Roo.data);
38277          this.store.parent = this;
38278          
38279          Roo.bootstrap.PhoneInput.superclass.initEvents.call(this);
38280          
38281          var _this = this;
38282          
38283          (function(){
38284              var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
38285              _this.list.setWidth(lw);
38286          }).defer(100);
38287          
38288          this.list.on('mouseover', this.onViewOver, this);
38289          this.list.on('mousemove', this.onViewMove, this);
38290          this.list.on('scroll', this.onViewScroll, this);
38291          
38292          if(!this.tpl){
38293              this.tpl = '<li><a href="#">{' + this.displayField + '}</a></li>';
38294          }
38295
38296          this.view = new Roo.View(this.list, this.tpl, {
38297              singleSelect:true, store: this.store, selectedClass: this.selectedClass
38298          });
38299          
38300          this.view.on('click', this.onViewClick, this);
38301          
38302          this.store.on('beforeload', this.onBeforeLoad, this);
38303          this.store.on('load', this.onLoad, this);
38304          this.store.on('loadexception', this.onLoadException, this);
38305          
38306          this.keyNav = new Roo.KeyNav(this.inputEl(), {
38307              "up" : function(e){
38308                  this.inKeyMode = true;
38309                  this.selectPrev();
38310              },
38311
38312              "down" : function(e){
38313                  if(!this.isExpanded()){
38314                      this.onTriggerClick();
38315                  }else{
38316                      this.inKeyMode = true;
38317                      this.selectNext();
38318                  }
38319              },
38320
38321              "enter" : function(e){
38322  //                this.onViewClick();
38323                  //return true;
38324                  this.collapse();
38325                  
38326                  if(this.fireEvent("specialkey", this, e)){
38327                      this.onViewClick(false);
38328                  }
38329                  
38330                  return true;
38331              },
38332
38333              "esc" : function(e){
38334                  this.collapse();
38335              },
38336
38337              "tab" : function(e){
38338                  this.collapse();
38339                  
38340                  if(this.fireEvent("specialkey", this, e)){
38341                      this.onViewClick(false);
38342                  }
38343                  
38344                  return true;
38345              },
38346
38347              scope : this,
38348
38349              doRelay : function(foo, bar, hname){
38350                  if(hname == 'down' || this.scope.isExpanded()){
38351                     return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
38352                  }
38353                  return true;
38354              },
38355
38356              forceKeyDown: true
38357          });
38358          
38359     },
38360     
38361     onViewOver : function(e, t){
38362         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
38363             return;
38364         }
38365         var item = this.view.findItemFromChild(t);
38366         
38367         if(item){
38368             var index = this.view.indexOf(item);
38369             this.select(index, false);
38370         }
38371     },
38372     
38373     onViewMove : function(e, t){
38374         this.inKeyMode = false;
38375     },
38376     
38377     onViewScroll : function(e, t){
38378         
38379         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){
38380             return;
38381         }
38382         
38383         this.hasQuery = true;
38384         
38385         this.loading = this.list.select('.loading', true).first();
38386         
38387         if(this.loading === null){
38388             this.list.createChild({
38389                 tag: 'div',
38390                 cls: 'loading roo-select2-more-results roo-select2-active',
38391                 html: 'Loading more results...'
38392             });
38393             
38394             this.loading = this.list.select('.loading', true).first();
38395             
38396             this.loading.setVisibilityMode(Roo.Element.DISPLAY);
38397             
38398             this.loading.hide();
38399         }
38400         
38401         this.loading.show();
38402         
38403         var _combo = this;
38404         
38405         this.page++;
38406         this.loadNext = true;
38407         
38408         (function() { _combo.doQuery(_combo.allQuery, true); }).defer(500);
38409         
38410         return;
38411     },
38412     
38413     onTriggerClick : function(e)
38414     {
38415         Roo.log('trigger click');
38416         
38417         if(this.disabled || !this.triggerList){
38418             return;
38419         }
38420         
38421         this.page = 0;
38422         this.loadNext = false;
38423         
38424         if(this.isExpanded()){
38425             this.collapse();
38426             if (!this.blockFocus) {
38427                 this.inputEl().focus();
38428             }
38429             
38430         }else {
38431             this.hasFocus = true;
38432             if(this.triggerAction == 'all') {
38433                 this.doQuery(this.allQuery, true);
38434             } else {
38435                 this.doQuery(this.getRawValue());
38436             }
38437             if (!this.blockFocus) {
38438                 this.inputEl().focus();
38439             }
38440         }
38441     }
38442     
38443  });
38444
38445  Roo.apply(Roo.bootstrap.PhoneInput, {
38446      
38447      /**
38448       * iso2 and abbr for all countries
38449       * @type Object
38450       */
38451      List : [
38452          ["Afghanistan (‫افغانستان‬‎)", "af", "93"],
38453          ["Albania (Shqipëri)", "al", "355"],
38454          ["Algeria (‫الجزائر‬‎)", "dz", "213"],
38455          ["American Samoa", "as", "1684"],
38456          ["Andorra", "ad", "376"],
38457          ["Angola", "ao", "244"],
38458          ["Anguilla", "ai", "1264"],
38459          ["Antigua and Barbuda", "ag", "1268"],
38460          ["Argentina", "ar", "54"],
38461          ["Armenia (Հայաստան)", "am", "374"],
38462          ["Aruba", "aw", "297"],
38463          ["Australia", "au", "61", 0],
38464          ["Austria (Österreich)", "at", "43"],
38465          ["Azerbaijan (Azərbaycan)", "az", "994"],
38466          ["Bahamas", "bs", "1242"],
38467          ["Bahrain (‫البحرين‬‎)", "bh", "973"],
38468          ["Bangladesh (বাংলাদেশ)", "bd", "880"],
38469          ["Barbados", "bb", "1246"],
38470          ["Belarus (Беларусь)", "by", "375"],
38471          ["Belgium (België)", "be", "32"],
38472          ["Belize", "bz", "501"],
38473          ["Benin (Bénin)", "bj", "229"],
38474          ["Bermuda", "bm", "1441"],
38475          ["Bhutan (འབྲུག)", "bt", "975"],
38476          ["Bolivia", "bo", "591"],
38477          ["Bosnia and Herzegovina (Босна и Херцеговина)", "ba", "387"],
38478          ["Botswana", "bw", "267"],
38479          ["Brazil (Brasil)", "br", "55"],
38480          ["British Indian Ocean Territory", "io", "246"],
38481          ["British Virgin Islands", "vg", "1284"],
38482          ["Brunei", "bn", "673"],
38483          ["Bulgaria (България)", "bg", "359"],
38484          ["Burkina Faso", "bf", "226"],
38485          ["Burundi (Uburundi)", "bi", "257"],
38486          ["Cambodia (កម្ពុជា)", "kh", "855"],
38487          ["Cameroon (Cameroun)", "cm", "237"],
38488          ["Canada", "ca", "1", 1, ["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"]],
38489          ["Cape Verde (Kabu Verdi)", "cv", "238"],
38490          ["Caribbean Netherlands", "bq", "599", 1],
38491          ["Cayman Islands", "ky", "1345"],
38492          ["Central African Republic (République centrafricaine)", "cf", "236"],
38493          ["Chad (Tchad)", "td", "235"],
38494          ["Chile", "cl", "56"],
38495          ["China (中国)", "cn", "86"],
38496          ["Christmas Island", "cx", "61", 2],
38497          ["Cocos (Keeling) Islands", "cc", "61", 1],
38498          ["Colombia", "co", "57"],
38499          ["Comoros (‫جزر القمر‬‎)", "km", "269"],
38500          ["Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)", "cd", "243"],
38501          ["Congo (Republic) (Congo-Brazzaville)", "cg", "242"],
38502          ["Cook Islands", "ck", "682"],
38503          ["Costa Rica", "cr", "506"],
38504          ["Côte d’Ivoire", "ci", "225"],
38505          ["Croatia (Hrvatska)", "hr", "385"],
38506          ["Cuba", "cu", "53"],
38507          ["Curaçao", "cw", "599", 0],
38508          ["Cyprus (Κύπρος)", "cy", "357"],
38509          ["Czech Republic (Česká republika)", "cz", "420"],
38510          ["Denmark (Danmark)", "dk", "45"],
38511          ["Djibouti", "dj", "253"],
38512          ["Dominica", "dm", "1767"],
38513          ["Dominican Republic (República Dominicana)", "do", "1", 2, ["809", "829", "849"]],
38514          ["Ecuador", "ec", "593"],
38515          ["Egypt (‫مصر‬‎)", "eg", "20"],
38516          ["El Salvador", "sv", "503"],
38517          ["Equatorial Guinea (Guinea Ecuatorial)", "gq", "240"],
38518          ["Eritrea", "er", "291"],
38519          ["Estonia (Eesti)", "ee", "372"],
38520          ["Ethiopia", "et", "251"],
38521          ["Falkland Islands (Islas Malvinas)", "fk", "500"],
38522          ["Faroe Islands (Føroyar)", "fo", "298"],
38523          ["Fiji", "fj", "679"],
38524          ["Finland (Suomi)", "fi", "358", 0],
38525          ["France", "fr", "33"],
38526          ["French Guiana (Guyane française)", "gf", "594"],
38527          ["French Polynesia (Polynésie française)", "pf", "689"],
38528          ["Gabon", "ga", "241"],
38529          ["Gambia", "gm", "220"],
38530          ["Georgia (საქართველო)", "ge", "995"],
38531          ["Germany (Deutschland)", "de", "49"],
38532          ["Ghana (Gaana)", "gh", "233"],
38533          ["Gibraltar", "gi", "350"],
38534          ["Greece (Ελλάδα)", "gr", "30"],
38535          ["Greenland (Kalaallit Nunaat)", "gl", "299"],
38536          ["Grenada", "gd", "1473"],
38537          ["Guadeloupe", "gp", "590", 0],
38538          ["Guam", "gu", "1671"],
38539          ["Guatemala", "gt", "502"],
38540          ["Guernsey", "gg", "44", 1],
38541          ["Guinea (Guinée)", "gn", "224"],
38542          ["Guinea-Bissau (Guiné Bissau)", "gw", "245"],
38543          ["Guyana", "gy", "592"],
38544          ["Haiti", "ht", "509"],
38545          ["Honduras", "hn", "504"],
38546          ["Hong Kong (香港)", "hk", "852"],
38547          ["Hungary (Magyarország)", "hu", "36"],
38548          ["Iceland (Ísland)", "is", "354"],
38549          ["India (भारत)", "in", "91"],
38550          ["Indonesia", "id", "62"],
38551          ["Iran (‫ایران‬‎)", "ir", "98"],
38552          ["Iraq (‫العراق‬‎)", "iq", "964"],
38553          ["Ireland", "ie", "353"],
38554          ["Isle of Man", "im", "44", 2],
38555          ["Israel (‫ישראל‬‎)", "il", "972"],
38556          ["Italy (Italia)", "it", "39", 0],
38557          ["Jamaica", "jm", "1876"],
38558          ["Japan (日本)", "jp", "81"],
38559          ["Jersey", "je", "44", 3],
38560          ["Jordan (‫الأردن‬‎)", "jo", "962"],
38561          ["Kazakhstan (Казахстан)", "kz", "7", 1],
38562          ["Kenya", "ke", "254"],
38563          ["Kiribati", "ki", "686"],
38564          ["Kosovo", "xk", "383"],
38565          ["Kuwait (‫الكويت‬‎)", "kw", "965"],
38566          ["Kyrgyzstan (Кыргызстан)", "kg", "996"],
38567          ["Laos (ລາວ)", "la", "856"],
38568          ["Latvia (Latvija)", "lv", "371"],
38569          ["Lebanon (‫لبنان‬‎)", "lb", "961"],
38570          ["Lesotho", "ls", "266"],
38571          ["Liberia", "lr", "231"],
38572          ["Libya (‫ليبيا‬‎)", "ly", "218"],
38573          ["Liechtenstein", "li", "423"],
38574          ["Lithuania (Lietuva)", "lt", "370"],
38575          ["Luxembourg", "lu", "352"],
38576          ["Macau (澳門)", "mo", "853"],
38577          ["Macedonia (FYROM) (Македонија)", "mk", "389"],
38578          ["Madagascar (Madagasikara)", "mg", "261"],
38579          ["Malawi", "mw", "265"],
38580          ["Malaysia", "my", "60"],
38581          ["Maldives", "mv", "960"],
38582          ["Mali", "ml", "223"],
38583          ["Malta", "mt", "356"],
38584          ["Marshall Islands", "mh", "692"],
38585          ["Martinique", "mq", "596"],
38586          ["Mauritania (‫موريتانيا‬‎)", "mr", "222"],
38587          ["Mauritius (Moris)", "mu", "230"],
38588          ["Mayotte", "yt", "262", 1],
38589          ["Mexico (México)", "mx", "52"],
38590          ["Micronesia", "fm", "691"],
38591          ["Moldova (Republica Moldova)", "md", "373"],
38592          ["Monaco", "mc", "377"],
38593          ["Mongolia (Монгол)", "mn", "976"],
38594          ["Montenegro (Crna Gora)", "me", "382"],
38595          ["Montserrat", "ms", "1664"],
38596          ["Morocco (‫المغرب‬‎)", "ma", "212", 0],
38597          ["Mozambique (Moçambique)", "mz", "258"],
38598          ["Myanmar (Burma) (မြန်မာ)", "mm", "95"],
38599          ["Namibia (Namibië)", "na", "264"],
38600          ["Nauru", "nr", "674"],
38601          ["Nepal (नेपाल)", "np", "977"],
38602          ["Netherlands (Nederland)", "nl", "31"],
38603          ["New Caledonia (Nouvelle-Calédonie)", "nc", "687"],
38604          ["New Zealand", "nz", "64"],
38605          ["Nicaragua", "ni", "505"],
38606          ["Niger (Nijar)", "ne", "227"],
38607          ["Nigeria", "ng", "234"],
38608          ["Niue", "nu", "683"],
38609          ["Norfolk Island", "nf", "672"],
38610          ["North Korea (조선 민주주의 인민 공화국)", "kp", "850"],
38611          ["Northern Mariana Islands", "mp", "1670"],
38612          ["Norway (Norge)", "no", "47", 0],
38613          ["Oman (‫عُمان‬‎)", "om", "968"],
38614          ["Pakistan (‫پاکستان‬‎)", "pk", "92"],
38615          ["Palau", "pw", "680"],
38616          ["Palestine (‫فلسطين‬‎)", "ps", "970"],
38617          ["Panama (Panamá)", "pa", "507"],
38618          ["Papua New Guinea", "pg", "675"],
38619          ["Paraguay", "py", "595"],
38620          ["Peru (Perú)", "pe", "51"],
38621          ["Philippines", "ph", "63"],
38622          ["Poland (Polska)", "pl", "48"],
38623          ["Portugal", "pt", "351"],
38624          ["Puerto Rico", "pr", "1", 3, ["787", "939"]],
38625          ["Qatar (‫قطر‬‎)", "qa", "974"],
38626          ["Réunion (La Réunion)", "re", "262", 0],
38627          ["Romania (România)", "ro", "40"],
38628          ["Russia (Россия)", "ru", "7", 0],
38629          ["Rwanda", "rw", "250"],
38630          ["Saint Barthélemy", "bl", "590", 1],
38631          ["Saint Helena", "sh", "290"],
38632          ["Saint Kitts and Nevis", "kn", "1869"],
38633          ["Saint Lucia", "lc", "1758"],
38634          ["Saint Martin (Saint-Martin (partie française))", "mf", "590", 2],
38635          ["Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)", "pm", "508"],
38636          ["Saint Vincent and the Grenadines", "vc", "1784"],
38637          ["Samoa", "ws", "685"],
38638          ["San Marino", "sm", "378"],
38639          ["São Tomé and Príncipe (São Tomé e Príncipe)", "st", "239"],
38640          ["Saudi Arabia (‫المملكة العربية السعودية‬‎)", "sa", "966"],
38641          ["Senegal (Sénégal)", "sn", "221"],
38642          ["Serbia (Србија)", "rs", "381"],
38643          ["Seychelles", "sc", "248"],
38644          ["Sierra Leone", "sl", "232"],
38645          ["Singapore", "sg", "65"],
38646          ["Sint Maarten", "sx", "1721"],
38647          ["Slovakia (Slovensko)", "sk", "421"],
38648          ["Slovenia (Slovenija)", "si", "386"],
38649          ["Solomon Islands", "sb", "677"],
38650          ["Somalia (Soomaaliya)", "so", "252"],
38651          ["South Africa", "za", "27"],
38652          ["South Korea (대한민국)", "kr", "82"],
38653          ["South Sudan (‫جنوب السودان‬‎)", "ss", "211"],
38654          ["Spain (España)", "es", "34"],
38655          ["Sri Lanka (ශ්‍රී ලංකාව)", "lk", "94"],
38656          ["Sudan (‫السودان‬‎)", "sd", "249"],
38657          ["Suriname", "sr", "597"],
38658          ["Svalbard and Jan Mayen", "sj", "47", 1],
38659          ["Swaziland", "sz", "268"],
38660          ["Sweden (Sverige)", "se", "46"],
38661          ["Switzerland (Schweiz)", "ch", "41"],
38662          ["Syria (‫سوريا‬‎)", "sy", "963"],
38663          ["Taiwan (台灣)", "tw", "886"],
38664          ["Tajikistan", "tj", "992"],
38665          ["Tanzania", "tz", "255"],
38666          ["Thailand (ไทย)", "th", "66"],
38667          ["Timor-Leste", "tl", "670"],
38668          ["Togo", "tg", "228"],
38669          ["Tokelau", "tk", "690"],
38670          ["Tonga", "to", "676"],
38671          ["Trinidad and Tobago", "tt", "1868"],
38672          ["Tunisia (‫تونس‬‎)", "tn", "216"],
38673          ["Turkey (Türkiye)", "tr", "90"],
38674          ["Turkmenistan", "tm", "993"],
38675          ["Turks and Caicos Islands", "tc", "1649"],
38676          ["Tuvalu", "tv", "688"],
38677          ["U.S. Virgin Islands", "vi", "1340"],
38678          ["Uganda", "ug", "256"],
38679          ["Ukraine (Україна)", "ua", "380"],
38680          ["United Arab Emirates (‫الإمارات العربية المتحدة‬‎)", "ae", "971"],
38681          ["United Kingdom", "gb", "44", 0],
38682          ["United States", "us", "1", 0],
38683          ["Uruguay", "uy", "598"],
38684          ["Uzbekistan (Oʻzbekiston)", "uz", "998"],
38685          ["Vanuatu", "vu", "678"],
38686          ["Vatican City (Città del Vaticano)", "va", "39", 1],
38687          ["Venezuela", "ve", "58"],
38688          ["Vietnam (Việt Nam)", "vn", "84"],
38689          ["Wallis and Futuna (Wallis-et-Futuna)", "wf", "681"],
38690          ["Western Sahara (‫الصحراء الغربية‬‎)", "eh", "212", 1],
38691          ["Yemen (‫اليمن‬‎)", "ye", "967"],
38692          ["Zambia", "zm", "260"],
38693          ["Zimbabwe", "zw", "263"],
38694          ["Åland Islands", "ax", "358", 1]
38695      ]
38696  });