Roo/bootstrap/ComboBox.js
[roojs1] / Roo / bootstrap / ComboBox.js
1 /*
2  * - LGPL
3  * * 
4  */
5
6 /**
7  * @class Roo.bootstrap.ComboBox
8  * @extends Roo.bootstrap.TriggerField
9  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
10  * @cfg {Boolean} append (true|false) default false
11  * @cfg {Boolean} autoFocus (true|false) auto focus the first item, default true
12  * @cfg {Boolean} tickable ComboBox with tickable selections (true|false), default false
13  * @cfg {Boolean} triggerList trigger show the list or not (true|false) default true
14  * @cfg {Boolean} showToggleBtn show toggle button or not (true|false) default true
15  * @cfg {String} btnPosition set the position of the trigger button (left | right) default right
16  * @cfg {Boolean} animate default true
17  * @cfg {Boolean} emptyResultText only for touch device
18  * @cfg {String} triggerText multiple combobox trigger button text default 'Select'
19  * @constructor
20  * Create a new ComboBox.
21  * @param {Object} config Configuration options
22  */
23 Roo.bootstrap.ComboBox = function(config){
24     Roo.bootstrap.ComboBox.superclass.constructor.call(this, config);
25     this.addEvents({
26         /**
27          * @event expand
28          * Fires when the dropdown list is expanded
29              * @param {Roo.bootstrap.ComboBox} combo This combo box
30              */
31         'expand' : true,
32         /**
33          * @event collapse
34          * Fires when the dropdown list is collapsed
35              * @param {Roo.bootstrap.ComboBox} combo This combo box
36              */
37         'collapse' : true,
38         /**
39          * @event beforeselect
40          * Fires before a list item is selected. Return false to cancel the selection.
41              * @param {Roo.bootstrap.ComboBox} combo This combo box
42              * @param {Roo.data.Record} record The data record returned from the underlying store
43              * @param {Number} index The index of the selected item in the dropdown list
44              */
45         'beforeselect' : true,
46         /**
47          * @event select
48          * Fires when a list item is selected
49              * @param {Roo.bootstrap.ComboBox} combo This combo box
50              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
51              * @param {Number} index The index of the selected item in the dropdown list
52              */
53         'select' : true,
54         /**
55          * @event beforequery
56          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
57          * The event object passed has these properties:
58              * @param {Roo.bootstrap.ComboBox} combo This combo box
59              * @param {String} query The query
60              * @param {Boolean} forceAll true to force "all" query
61              * @param {Boolean} cancel true to cancel the query
62              * @param {Object} e The query event object
63              */
64         'beforequery': true,
65          /**
66          * @event add
67          * Fires when the 'add' icon is pressed (add a listener to enable add button)
68              * @param {Roo.bootstrap.ComboBox} combo This combo box
69              */
70         'add' : true,
71         /**
72          * @event edit
73          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
74              * @param {Roo.bootstrap.ComboBox} combo This combo box
75              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
76              */
77         'edit' : true,
78         /**
79          * @event remove
80          * Fires when the remove value from the combobox array
81              * @param {Roo.bootstrap.ComboBox} combo This combo box
82              */
83         'remove' : true,
84         /**
85          * @event afterremove
86          * Fires when the remove value from the combobox array
87              * @param {Roo.bootstrap.ComboBox} combo This combo box
88              */
89         'afterremove' : true,
90         /**
91          * @event specialfilter
92          * Fires when specialfilter
93             * @param {Roo.bootstrap.ComboBox} combo This combo box
94             */
95         'specialfilter' : true,
96         /**
97          * @event tick
98          * Fires when tick the element
99             * @param {Roo.bootstrap.ComboBox} combo This combo box
100             */
101         'tick' : true,
102         /**
103          * @event touchviewdisplay
104          * Fires when touch view require special display (default is using displayField)
105             * @param {Roo.bootstrap.ComboBox} combo This combo box
106             * @param {Object} cfg set html .
107             */
108         'touchviewdisplay' : true
109         
110     });
111     
112     this.item = [];
113     this.tickItems = [];
114     
115     this.selectedIndex = -1;
116     if(this.mode == 'local'){
117         if(config.queryDelay === undefined){
118             this.queryDelay = 10;
119         }
120         if(config.minChars === undefined){
121             this.minChars = 0;
122         }
123     }
124 };
125
126 Roo.extend(Roo.bootstrap.ComboBox, Roo.bootstrap.TriggerField, {
127      
128     /**
129      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
130      * rendering into an Roo.Editor, defaults to false)
131      */
132     /**
133      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
134      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
135      */
136     /**
137      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
138      */
139     /**
140      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
141      * the dropdown list (defaults to undefined, with no header element)
142      */
143
144      /**
145      * @cfg {String/Roo.Template} tpl The template to use to render the output
146      */
147      
148      /**
149      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
150      */
151     listWidth: undefined,
152     /**
153      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
154      * mode = 'remote' or 'text' if mode = 'local')
155      */
156     displayField: undefined,
157     
158     /**
159      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
160      * mode = 'remote' or 'value' if mode = 'local'). 
161      * Note: use of a valueField requires the user make a selection
162      * in order for a value to be mapped.
163      */
164     valueField: undefined,
165     /**
166      * @cfg {String} modalTitle The title of the dialog that pops up on mobile views.
167      */
168     modalTitle : '',
169     
170     /**
171      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
172      * field's data value (defaults to the underlying DOM element's name)
173      */
174     hiddenName: undefined,
175     /**
176      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
177      */
178     listClass: '',
179     /**
180      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
181      */
182     selectedClass: 'active',
183     
184     /**
185      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
186      */
187     shadow:'sides',
188     /**
189      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
190      * anchor positions (defaults to 'tl-bl')
191      */
192     listAlign: 'tl-bl?',
193     /**
194      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
195      */
196     maxHeight: 300,
197     /**
198      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
199      * query specified by the allQuery config option (defaults to 'query')
200      */
201     triggerAction: 'query',
202     /**
203      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
204      * (defaults to 4, does not apply if editable = false)
205      */
206     minChars : 4,
207     /**
208      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
209      * delay (typeAheadDelay) if it matches a known value (defaults to false)
210      */
211     typeAhead: false,
212     /**
213      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
214      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
215      */
216     queryDelay: 500,
217     /**
218      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
219      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
220      */
221     pageSize: 0,
222     /**
223      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
224      * when editable = true (defaults to false)
225      */
226     selectOnFocus:false,
227     /**
228      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
229      */
230     queryParam: 'query',
231     /**
232      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
233      * when mode = 'remote' (defaults to 'Loading...')
234      */
235     loadingText: 'Loading...',
236     /**
237      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
238      */
239     resizable: false,
240     /**
241      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
242      */
243     handleHeight : 8,
244     /**
245      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
246      * traditional select (defaults to true)
247      */
248     editable: true,
249     /**
250      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
251      */
252     allQuery: '',
253     /**
254      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
255      */
256     mode: 'remote',
257     /**
258      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
259      * listWidth has a higher value)
260      */
261     minListWidth : 70,
262     /**
263      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
264      * allow the user to set arbitrary text into the field (defaults to false)
265      */
266     forceSelection:false,
267     /**
268      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
269      * if typeAhead = true (defaults to 250)
270      */
271     typeAheadDelay : 250,
272     /**
273      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
274      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
275      */
276     valueNotFoundText : undefined,
277     /**
278      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
279      */
280     blockFocus : false,
281     
282     /**
283      * @cfg {Boolean} disableClear Disable showing of clear button.
284      */
285     disableClear : false,
286     /**
287      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
288      */
289     alwaysQuery : false,
290     
291     /**
292      * @cfg {Boolean} multiple  (true|false) ComboBobArray, default false
293      */
294     multiple : false,
295     
296     /**
297      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
298      */
299     invalidClass : "has-warning",
300     
301     /**
302      * @cfg {String} validClass The CSS class to use when marking a field valid (defaults to "x-form-invalid")
303      */
304     validClass : "has-success",
305     
306     /**
307      * @cfg {Boolean} specialFilter (true|false) special filter default false
308      */
309     specialFilter : false,
310     
311     /**
312      * @cfg {Boolean} mobileTouchView (true|false) show mobile touch view when using a mobile default true
313      */
314     mobileTouchView : true,
315     
316     /**
317      * @cfg {Boolean} useNativeIOS (true|false) render it as classic select for ios, not support dynamic load data (default false)
318      */
319     useNativeIOS : false,
320     
321     ios_options : false,
322     
323     //private
324     addicon : false,
325     editicon: false,
326     
327     page: 0,
328     hasQuery: false,
329     append: false,
330     loadNext: false,
331     autoFocus : true,
332     tickable : false,
333     btnPosition : 'right',
334     triggerList : true,
335     showToggleBtn : true,
336     animate : true,
337     emptyResultText: 'Empty',
338     triggerText : 'Select',
339     
340     // element that contains real text value.. (when hidden is used..)
341     
342     getAutoCreate : function()
343     {
344         var cfg = false;
345         
346         /*
347          * Render classic select for iso
348          */
349         
350         if(Roo.isIOS && this.useNativeIOS){
351             cfg = this.getAutoCreateNativeIOS();
352             return cfg;
353         }
354         
355         /*
356          * Touch Devices
357          */
358         
359         if(Roo.isTouch && this.mobileTouchView){
360             cfg = this.getAutoCreateTouchView();
361             return cfg;;
362         }
363         
364         /*
365          *  Normal ComboBox
366          */
367         if(!this.tickable){
368             cfg = Roo.bootstrap.ComboBox.superclass.getAutoCreate.call(this);
369             if(this.name == 'info_year_invest_id_display_name'){
370                 Roo.log('cfg.................................................');
371                 Roo.log(cfg);
372             }
373             return cfg;
374         }
375         
376         /*
377          *  ComboBox with tickable selections
378          */
379              
380         var align = this.labelAlign || this.parentLabelAlign();
381         
382         cfg = {
383             cls : 'form-group roo-combobox-tickable' //input-group
384         };
385         
386         var btn_text_select = '';
387         var btn_text_done = '';
388         var btn_text_cancel = '';
389         
390         if (this.btn_text_show) {
391             btn_text_select = 'Select';
392             btn_text_done = 'Done';
393             btn_text_cancel = 'Cancel'; 
394         }
395         
396         var buttons = {
397             tag : 'div',
398             cls : 'tickable-buttons',
399             cn : [
400                 {
401                     tag : 'button',
402                     type : 'button',
403                     cls : 'btn btn-link btn-edit pull-' + this.btnPosition,
404                     //html : this.triggerText
405                     html: btn_text_select
406                 },
407                 {
408                     tag : 'button',
409                     type : 'button',
410                     name : 'ok',
411                     cls : 'btn btn-link btn-ok pull-' + this.btnPosition,
412                     //html : 'Done'
413                     html: btn_text_done
414                 },
415                 {
416                     tag : 'button',
417                     type : 'button',
418                     name : 'cancel',
419                     cls : 'btn btn-link btn-cancel pull-' + this.btnPosition,
420                     //html : 'Cancel'
421                     html: btn_text_cancel
422                 }
423             ]
424         };
425         
426         if(this.editable){
427             buttons.cn.unshift({
428                 tag: 'input',
429                 cls: 'roo-select2-search-field-input'
430             });
431         }
432         
433         var _this = this;
434         
435         Roo.each(buttons.cn, function(c){
436             if (_this.size) {
437                 c.cls += ' btn-' + _this.size;
438             }
439
440             if (_this.disabled) {
441                 c.disabled = true;
442             }
443         });
444         
445         var box = {
446             tag: 'div',
447             cn: [
448                 {
449                     tag: 'input',
450                     type : 'hidden',
451                     cls: 'form-hidden-field'
452                 },
453                 {
454                     tag: 'ul',
455                     cls: 'roo-select2-choices',
456                     cn:[
457                         {
458                             tag: 'li',
459                             cls: 'roo-select2-search-field',
460                             cn: [
461
462                                 buttons
463                             ]
464                         }
465                     ]
466                 }
467             ]
468         };
469         
470         var combobox = {
471             cls: 'roo-select2-container input-group roo-select2-container-multi',
472             cn: [
473                 box
474 //                {
475 //                    tag: 'ul',
476 //                    cls: 'typeahead typeahead-long dropdown-menu',
477 //                    style: 'display:none; max-height:' + this.maxHeight + 'px;'
478 //                }
479             ]
480         };
481         
482         if(this.hasFeedback && !this.allowBlank){
483             
484             var feedback = {
485                 tag: 'span',
486                 cls: 'glyphicon form-control-feedback'
487             };
488
489             combobox.cn.push(feedback);
490         }
491         
492         if (align ==='left' && this.fieldLabel.length) {
493             
494             cfg.cn = [
495                 {
496                     tag : 'i',
497                     cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
498                     tooltip : 'This field is required'
499                 },
500                 {
501                     tag: 'label',
502                     'for' :  id,
503                     cls : 'control-label',
504                     html : this.fieldLabel
505
506                 },
507                 {
508                     cls : "", 
509                     cn: [
510                         combobox
511                     ]
512                 }
513
514             ];
515             
516             var labelCfg = cfg.cn[1];
517             var contentCfg = cfg.cn[2];
518             
519
520             if(this.indicatorpos == 'right'){
521                 
522                 cfg.cn = [
523                     {
524                         tag: 'label',
525                         'for' :  id,
526                         cls : 'control-label',
527                         html : this.fieldLabel
528
529                     },
530                     {
531                         tag : 'i',
532                         cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
533                         tooltip : 'This field is required'
534                     },
535                     {
536                         cls : "",
537                         cn: [
538                             combobox
539                         ]
540                     }
541
542                 ];
543                 
544                 labelCfg = cfg.cn[0];
545             
546             }
547             
548             if(this.labelWidth > 12){
549                 labelCfg.style = "width: " + this.labelWidth + 'px';
550             }
551             
552             if(this.labelWidth < 13 && this.labelmd == 0){
553                 this.labelmd = this.labelWidth;
554             }
555             
556             if(this.labellg > 0){
557                 labelCfg.cls += ' col-lg-' + this.labellg;
558                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
559             }
560             
561             if(this.labelmd > 0){
562                 labelCfg.cls += ' col-md-' + this.labelmd;
563                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
564             }
565             
566             if(this.labelsm > 0){
567                 labelCfg.cls += ' col-sm-' + this.labelsm;
568                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
569             }
570             
571             if(this.labelxs > 0){
572                 labelCfg.cls += ' col-xs-' + this.labelxs;
573                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
574             }
575                 
576                 
577         } else if ( this.fieldLabel.length) {
578 //                Roo.log(" label");
579                  cfg.cn = [
580                     {
581                         tag : 'i',
582                         cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
583                         tooltip : 'This field is required'
584                     },
585                     {
586                         tag: 'label',
587                         //cls : 'input-group-addon',
588                         html : this.fieldLabel
589                         
590                     },
591                     
592                     combobox
593                     
594                 ];
595                 
596                 if(this.indicatorpos == 'right'){
597                     
598                     cfg.cn = [
599                         {
600                             tag: 'label',
601                             //cls : 'input-group-addon',
602                             html : this.fieldLabel
603
604                         },
605                         
606                         {
607                             tag : 'i',
608                             cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
609                             tooltip : 'This field is required'
610                         },
611                         
612                         combobox
613
614                     ];
615                 
616                 }
617
618         } else {
619             
620 //                Roo.log(" no label && no align");
621                 cfg = combobox
622                      
623                 
624         }
625          
626         var settings=this;
627         ['xs','sm','md','lg'].map(function(size){
628             if (settings[size]) {
629                 cfg.cls += ' col-' + size + '-' + settings[size];
630             }
631         });
632         
633         return cfg;
634         
635     },
636     
637     _initEventsCalled : false,
638     
639     // private
640     initEvents: function()
641     {   
642         if (this._initEventsCalled) { // as we call render... prevent looping...
643             return;
644         }
645         this._initEventsCalled = true;
646         
647         if (!this.store) {
648             throw "can not find store for combo";
649         }
650         
651         this.store = Roo.factory(this.store, Roo.data);
652         
653         // if we are building from html. then this element is so complex, that we can not really
654         // use the rendered HTML.
655         // so we have to trash and replace the previous code.
656         if (Roo.XComponent.build_from_html) {
657             
658             // remove this element....
659             var e = this.el.dom, k=0;
660             while (e ) { e = e.previousSibling;  ++k;}
661
662             this.el.remove();
663             
664             this.el=false;
665             this.rendered = false;
666             
667             this.render(this.parent().getChildContainer(true), k);
668             
669             
670             
671         }
672         
673         if(Roo.isIOS && this.useNativeIOS){
674             this.initIOSView();
675             return;
676         }
677         
678         /*
679          * Touch Devices
680          */
681         
682         if(Roo.isTouch && this.mobileTouchView){
683             this.initTouchView();
684             return;
685         }
686         
687         if(this.tickable){
688             this.initTickableEvents();
689             return;
690         }
691         
692         Roo.bootstrap.ComboBox.superclass.initEvents.call(this);
693         
694         if(this.hiddenName){
695             
696             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
697             
698             this.hiddenField.dom.value =
699                 this.hiddenValue !== undefined ? this.hiddenValue :
700                 this.value !== undefined ? this.value : '';
701
702             // prevent input submission
703             this.el.dom.removeAttribute('name');
704             this.hiddenField.dom.setAttribute('name', this.hiddenName);
705              
706              
707         }
708         //if(Roo.isGecko){
709         //    this.el.dom.setAttribute('autocomplete', 'off');
710         //}
711         
712         var cls = 'x-combo-list';
713         
714         //this.list = new Roo.Layer({
715         //    shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
716         //});
717         
718         var _this = this;
719         
720         (function(){
721             var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
722             _this.list.setWidth(lw);
723         }).defer(100);
724         
725         this.list.on('mouseover', this.onViewOver, this);
726         this.list.on('mousemove', this.onViewMove, this);
727         
728         this.list.on('scroll', this.onViewScroll, this);
729         
730         /*
731         this.list.swallowEvent('mousewheel');
732         this.assetHeight = 0;
733
734         if(this.title){
735             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
736             this.assetHeight += this.header.getHeight();
737         }
738
739         this.innerList = this.list.createChild({cls:cls+'-inner'});
740         this.innerList.on('mouseover', this.onViewOver, this);
741         this.innerList.on('mousemove', this.onViewMove, this);
742         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
743         
744         if(this.allowBlank && !this.pageSize && !this.disableClear){
745             this.footer = this.list.createChild({cls:cls+'-ft'});
746             this.pageTb = new Roo.Toolbar(this.footer);
747            
748         }
749         if(this.pageSize){
750             this.footer = this.list.createChild({cls:cls+'-ft'});
751             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
752                     {pageSize: this.pageSize});
753             
754         }
755         
756         if (this.pageTb && this.allowBlank && !this.disableClear) {
757             var _this = this;
758             this.pageTb.add(new Roo.Toolbar.Fill(), {
759                 cls: 'x-btn-icon x-btn-clear',
760                 text: '&#160;',
761                 handler: function()
762                 {
763                     _this.collapse();
764                     _this.clearValue();
765                     _this.onSelect(false, -1);
766                 }
767             });
768         }
769         if (this.footer) {
770             this.assetHeight += this.footer.getHeight();
771         }
772         */
773             
774         if(!this.tpl){
775             this.tpl = '<li><a href="#">{' + this.displayField + '}</a></li>';
776         }
777
778         this.view = new Roo.View(this.list, this.tpl, {
779             singleSelect:true, store: this.store, selectedClass: this.selectedClass
780         });
781         //this.view.wrapEl.setDisplayed(false);
782         this.view.on('click', this.onViewClick, this);
783         
784         
785         
786         this.store.on('beforeload', this.onBeforeLoad, this);
787         this.store.on('load', this.onLoad, this);
788         this.store.on('loadexception', this.onLoadException, this);
789         /*
790         if(this.resizable){
791             this.resizer = new Roo.Resizable(this.list,  {
792                pinned:true, handles:'se'
793             });
794             this.resizer.on('resize', function(r, w, h){
795                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
796                 this.listWidth = w;
797                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
798                 this.restrictHeight();
799             }, this);
800             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
801         }
802         */
803         if(!this.editable){
804             this.editable = true;
805             this.setEditable(false);
806         }
807         
808         /*
809         
810         if (typeof(this.events.add.listeners) != 'undefined') {
811             
812             this.addicon = this.wrap.createChild(
813                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
814        
815             this.addicon.on('click', function(e) {
816                 this.fireEvent('add', this);
817             }, this);
818         }
819         if (typeof(this.events.edit.listeners) != 'undefined') {
820             
821             this.editicon = this.wrap.createChild(
822                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
823             if (this.addicon) {
824                 this.editicon.setStyle('margin-left', '40px');
825             }
826             this.editicon.on('click', function(e) {
827                 
828                 // we fire even  if inothing is selected..
829                 this.fireEvent('edit', this, this.lastData );
830                 
831             }, this);
832         }
833         */
834         
835         this.keyNav = new Roo.KeyNav(this.inputEl(), {
836             "up" : function(e){
837                 this.inKeyMode = true;
838                 this.selectPrev();
839             },
840
841             "down" : function(e){
842                 if(!this.isExpanded()){
843                     this.onTriggerClick();
844                 }else{
845                     this.inKeyMode = true;
846                     this.selectNext();
847                 }
848             },
849
850             "enter" : function(e){
851 //                this.onViewClick();
852                 //return true;
853                 this.collapse();
854                 
855                 if(this.fireEvent("specialkey", this, e)){
856                     this.onViewClick(false);
857                 }
858                 
859                 return true;
860             },
861
862             "esc" : function(e){
863                 this.collapse();
864             },
865
866             "tab" : function(e){
867                 this.collapse();
868                 
869                 if(this.fireEvent("specialkey", this, e)){
870                     this.onViewClick(false);
871                 }
872                 
873                 return true;
874             },
875
876             scope : this,
877
878             doRelay : function(foo, bar, hname){
879                 if(hname == 'down' || this.scope.isExpanded()){
880                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
881                 }
882                 return true;
883             },
884
885             forceKeyDown: true
886         });
887         
888         
889         this.queryDelay = Math.max(this.queryDelay || 10,
890                 this.mode == 'local' ? 10 : 250);
891         
892         
893         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
894         
895         if(this.typeAhead){
896             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
897         }
898         if(this.editable !== false){
899             this.inputEl().on("keyup", this.onKeyUp, this);
900         }
901         if(this.forceSelection){
902             this.inputEl().on('blur', this.doForce, this);
903         }
904         
905         if(this.multiple){
906             this.choices = this.el.select('ul.roo-select2-choices', true).first();
907             this.searchField = this.el.select('ul li.roo-select2-search-field', true).first();
908         }
909     },
910     
911     initTickableEvents: function()
912     {   
913         this.createList();
914         
915         if(this.hiddenName){
916             
917             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
918             
919             this.hiddenField.dom.value =
920                 this.hiddenValue !== undefined ? this.hiddenValue :
921                 this.value !== undefined ? this.value : '';
922
923             // prevent input submission
924             this.el.dom.removeAttribute('name');
925             this.hiddenField.dom.setAttribute('name', this.hiddenName);
926              
927              
928         }
929         
930 //        this.list = this.el.select('ul.dropdown-menu',true).first();
931         
932         this.choices = this.el.select('ul.roo-select2-choices', true).first();
933         this.searchField = this.el.select('ul li.roo-select2-search-field', true).first();
934         if(this.triggerList){
935             this.searchField.on("click", this.onSearchFieldClick, this, {preventDefault:true});
936         }
937          
938         this.trigger = this.el.select('.tickable-buttons > .btn-edit', true).first();
939         this.trigger.on("click", this.onTickableTriggerClick, this, {preventDefault:true});
940         
941         this.okBtn = this.el.select('.tickable-buttons > .btn-ok', true).first();
942         this.cancelBtn = this.el.select('.tickable-buttons > .btn-cancel', true).first();
943         
944         this.okBtn.on('click', this.onTickableFooterButtonClick, this, this.okBtn);
945         this.cancelBtn.on('click', this.onTickableFooterButtonClick, this, this.cancelBtn);
946         
947         this.trigger.setVisibilityMode(Roo.Element.DISPLAY);
948         this.okBtn.setVisibilityMode(Roo.Element.DISPLAY);
949         this.cancelBtn.setVisibilityMode(Roo.Element.DISPLAY);
950         
951         this.okBtn.hide();
952         this.cancelBtn.hide();
953         
954         var _this = this;
955         
956         (function(){
957             var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
958             _this.list.setWidth(lw);
959         }).defer(100);
960         
961         this.list.on('mouseover', this.onViewOver, this);
962         this.list.on('mousemove', this.onViewMove, this);
963         
964         this.list.on('scroll', this.onViewScroll, this);
965         
966         if(!this.tpl){
967             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>';
968         }
969
970         this.view = new Roo.View(this.list, this.tpl, {
971             singleSelect:true, tickable:true, parent:this, store: this.store, selectedClass: this.selectedClass
972         });
973         
974         //this.view.wrapEl.setDisplayed(false);
975         this.view.on('click', this.onViewClick, this);
976         
977         
978         
979         this.store.on('beforeload', this.onBeforeLoad, this);
980         this.store.on('load', this.onLoad, this);
981         this.store.on('loadexception', this.onLoadException, this);
982         
983         if(this.editable){
984             this.keyNav = new Roo.KeyNav(this.tickableInputEl(), {
985                 "up" : function(e){
986                     this.inKeyMode = true;
987                     this.selectPrev();
988                 },
989
990                 "down" : function(e){
991                     this.inKeyMode = true;
992                     this.selectNext();
993                 },
994
995                 "enter" : function(e){
996                     if(this.fireEvent("specialkey", this, e)){
997                         this.onViewClick(false);
998                     }
999                     
1000                     return true;
1001                 },
1002
1003                 "esc" : function(e){
1004                     this.onTickableFooterButtonClick(e, false, false);
1005                 },
1006
1007                 "tab" : function(e){
1008                     this.fireEvent("specialkey", this, e);
1009                     
1010                     this.onTickableFooterButtonClick(e, false, false);
1011                     
1012                     return true;
1013                 },
1014
1015                 scope : this,
1016
1017                 doRelay : function(e, fn, key){
1018                     if(this.scope.isExpanded()){
1019                        return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
1020                     }
1021                     return true;
1022                 },
1023
1024                 forceKeyDown: true
1025             });
1026         }
1027         
1028         this.queryDelay = Math.max(this.queryDelay || 10,
1029                 this.mode == 'local' ? 10 : 250);
1030         
1031         
1032         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
1033         
1034         if(this.typeAhead){
1035             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
1036         }
1037         
1038         if(this.editable !== false){
1039             this.tickableInputEl().on("keyup", this.onKeyUp, this);
1040         }
1041         
1042     },
1043
1044     onDestroy : function(){
1045         if(this.view){
1046             this.view.setStore(null);
1047             this.view.el.removeAllListeners();
1048             this.view.el.remove();
1049             this.view.purgeListeners();
1050         }
1051         if(this.list){
1052             this.list.dom.innerHTML  = '';
1053         }
1054         
1055         if(this.store){
1056             this.store.un('beforeload', this.onBeforeLoad, this);
1057             this.store.un('load', this.onLoad, this);
1058             this.store.un('loadexception', this.onLoadException, this);
1059         }
1060         Roo.bootstrap.ComboBox.superclass.onDestroy.call(this);
1061     },
1062
1063     // private
1064     fireKey : function(e){
1065         if(e.isNavKeyPress() && !this.list.isVisible()){
1066             this.fireEvent("specialkey", this, e);
1067         }
1068     },
1069
1070     // private
1071     onResize: function(w, h){
1072 //        Roo.bootstrap.ComboBox.superclass.onResize.apply(this, arguments);
1073 //        
1074 //        if(typeof w != 'number'){
1075 //            // we do not handle it!?!?
1076 //            return;
1077 //        }
1078 //        var tw = this.trigger.getWidth();
1079 //       // tw += this.addicon ? this.addicon.getWidth() : 0;
1080 //       // tw += this.editicon ? this.editicon.getWidth() : 0;
1081 //        var x = w - tw;
1082 //        this.inputEl().setWidth( this.adjustWidth('input', x));
1083 //            
1084 //        //this.trigger.setStyle('left', x+'px');
1085 //        
1086 //        if(this.list && this.listWidth === undefined){
1087 //            var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
1088 //            this.list.setWidth(lw);
1089 //            this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
1090 //        }
1091         
1092     
1093         
1094     },
1095
1096     /**
1097      * Allow or prevent the user from directly editing the field text.  If false is passed,
1098      * the user will only be able to select from the items defined in the dropdown list.  This method
1099      * is the runtime equivalent of setting the 'editable' config option at config time.
1100      * @param {Boolean} value True to allow the user to directly edit the field text
1101      */
1102     setEditable : function(value){
1103         if(value == this.editable){
1104             return;
1105         }
1106         this.editable = value;
1107         if(!value){
1108             this.inputEl().dom.setAttribute('readOnly', true);
1109             this.inputEl().on('mousedown', this.onTriggerClick,  this);
1110             this.inputEl().addClass('x-combo-noedit');
1111         }else{
1112             this.inputEl().dom.setAttribute('readOnly', false);
1113             this.inputEl().un('mousedown', this.onTriggerClick,  this);
1114             this.inputEl().removeClass('x-combo-noedit');
1115         }
1116     },
1117
1118     // private
1119     
1120     onBeforeLoad : function(combo,opts){
1121         if(!this.hasFocus){
1122             return;
1123         }
1124          if (!opts.add) {
1125             this.list.dom.innerHTML = '<li class="loading-indicator">'+(this.loadingText||'loading')+'</li>' ;
1126          }
1127         this.restrictHeight();
1128         this.selectedIndex = -1;
1129     },
1130
1131     // private
1132     onLoad : function(){
1133         
1134         this.hasQuery = false;
1135         
1136         if(!this.hasFocus){
1137             return;
1138         }
1139         
1140         if(typeof(this.loading) !== 'undefined' && this.loading !== null){
1141             this.loading.hide();
1142         }
1143              
1144         if(this.store.getCount() > 0){
1145             this.expand();
1146             this.restrictHeight();
1147             if(this.lastQuery == this.allQuery){
1148                 if(this.editable && !this.tickable){
1149                     this.inputEl().dom.select();
1150                 }
1151                 
1152                 if(
1153                     !this.selectByValue(this.value, true) &&
1154                     this.autoFocus && 
1155                     (
1156                         !this.store.lastOptions ||
1157                         typeof(this.store.lastOptions.add) == 'undefined' || 
1158                         this.store.lastOptions.add != true
1159                     )
1160                 ){
1161                     this.select(0, true);
1162                 }
1163             }else{
1164                 if(this.autoFocus){
1165                     this.selectNext();
1166                 }
1167                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
1168                     this.taTask.delay(this.typeAheadDelay);
1169                 }
1170             }
1171         }else{
1172             this.onEmptyResults();
1173         }
1174         
1175         //this.el.focus();
1176     },
1177     // private
1178     onLoadException : function()
1179     {
1180         this.hasQuery = false;
1181         
1182         if(typeof(this.loading) !== 'undefined' && this.loading !== null){
1183             this.loading.hide();
1184         }
1185         
1186         if(this.tickable && this.editable){
1187             return;
1188         }
1189         
1190         this.collapse();
1191         // only causes errors at present
1192         //Roo.log(this.store.reader.jsonData);
1193         //if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
1194             // fixme
1195             //Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
1196         //}
1197         
1198         
1199     },
1200     // private
1201     onTypeAhead : function(){
1202         if(this.store.getCount() > 0){
1203             var r = this.store.getAt(0);
1204             var newValue = r.data[this.displayField];
1205             var len = newValue.length;
1206             var selStart = this.getRawValue().length;
1207             
1208             if(selStart != len){
1209                 this.setRawValue(newValue);
1210                 this.selectText(selStart, newValue.length);
1211             }
1212         }
1213     },
1214
1215     // private
1216     onSelect : function(record, index){
1217         
1218         if(this.fireEvent('beforeselect', this, record, index) !== false){
1219         
1220             this.setFromData(index > -1 ? record.data : false);
1221             
1222             this.collapse();
1223             this.fireEvent('select', this, record, index);
1224         }
1225     },
1226
1227     /**
1228      * Returns the currently selected field value or empty string if no value is set.
1229      * @return {String} value The selected value
1230      */
1231     getValue : function()
1232     {
1233         if(Roo.isIOS && this.useNativeIOS){
1234             return this.ios_options[this.inputEl().dom.selectedIndex].data[this.valueField];
1235         }
1236         
1237         if(this.multiple){
1238             return (this.hiddenField) ? this.hiddenField.dom.value : this.value;
1239         }
1240         
1241         if(this.valueField){
1242             return typeof this.value != 'undefined' ? this.value : '';
1243         }else{
1244             return Roo.bootstrap.ComboBox.superclass.getValue.call(this);
1245         }
1246     },
1247     
1248     getRawValue : function()
1249     {
1250         if(Roo.isIOS && this.useNativeIOS){
1251             return this.ios_options[this.inputEl().dom.selectedIndex].data[this.displayField];
1252         }
1253         
1254         var v = this.inputEl().getValue();
1255         
1256         return v;
1257     },
1258
1259     /**
1260      * Clears any text/value currently set in the field
1261      */
1262     clearValue : function(){
1263         
1264         if(this.hiddenField){
1265             this.hiddenField.dom.value = '';
1266         }
1267         this.value = '';
1268         this.setRawValue('');
1269         this.lastSelectionText = '';
1270         this.lastData = false;
1271         
1272         var close = this.closeTriggerEl();
1273         
1274         if(close){
1275             close.hide();
1276         }
1277         
1278         this.validate();
1279         
1280     },
1281
1282     /**
1283      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
1284      * will be displayed in the field.  If the value does not match the data value of an existing item,
1285      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
1286      * Otherwise the field will be blank (although the value will still be set).
1287      * @param {String} value The value to match
1288      */
1289     setValue : function(v)
1290     {
1291         if(Roo.isIOS && this.useNativeIOS){
1292             this.setIOSValue(v);
1293             return;
1294         }
1295         
1296         if(this.multiple){
1297             this.syncValue();
1298             return;
1299         }
1300         
1301         var text = v;
1302         if(this.valueField){
1303             var r = this.findRecord(this.valueField, v);
1304             if(r){
1305                 text = r.data[this.displayField];
1306             }else if(this.valueNotFoundText !== undefined){
1307                 text = this.valueNotFoundText;
1308             }
1309         }
1310         this.lastSelectionText = text;
1311         if(this.hiddenField){
1312             this.hiddenField.dom.value = v;
1313         }
1314         Roo.bootstrap.ComboBox.superclass.setValue.call(this, text);
1315         this.value = v;
1316         
1317         var close = this.closeTriggerEl();
1318         
1319         if(close){
1320             (v && (v.length || v * 1 > 0)) ? close.show() : close.hide();
1321         }
1322         
1323         this.validate();
1324     },
1325     /**
1326      * @property {Object} the last set data for the element
1327      */
1328     
1329     lastData : false,
1330     /**
1331      * Sets the value of the field based on a object which is related to the record format for the store.
1332      * @param {Object} value the value to set as. or false on reset?
1333      */
1334     setFromData : function(o){
1335         
1336         if(this.multiple){
1337             this.addItem(o);
1338             return;
1339         }
1340             
1341         var dv = ''; // display value
1342         var vv = ''; // value value..
1343         this.lastData = o;
1344         if (this.displayField) {
1345             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
1346         } else {
1347             // this is an error condition!!!
1348             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
1349         }
1350         
1351         if(this.valueField){
1352             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
1353         }
1354         
1355         var close = this.closeTriggerEl();
1356         
1357         if(close){
1358             (vv.length || vv * 1 > 0) ? close.show() : close.hide();
1359         }
1360         
1361         if(this.hiddenField){
1362             this.hiddenField.dom.value = vv;
1363             
1364             this.lastSelectionText = dv;
1365             Roo.bootstrap.ComboBox.superclass.setValue.call(this, dv);
1366             this.value = vv;
1367             return;
1368         }
1369         // no hidden field.. - we store the value in 'value', but still display
1370         // display field!!!!
1371         this.lastSelectionText = dv;
1372         Roo.bootstrap.ComboBox.superclass.setValue.call(this, dv);
1373         this.value = vv;
1374         
1375         
1376         
1377     },
1378     // private
1379     reset : function(){
1380         // overridden so that last data is reset..
1381         
1382         if(this.multiple){
1383             this.clearItem();
1384             return;
1385         }
1386         
1387         this.setValue(this.originalValue);
1388         //this.clearInvalid();
1389         this.lastData = false;
1390         if (this.view) {
1391             this.view.clearSelections();
1392         }
1393         
1394         this.validate();
1395     },
1396     // private
1397     findRecord : function(prop, value){
1398         var record;
1399         if(this.store.getCount() > 0){
1400             this.store.each(function(r){
1401                 if(r.data[prop] == value){
1402                     record = r;
1403                     return false;
1404                 }
1405                 return true;
1406             });
1407         }
1408         return record;
1409     },
1410     
1411     getName: function()
1412     {
1413         // returns hidden if it's set..
1414         if (!this.rendered) {return ''};
1415         return !this.hiddenName && this.inputEl().dom.name  ? this.inputEl().dom.name : (this.hiddenName || '');
1416         
1417     },
1418     // private
1419     onViewMove : function(e, t){
1420         this.inKeyMode = false;
1421     },
1422
1423     // private
1424     onViewOver : function(e, t){
1425         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
1426             return;
1427         }
1428         var item = this.view.findItemFromChild(t);
1429         
1430         if(item){
1431             var index = this.view.indexOf(item);
1432             this.select(index, false);
1433         }
1434     },
1435
1436     // private
1437     onViewClick : function(view, doFocus, el, e)
1438     {
1439         var index = this.view.getSelectedIndexes()[0];
1440         
1441         var r = this.store.getAt(index);
1442         
1443         if(this.tickable){
1444             
1445             if(typeof(e) != 'undefined' && e.getTarget().nodeName.toLowerCase() != 'input'){
1446                 return;
1447             }
1448             
1449             var rm = false;
1450             var _this = this;
1451             
1452             Roo.each(this.tickItems, function(v,k){
1453                 
1454                 if(typeof(v) != 'undefined' && v[_this.valueField] == r.data[_this.valueField]){
1455                     Roo.log(v);
1456                     _this.tickItems.splice(k, 1);
1457                     
1458                     if(typeof(e) == 'undefined' && view == false){
1459                         Roo.get(_this.view.getNodes(index, index)[0]).select('input', true).first().dom.checked = false;
1460                     }
1461                     
1462                     rm = true;
1463                     return;
1464                 }
1465             });
1466             
1467             if(rm){
1468                 return;
1469             }
1470             
1471             if(this.fireEvent('tick', this, r, index, Roo.get(_this.view.getNodes(index, index)[0]).select('input', true).first().dom.checked) !== false){
1472                 this.tickItems.push(r.data);
1473             }
1474             
1475             if(typeof(e) == 'undefined' && view == false){
1476                 Roo.get(_this.view.getNodes(index, index)[0]).select('input', true).first().dom.checked = true;
1477             }
1478                     
1479             return;
1480         }
1481         
1482         if(r){
1483             this.onSelect(r, index);
1484         }
1485         if(doFocus !== false && !this.blockFocus){
1486             this.inputEl().focus();
1487         }
1488     },
1489
1490     // private
1491     restrictHeight : function(){
1492         //this.innerList.dom.style.height = '';
1493         //var inner = this.innerList.dom;
1494         //var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
1495         //this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
1496         //this.list.beginUpdate();
1497         //this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
1498         this.list.alignTo(this.inputEl(), this.listAlign);
1499         this.list.alignTo(this.inputEl(), this.listAlign);
1500         //this.list.endUpdate();
1501     },
1502
1503     // private
1504     onEmptyResults : function(){
1505         
1506         if(this.tickable && this.editable){
1507             this.restrictHeight();
1508             return;
1509         }
1510         
1511         this.collapse();
1512     },
1513
1514     /**
1515      * Returns true if the dropdown list is expanded, else false.
1516      */
1517     isExpanded : function(){
1518         return this.list.isVisible();
1519     },
1520
1521     /**
1522      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
1523      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
1524      * @param {String} value The data value of the item to select
1525      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
1526      * selected item if it is not currently in view (defaults to true)
1527      * @return {Boolean} True if the value matched an item in the list, else false
1528      */
1529     selectByValue : function(v, scrollIntoView){
1530         if(v !== undefined && v !== null){
1531             var r = this.findRecord(this.valueField || this.displayField, v);
1532             if(r){
1533                 this.select(this.store.indexOf(r), scrollIntoView);
1534                 return true;
1535             }
1536         }
1537         return false;
1538     },
1539
1540     /**
1541      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
1542      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
1543      * @param {Number} index The zero-based index of the list item to select
1544      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
1545      * selected item if it is not currently in view (defaults to true)
1546      */
1547     select : function(index, scrollIntoView){
1548         this.selectedIndex = index;
1549         this.view.select(index);
1550         if(scrollIntoView !== false){
1551             var el = this.view.getNode(index);
1552             /*
1553              * el && !this.multiple && !this.tickable // not sure why we disable multiple before..
1554              */
1555             if(el){
1556                 this.list.scrollChildIntoView(el, false);
1557             }
1558         }
1559     },
1560
1561     // private
1562     selectNext : function(){
1563         var ct = this.store.getCount();
1564         if(ct > 0){
1565             if(this.selectedIndex == -1){
1566                 this.select(0);
1567             }else if(this.selectedIndex < ct-1){
1568                 this.select(this.selectedIndex+1);
1569             }
1570         }
1571     },
1572
1573     // private
1574     selectPrev : function(){
1575         var ct = this.store.getCount();
1576         if(ct > 0){
1577             if(this.selectedIndex == -1){
1578                 this.select(0);
1579             }else if(this.selectedIndex != 0){
1580                 this.select(this.selectedIndex-1);
1581             }
1582         }
1583     },
1584
1585     // private
1586     onKeyUp : function(e){
1587         if(this.editable !== false && !e.isSpecialKey()){
1588             this.lastKey = e.getKey();
1589             this.dqTask.delay(this.queryDelay);
1590         }
1591     },
1592
1593     // private
1594     validateBlur : function(){
1595         return !this.list || !this.list.isVisible();   
1596     },
1597
1598     // private
1599     initQuery : function(){
1600         
1601         var v = this.getRawValue();
1602         
1603         if(this.tickable && this.editable){
1604             v = this.tickableInputEl().getValue();
1605         }
1606         
1607         this.doQuery(v);
1608     },
1609
1610     // private
1611     doForce : function(){
1612         if(this.inputEl().dom.value.length > 0){
1613             this.inputEl().dom.value =
1614                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
1615              
1616         }
1617     },
1618
1619     /**
1620      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
1621      * query allowing the query action to be canceled if needed.
1622      * @param {String} query The SQL query to execute
1623      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
1624      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
1625      * saved in the current store (defaults to false)
1626      */
1627     doQuery : function(q, forceAll){
1628         
1629         if(q === undefined || q === null){
1630             q = '';
1631         }
1632         var qe = {
1633             query: q,
1634             forceAll: forceAll,
1635             combo: this,
1636             cancel:false
1637         };
1638         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
1639             return false;
1640         }
1641         q = qe.query;
1642         
1643         forceAll = qe.forceAll;
1644         if(forceAll === true || (q.length >= this.minChars)){
1645             
1646             this.hasQuery = true;
1647             
1648             if(this.lastQuery != q || this.alwaysQuery){
1649                 this.lastQuery = q;
1650                 if(this.mode == 'local'){
1651                     this.selectedIndex = -1;
1652                     if(forceAll){
1653                         this.store.clearFilter();
1654                     }else{
1655                         
1656                         if(this.specialFilter){
1657                             this.fireEvent('specialfilter', this);
1658                             this.onLoad();
1659                             return;
1660                         }
1661                         
1662                         this.store.filter(this.displayField, q);
1663                     }
1664                     
1665                     this.store.fireEvent("datachanged", this.store);
1666                     
1667                     this.onLoad();
1668                     
1669                     
1670                 }else{
1671                     
1672                     this.store.baseParams[this.queryParam] = q;
1673                     
1674                     var options = {params : this.getParams(q)};
1675                     
1676                     if(this.loadNext){
1677                         options.add = true;
1678                         options.params.start = this.page * this.pageSize;
1679                     }
1680                     
1681                     this.store.load(options);
1682                     
1683                     /*
1684                      *  this code will make the page width larger, at the beginning, the list not align correctly, 
1685                      *  we should expand the list on onLoad
1686                      *  so command out it
1687                      */
1688 //                    this.expand();
1689                 }
1690             }else{
1691                 this.selectedIndex = -1;
1692                 this.onLoad();   
1693             }
1694         }
1695         
1696         this.loadNext = false;
1697     },
1698     
1699     // private
1700     getParams : function(q){
1701         var p = {};
1702         //p[this.queryParam] = q;
1703         
1704         if(this.pageSize){
1705             p.start = 0;
1706             p.limit = this.pageSize;
1707         }
1708         return p;
1709     },
1710
1711     /**
1712      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
1713      */
1714     collapse : function(){
1715         if(!this.isExpanded()){
1716             return;
1717         }
1718         
1719         this.list.hide();
1720         
1721         this.hasFocus = false;
1722         
1723         if(this.tickable){
1724             this.okBtn.hide();
1725             this.cancelBtn.hide();
1726             this.trigger.show();
1727             
1728             if(this.editable){
1729                 this.tickableInputEl().dom.value = '';
1730                 this.tickableInputEl().blur();
1731             }
1732             
1733         }
1734         
1735         Roo.get(document).un('mousedown', this.collapseIf, this);
1736         Roo.get(document).un('mousewheel', this.collapseIf, this);
1737         if (!this.editable) {
1738             Roo.get(document).un('keydown', this.listKeyPress, this);
1739         }
1740         this.fireEvent('collapse', this);
1741         
1742         this.validate();
1743     },
1744
1745     // private
1746     collapseIf : function(e){
1747         var in_combo  = e.within(this.el);
1748         var in_list =  e.within(this.list);
1749         var is_list = (Roo.get(e.getTarget()).id == this.list.id) ? true : false;
1750         
1751         if (in_combo || in_list || is_list) {
1752             //e.stopPropagation();
1753             return;
1754         }
1755         
1756         if(this.tickable){
1757             this.onTickableFooterButtonClick(e, false, false);
1758         }
1759
1760         this.collapse();
1761         
1762     },
1763
1764     /**
1765      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
1766      */
1767     expand : function(){
1768        
1769         if(this.isExpanded() || !this.hasFocus){
1770             return;
1771         }
1772         
1773         var lw = this.listWidth || Math.max(this.inputEl().getWidth(), this.minListWidth);
1774         this.list.setWidth(lw);
1775         
1776         Roo.log('expand');
1777         
1778         this.list.show();
1779         
1780         this.restrictHeight();
1781         
1782         if(this.tickable){
1783             
1784             this.tickItems = Roo.apply([], this.item);
1785             
1786             this.okBtn.show();
1787             this.cancelBtn.show();
1788             this.trigger.hide();
1789             
1790             if(this.editable){
1791                 this.tickableInputEl().focus();
1792             }
1793             
1794         }
1795         
1796         Roo.get(document).on('mousedown', this.collapseIf, this);
1797         Roo.get(document).on('mousewheel', this.collapseIf, this);
1798         if (!this.editable) {
1799             Roo.get(document).on('keydown', this.listKeyPress, this);
1800         }
1801         
1802         this.fireEvent('expand', this);
1803     },
1804
1805     // private
1806     // Implements the default empty TriggerField.onTriggerClick function
1807     onTriggerClick : function(e)
1808     {
1809         Roo.log('trigger click');
1810         
1811         if(this.disabled || !this.triggerList){
1812             return;
1813         }
1814         
1815         this.page = 0;
1816         this.loadNext = false;
1817         
1818         if(this.isExpanded()){
1819             this.collapse();
1820             if (!this.blockFocus) {
1821                 this.inputEl().focus();
1822             }
1823             
1824         }else {
1825             this.hasFocus = true;
1826             if(this.triggerAction == 'all') {
1827                 this.doQuery(this.allQuery, true);
1828             } else {
1829                 this.doQuery(this.getRawValue());
1830             }
1831             if (!this.blockFocus) {
1832                 this.inputEl().focus();
1833             }
1834         }
1835     },
1836     
1837     onTickableTriggerClick : function(e)
1838     {
1839         if(this.disabled){
1840             return;
1841         }
1842         
1843         this.page = 0;
1844         this.loadNext = false;
1845         this.hasFocus = true;
1846         
1847         if(this.triggerAction == 'all') {
1848             this.doQuery(this.allQuery, true);
1849         } else {
1850             this.doQuery(this.getRawValue());
1851         }
1852     },
1853     
1854     onSearchFieldClick : function(e)
1855     {
1856         if(this.hasFocus && !this.disabled && e.getTarget().nodeName.toLowerCase() != 'button'){
1857             this.onTickableFooterButtonClick(e, false, false);
1858             return;
1859         }
1860         
1861         if(this.hasFocus || this.disabled || e.getTarget().nodeName.toLowerCase() == 'button'){
1862             return;
1863         }
1864         
1865         this.page = 0;
1866         this.loadNext = false;
1867         this.hasFocus = true;
1868         
1869         if(this.triggerAction == 'all') {
1870             this.doQuery(this.allQuery, true);
1871         } else {
1872             this.doQuery(this.getRawValue());
1873         }
1874     },
1875     
1876     listKeyPress : function(e)
1877     {
1878         //Roo.log('listkeypress');
1879         // scroll to first matching element based on key pres..
1880         if (e.isSpecialKey()) {
1881             return false;
1882         }
1883         var k = String.fromCharCode(e.getKey()).toUpperCase();
1884         //Roo.log(k);
1885         var match  = false;
1886         var csel = this.view.getSelectedNodes();
1887         var cselitem = false;
1888         if (csel.length) {
1889             var ix = this.view.indexOf(csel[0]);
1890             cselitem  = this.store.getAt(ix);
1891             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
1892                 cselitem = false;
1893             }
1894             
1895         }
1896         
1897         this.store.each(function(v) { 
1898             if (cselitem) {
1899                 // start at existing selection.
1900                 if (cselitem.id == v.id) {
1901                     cselitem = false;
1902                 }
1903                 return true;
1904             }
1905                 
1906             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
1907                 match = this.store.indexOf(v);
1908                 return false;
1909             }
1910             return true;
1911         }, this);
1912         
1913         if (match === false) {
1914             return true; // no more action?
1915         }
1916         // scroll to?
1917         this.view.select(match);
1918         var sn = Roo.get(this.view.getSelectedNodes()[0]);
1919         sn.scrollIntoView(sn.dom.parentNode, false);
1920     },
1921     
1922     onViewScroll : function(e, t){
1923         
1924         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){
1925             return;
1926         }
1927         
1928         this.hasQuery = true;
1929         
1930         this.loading = this.list.select('.loading', true).first();
1931         
1932         if(this.loading === null){
1933             this.list.createChild({
1934                 tag: 'div',
1935                 cls: 'loading roo-select2-more-results roo-select2-active',
1936                 html: 'Loading more results...'
1937             });
1938             
1939             this.loading = this.list.select('.loading', true).first();
1940             
1941             this.loading.setVisibilityMode(Roo.Element.DISPLAY);
1942             
1943             this.loading.hide();
1944         }
1945         
1946         this.loading.show();
1947         
1948         var _combo = this;
1949         
1950         this.page++;
1951         this.loadNext = true;
1952         
1953         (function() { _combo.doQuery(_combo.allQuery, true); }).defer(500);
1954         
1955         return;
1956     },
1957     
1958     addItem : function(o)
1959     {   
1960         var dv = ''; // display value
1961         
1962         if (this.displayField) {
1963             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
1964         } else {
1965             // this is an error condition!!!
1966             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
1967         }
1968         
1969         if(!dv.length){
1970             return;
1971         }
1972         
1973         var choice = this.choices.createChild({
1974             tag: 'li',
1975             cls: 'roo-select2-search-choice',
1976             cn: [
1977                 {
1978                     tag: 'div',
1979                     html: dv
1980                 },
1981                 {
1982                     tag: 'a',
1983                     href: '#',
1984                     cls: 'roo-select2-search-choice-close',
1985                     tabindex: '-1'
1986                 }
1987             ]
1988             
1989         }, this.searchField);
1990         
1991         var close = choice.select('a.roo-select2-search-choice-close', true).first();
1992         
1993         close.on('click', this.onRemoveItem, this, { item : choice, data : o} );
1994         
1995         this.item.push(o);
1996         
1997         this.lastData = o;
1998         
1999         this.syncValue();
2000         
2001         this.inputEl().dom.value = '';
2002         
2003         this.validate();
2004     },
2005     
2006     onRemoveItem : function(e, _self, o)
2007     {
2008         e.preventDefault();
2009         
2010         this.lastItem = Roo.apply([], this.item);
2011         
2012         var index = this.item.indexOf(o.data) * 1;
2013         
2014         if( index < 0){
2015             Roo.log('not this item?!');
2016             return;
2017         }
2018         
2019         this.item.splice(index, 1);
2020         o.item.remove();
2021         
2022         this.syncValue();
2023         
2024         this.fireEvent('remove', this, e);
2025         
2026         this.validate();
2027         
2028     },
2029     
2030     syncValue : function()
2031     {
2032         if(!this.item.length){
2033             this.clearValue();
2034             return;
2035         }
2036             
2037         var value = [];
2038         var _this = this;
2039         Roo.each(this.item, function(i){
2040             if(_this.valueField){
2041                 value.push(i[_this.valueField]);
2042                 return;
2043             }
2044
2045             value.push(i);
2046         });
2047
2048         this.value = value.join(',');
2049
2050         if(this.hiddenField){
2051             this.hiddenField.dom.value = this.value;
2052         }
2053         
2054         this.store.fireEvent("datachanged", this.store);
2055         
2056         this.validate();
2057     },
2058     
2059     clearItem : function()
2060     {
2061         if(!this.multiple){
2062             return;
2063         }
2064         
2065         this.item = [];
2066         
2067         Roo.each(this.choices.select('>li.roo-select2-search-choice', true).elements, function(c){
2068            c.remove();
2069         });
2070         
2071         this.syncValue();
2072         
2073         this.validate();
2074         
2075         if(this.tickable && !Roo.isTouch){
2076             this.view.refresh();
2077         }
2078     },
2079     
2080     inputEl: function ()
2081     {
2082         if(Roo.isIOS && this.useNativeIOS){
2083             return this.el.select('select.roo-ios-select', true).first();
2084         }
2085         
2086         if(Roo.isTouch && this.mobileTouchView){
2087             return this.el.select('input.form-control',true).first();
2088         }
2089         
2090         if(this.tickable){
2091             return this.searchField;
2092         }
2093         
2094         return this.el.select('input.form-control',true).first();
2095     },
2096     
2097     onTickableFooterButtonClick : function(e, btn, el)
2098     {
2099         e.preventDefault();
2100         
2101         this.lastItem = Roo.apply([], this.item);
2102         
2103         if(btn && btn.name == 'cancel'){
2104             this.tickItems = Roo.apply([], this.item);
2105             this.collapse();
2106             return;
2107         }
2108         
2109         this.clearItem();
2110         
2111         var _this = this;
2112         
2113         Roo.each(this.tickItems, function(o){
2114             _this.addItem(o);
2115         });
2116         
2117         this.collapse();
2118         
2119     },
2120     
2121     validate : function()
2122     {
2123         var v = this.getRawValue();
2124         
2125         if(this.multiple){
2126             v = this.getValue();
2127         }
2128         
2129         if(this.disabled || this.allowBlank || v.length){
2130             this.markValid();
2131             return true;
2132         }
2133         
2134         this.markInvalid();
2135         return false;
2136     },
2137     
2138     tickableInputEl : function()
2139     {
2140         if(!this.tickable || !this.editable){
2141             return this.inputEl();
2142         }
2143         
2144         return this.inputEl().select('.roo-select2-search-field-input', true).first();
2145     },
2146     
2147     
2148     getAutoCreateTouchView : function()
2149     {
2150         var id = Roo.id();
2151         
2152         var cfg = {
2153             cls: 'form-group' //input-group
2154         };
2155         
2156         var input =  {
2157             tag: 'input',
2158             id : id,
2159             type : this.inputType,
2160             cls : 'form-control x-combo-noedit',
2161             autocomplete: 'new-password',
2162             placeholder : this.placeholder || '',
2163             readonly : true
2164         };
2165         
2166         if (this.name) {
2167             input.name = this.name;
2168         }
2169         
2170         if (this.size) {
2171             input.cls += ' input-' + this.size;
2172         }
2173         
2174         if (this.disabled) {
2175             input.disabled = true;
2176         }
2177         
2178         var inputblock = {
2179             cls : '',
2180             cn : [
2181                 input
2182             ]
2183         };
2184         
2185         if(this.before){
2186             inputblock.cls += ' input-group';
2187             
2188             inputblock.cn.unshift({
2189                 tag :'span',
2190                 cls : 'input-group-addon',
2191                 html : this.before
2192             });
2193         }
2194         
2195         if(this.removable && !this.multiple){
2196             inputblock.cls += ' roo-removable';
2197             
2198             inputblock.cn.push({
2199                 tag: 'button',
2200                 html : 'x',
2201                 cls : 'roo-combo-removable-btn close'
2202             });
2203         }
2204
2205         if(this.hasFeedback && !this.allowBlank){
2206             
2207             inputblock.cls += ' has-feedback';
2208             
2209             inputblock.cn.push({
2210                 tag: 'span',
2211                 cls: 'glyphicon form-control-feedback'
2212             });
2213             
2214         }
2215         
2216         if (this.after) {
2217             
2218             inputblock.cls += (this.before) ? '' : ' input-group';
2219             
2220             inputblock.cn.push({
2221                 tag :'span',
2222                 cls : 'input-group-addon',
2223                 html : this.after
2224             });
2225         }
2226
2227         var box = {
2228             tag: 'div',
2229             cn: [
2230                 {
2231                     tag: 'input',
2232                     type : 'hidden',
2233                     cls: 'form-hidden-field'
2234                 },
2235                 inputblock
2236             ]
2237             
2238         };
2239         
2240         if(this.multiple){
2241             box = {
2242                 tag: 'div',
2243                 cn: [
2244                     {
2245                         tag: 'input',
2246                         type : 'hidden',
2247                         cls: 'form-hidden-field'
2248                     },
2249                     {
2250                         tag: 'ul',
2251                         cls: 'roo-select2-choices',
2252                         cn:[
2253                             {
2254                                 tag: 'li',
2255                                 cls: 'roo-select2-search-field',
2256                                 cn: [
2257
2258                                     inputblock
2259                                 ]
2260                             }
2261                         ]
2262                     }
2263                 ]
2264             }
2265         };
2266         
2267         var combobox = {
2268             cls: 'roo-select2-container input-group roo-touchview-combobox ',
2269             cn: [
2270                 box
2271             ]
2272         };
2273         
2274         if(!this.multiple && this.showToggleBtn){
2275             
2276             var caret = {
2277                         tag: 'span',
2278                         cls: 'caret'
2279             };
2280             
2281             if (this.caret != false) {
2282                 caret = {
2283                      tag: 'i',
2284                      cls: 'fa fa-' + this.caret
2285                 };
2286                 
2287             }
2288             
2289             combobox.cn.push({
2290                 tag :'span',
2291                 cls : 'input-group-addon btn dropdown-toggle',
2292                 cn : [
2293                     caret,
2294                     {
2295                         tag: 'span',
2296                         cls: 'combobox-clear',
2297                         cn  : [
2298                             {
2299                                 tag : 'i',
2300                                 cls: 'icon-remove'
2301                             }
2302                         ]
2303                     }
2304                 ]
2305
2306             })
2307         }
2308         
2309         if(this.multiple){
2310             combobox.cls += ' roo-select2-container-multi';
2311         }
2312         
2313         var align = this.labelAlign || this.parentLabelAlign();
2314         
2315         if (align ==='left' && this.fieldLabel.length) {
2316             
2317             cfg.cn = [
2318                 {
2319                    tag : 'i',
2320                    cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
2321                    tooltip : 'This field is required'
2322                 },
2323                 {
2324                     tag: 'label',
2325                     cls : 'control-label',
2326                     html : this.fieldLabel
2327
2328                 },
2329                 {
2330                     cls : '', 
2331                     cn: [
2332                         combobox
2333                     ]
2334                 }
2335             ];
2336             
2337             var labelCfg = cfg.cn[1];
2338             var contentCfg = cfg.cn[2];
2339             
2340
2341             if(this.indicatorpos == 'right'){
2342                 cfg.cn = [
2343                     {
2344                         tag: 'label',
2345                         cls : 'control-label',
2346                         html : this.fieldLabel
2347
2348                     },
2349                     {
2350                        tag : 'i',
2351                        cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
2352                        tooltip : 'This field is required'
2353                     },
2354                     {
2355                         cls : '', 
2356                         cn: [
2357                             combobox
2358                         ]
2359                     }
2360                 ];
2361             }
2362             
2363             labelCfg = cfg.cn[0];
2364             
2365             if(this.labelWidth > 12){
2366                 labelCfg.style = "width: " + this.labelWidth + 'px';
2367             }
2368             
2369             if(this.labelWidth < 13 && this.labelmd == 0){
2370                 this.labelmd = this.labelWidth;
2371             }
2372             
2373             if(this.labellg > 0){
2374                 labelCfg.cls += ' col-lg-' + this.labellg;
2375                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
2376             }
2377             
2378             if(this.labelmd > 0){
2379                 labelCfg.cls += ' col-md-' + this.labelmd;
2380                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
2381             }
2382             
2383             if(this.labelsm > 0){
2384                 labelCfg.cls += ' col-sm-' + this.labelsm;
2385                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
2386             }
2387             
2388             if(this.labelxs > 0){
2389                 labelCfg.cls += ' col-xs-' + this.labelxs;
2390                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
2391             }
2392                 
2393                 
2394         } else if ( this.fieldLabel.length) {
2395             cfg.cn = [
2396                 {
2397                    tag : 'i',
2398                    cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
2399                    tooltip : 'This field is required'
2400                 },
2401                 {
2402                     tag: 'label',
2403                     cls : 'control-label',
2404                     html : this.fieldLabel
2405
2406                 },
2407                 {
2408                     cls : '', 
2409                     cn: [
2410                         combobox
2411                     ]
2412                 }
2413             ];
2414             
2415             if(this.indicatorpos == 'right'){
2416                 cfg.cn = [
2417                     {
2418                         tag: 'label',
2419                         cls : 'control-label',
2420                         html : this.fieldLabel
2421
2422                     },
2423                     {
2424                        tag : 'i',
2425                        cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
2426                        tooltip : 'This field is required'
2427                     },
2428                     {
2429                         cls : '', 
2430                         cn: [
2431                             combobox
2432                         ]
2433                     }
2434                 ];
2435             }
2436         } else {
2437             cfg.cn = combobox;    
2438         }
2439         
2440         
2441         var settings = this;
2442         
2443         ['xs','sm','md','lg'].map(function(size){
2444             if (settings[size]) {
2445                 cfg.cls += ' col-' + size + '-' + settings[size];
2446             }
2447         });
2448         
2449         return cfg;
2450     },
2451     
2452     initTouchView : function()
2453     {
2454         this.renderTouchView();
2455         
2456         this.touchViewEl.on('scroll', function(){
2457             this.el.dom.scrollTop = 0;
2458         }, this);
2459         
2460         this.originalValue = this.getValue();
2461         
2462         this.triggerEl = this.el.select('span.dropdown-toggle',true).first();
2463         
2464         this.inputEl().on("click", this.showTouchView, this);
2465         if (this.triggerEl) {
2466             this.triggerEl.on("click", this.showTouchView, this);
2467         }
2468         
2469         
2470         this.touchViewFooterEl.select('.roo-touch-view-cancel', true).first().on('click', this.hideTouchView, this);
2471         this.touchViewFooterEl.select('.roo-touch-view-ok', true).first().on('click', this.setTouchViewValue, this);
2472         
2473         this.maskEl = new Roo.LoadMask(this.touchViewEl, { store : this.store, msgCls: 'roo-el-mask-msg' });
2474         
2475         this.store.on('beforeload', this.onTouchViewBeforeLoad, this);
2476         this.store.on('load', this.onTouchViewLoad, this);
2477         this.store.on('loadexception', this.onTouchViewLoadException, this);
2478         
2479         if(this.hiddenName){
2480             
2481             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
2482             
2483             this.hiddenField.dom.value =
2484                 this.hiddenValue !== undefined ? this.hiddenValue :
2485                 this.value !== undefined ? this.value : '';
2486         
2487             this.el.dom.removeAttribute('name');
2488             this.hiddenField.dom.setAttribute('name', this.hiddenName);
2489         }
2490         
2491         if(this.multiple){
2492             this.choices = this.el.select('ul.roo-select2-choices', true).first();
2493             this.searchField = this.el.select('ul li.roo-select2-search-field', true).first();
2494         }
2495         
2496         if(this.removable && !this.multiple){
2497             var close = this.closeTriggerEl();
2498             if(close){
2499                 close.setVisibilityMode(Roo.Element.DISPLAY).hide();
2500                 close.on('click', this.removeBtnClick, this, close);
2501             }
2502         }
2503         /*
2504          * fix the bug in Safari iOS8
2505          */
2506         this.inputEl().on("focus", function(e){
2507             document.activeElement.blur();
2508         }, this);
2509         
2510         return;
2511         
2512         
2513     },
2514     
2515     renderTouchView : function()
2516     {
2517         this.touchViewEl = Roo.get(document.body).createChild(Roo.bootstrap.ComboBox.touchViewTemplate);
2518         this.touchViewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
2519         
2520         this.touchViewHeaderEl = this.touchViewEl.select('.modal-header', true).first();
2521         this.touchViewHeaderEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
2522         
2523         this.touchViewBodyEl = this.touchViewEl.select('.modal-body', true).first();
2524         this.touchViewBodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
2525         this.touchViewBodyEl.setStyle('overflow', 'auto');
2526         
2527         this.touchViewListGroup = this.touchViewBodyEl.select('.list-group', true).first();
2528         this.touchViewListGroup.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
2529         
2530         this.touchViewFooterEl = this.touchViewEl.select('.modal-footer', true).first();
2531         this.touchViewFooterEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
2532         
2533     },
2534     
2535     showTouchView : function()
2536     {
2537         if(this.disabled){
2538             return;
2539         }
2540         
2541         this.touchViewHeaderEl.hide();
2542
2543         if(this.modalTitle.length){
2544             this.touchViewHeaderEl.dom.innerHTML = this.modalTitle;
2545             this.touchViewHeaderEl.show();
2546         }
2547
2548         this.touchViewEl.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
2549         this.touchViewEl.show();
2550
2551         this.touchViewEl.select('.modal-dialog', true).first().setStyle('margin', '0px');
2552         this.touchViewEl.select('.modal-dialog > .modal-content', true).first().setSize(
2553                 Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
2554
2555         var bodyHeight = Roo.lib.Dom.getViewHeight() - this.touchViewFooterEl.getHeight() + this.touchViewBodyEl.getPadding('tb');
2556
2557         if(this.modalTitle.length){
2558             bodyHeight = bodyHeight - this.touchViewHeaderEl.getHeight();
2559         }
2560         
2561         this.touchViewBodyEl.setHeight(bodyHeight);
2562
2563         if(this.animate){
2564             var _this = this;
2565             (function(){ _this.touchViewEl.addClass('in'); }).defer(50);
2566         }else{
2567             this.touchViewEl.addClass('in');
2568         }
2569
2570         this.doTouchViewQuery();
2571         
2572     },
2573     
2574     hideTouchView : function()
2575     {
2576         this.touchViewEl.removeClass('in');
2577
2578         if(this.animate){
2579             var _this = this;
2580             (function(){ _this.touchViewEl.setStyle('display', 'none'); }).defer(150);
2581         }else{
2582             this.touchViewEl.setStyle('display', 'none');
2583         }
2584         
2585     },
2586     
2587     setTouchViewValue : function()
2588     {
2589         if(this.multiple){
2590             this.clearItem();
2591         
2592             var _this = this;
2593
2594             Roo.each(this.tickItems, function(o){
2595                 this.addItem(o);
2596             }, this);
2597         }
2598         
2599         this.hideTouchView();
2600     },
2601     
2602     doTouchViewQuery : function()
2603     {
2604         var qe = {
2605             query: '',
2606             forceAll: true,
2607             combo: this,
2608             cancel:false
2609         };
2610         
2611         if(this.fireEvent('beforequery', qe) ===false || qe.cancel){
2612             return false;
2613         }
2614         
2615         if(!this.alwaysQuery || this.mode == 'local'){
2616             this.onTouchViewLoad();
2617             return;
2618         }
2619         
2620         this.store.load();
2621     },
2622     
2623     onTouchViewBeforeLoad : function(combo,opts)
2624     {
2625         return;
2626     },
2627
2628     // private
2629     onTouchViewLoad : function()
2630     {
2631         if(this.store.getCount() < 1){
2632             this.onTouchViewEmptyResults();
2633             return;
2634         }
2635         
2636         this.clearTouchView();
2637         
2638         var rawValue = this.getRawValue();
2639         
2640         var template = (this.multiple) ? Roo.bootstrap.ComboBox.listItemCheckbox : Roo.bootstrap.ComboBox.listItemRadio;
2641         
2642         this.tickItems = [];
2643         
2644         this.store.data.each(function(d, rowIndex){
2645             var row = this.touchViewListGroup.createChild(template);
2646             
2647             if(typeof(d.data.cls) != 'undefined' && d.data.cls.length){
2648                 row.addClass(d.data.cls);
2649             }
2650             
2651             if(this.displayField && typeof(d.data[this.displayField]) != 'undefined'){
2652                 var cfg = {
2653                     data : d.data,
2654                     html : d.data[this.displayField]
2655                 };
2656                 
2657                 if(this.fireEvent('touchviewdisplay', this, cfg) !== false){
2658                     row.select('.roo-combobox-list-group-item-value', true).first().dom.innerHTML = cfg.html;
2659                 }
2660             }
2661             row.removeClass('selected');
2662             if(!this.multiple && this.valueField &&
2663                     typeof(d.data[this.valueField]) != 'undefined' && d.data[this.valueField] == this.getValue())
2664             {
2665                 // radio buttons..
2666                 row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
2667                 row.addClass('selected');
2668             }
2669             
2670             if(this.multiple && this.valueField &&
2671                     typeof(d.data[this.valueField]) != 'undefined' && this.getValue().indexOf(d.data[this.valueField]) != -1)
2672             {
2673                 
2674                 // checkboxes...
2675                 row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
2676                 this.tickItems.push(d.data);
2677             }
2678             
2679             row.on('click', this.onTouchViewClick, this, {row : row, rowIndex : rowIndex});
2680             
2681         }, this);
2682         
2683         var firstChecked = this.touchViewListGroup.select('.list-group-item > .roo-combobox-list-group-item-box > input:checked', true).first();
2684         
2685         var bodyHeight = Roo.lib.Dom.getViewHeight() - this.touchViewFooterEl.getHeight() + this.touchViewBodyEl.getPadding('tb');
2686
2687         if(this.modalTitle.length){
2688             bodyHeight = bodyHeight - this.touchViewHeaderEl.getHeight();
2689         }
2690
2691         var listHeight = this.touchViewListGroup.getHeight();
2692         
2693         var _this = this;
2694         
2695         if(firstChecked && listHeight > bodyHeight){
2696             (function() { firstChecked.findParent('li').scrollIntoView(_this.touchViewListGroup.dom); }).defer(500);
2697         }
2698         
2699     },
2700     
2701     onTouchViewLoadException : function()
2702     {
2703         this.hideTouchView();
2704     },
2705     
2706     onTouchViewEmptyResults : function()
2707     {
2708         this.clearTouchView();
2709         
2710         this.touchViewListGroup.createChild(Roo.bootstrap.ComboBox.emptyResult);
2711         
2712         this.touchViewListGroup.select('.roo-combobox-touch-view-empty-result', true).first().dom.innerHTML = this.emptyResultText;
2713         
2714     },
2715     
2716     clearTouchView : function()
2717     {
2718         this.touchViewListGroup.dom.innerHTML = '';
2719     },
2720     
2721     onTouchViewClick : function(e, el, o)
2722     {
2723         e.preventDefault();
2724         
2725         var row = o.row;
2726         var rowIndex = o.rowIndex;
2727         
2728         var r = this.store.getAt(rowIndex);
2729         
2730         if(this.fireEvent('beforeselect', this, r, rowIndex) !== false){
2731             
2732             if(!this.multiple){
2733                 Roo.each(this.touchViewListGroup.select('.list-group-item > .roo-combobox-list-group-item-box > input:checked', true).elements, function(c){
2734                     c.dom.removeAttribute('checked');
2735                 }, this);
2736
2737                 row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
2738
2739                 this.setFromData(r.data);
2740
2741                 var close = this.closeTriggerEl();
2742
2743                 if(close){
2744                     close.show();
2745                 }
2746
2747                 this.hideTouchView();
2748
2749                 this.fireEvent('select', this, r, rowIndex);
2750
2751                 return;
2752             }
2753
2754             if(this.valueField && typeof(r.data[this.valueField]) != 'undefined' && this.getValue().indexOf(r.data[this.valueField]) != -1){
2755                 row.select('.roo-combobox-list-group-item-box > input', true).first().dom.removeAttribute('checked');
2756                 this.tickItems.splice(this.tickItems.indexOf(r.data), 1);
2757                 return;
2758             }
2759
2760             row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
2761             this.addItem(r.data);
2762             this.tickItems.push(r.data);
2763         }
2764     },
2765     
2766     getAutoCreateNativeIOS : function()
2767     {
2768         var cfg = {
2769             cls: 'form-group' //input-group,
2770         };
2771         
2772         var combobox =  {
2773             tag: 'select',
2774             cls : 'roo-ios-select'
2775         };
2776         
2777         if (this.name) {
2778             combobox.name = this.name;
2779         }
2780         
2781         if (this.disabled) {
2782             combobox.disabled = true;
2783         }
2784         
2785         var settings = this;
2786         
2787         ['xs','sm','md','lg'].map(function(size){
2788             if (settings[size]) {
2789                 cfg.cls += ' col-' + size + '-' + settings[size];
2790             }
2791         });
2792         
2793         cfg.cn = combobox;
2794         
2795         return cfg;
2796         
2797     },
2798     
2799     initIOSView : function()
2800     {
2801         this.store.on('load', this.onIOSViewLoad, this);
2802         
2803         return;
2804     },
2805     
2806     onIOSViewLoad : function()
2807     {
2808         if(this.store.getCount() < 1){
2809             return;
2810         }
2811         
2812         this.clearIOSView();
2813         
2814         if(this.allowBlank) {
2815             
2816             var default_text = '-- SELECT --';
2817             
2818             var opt = this.inputEl().createChild({
2819                 tag: 'option',
2820                 value : 0,
2821                 html : default_text
2822             });
2823             
2824             var o = {};
2825             o[this.valueField] = 0;
2826             o[this.displayField] = default_text;
2827             
2828             this.ios_options.push({
2829                 data : o,
2830                 el : opt
2831             });
2832             
2833         }
2834         
2835         this.store.data.each(function(d, rowIndex){
2836             
2837             var html = '';
2838             
2839             if(this.displayField && typeof(d.data[this.displayField]) != 'undefined'){
2840                 html = d.data[this.displayField];
2841             }
2842             
2843             var value = '';
2844             
2845             if(this.valueField && typeof(d.data[this.valueField]) != 'undefined'){
2846                 value = d.data[this.valueField];
2847             }
2848             
2849             var option = {
2850                 tag: 'option',
2851                 value : value,
2852                 html : html
2853             };
2854             
2855             if(this.value == d.data[this.valueField]){
2856                 option['selected'] = true;
2857             }
2858             
2859             var opt = this.inputEl().createChild(option);
2860             
2861             this.ios_options.push({
2862                 data : d.data,
2863                 el : opt
2864             });
2865             
2866         }, this);
2867         
2868         this.inputEl().on('change', function(){
2869            this.fireEvent('select', this);
2870         }, this);
2871         
2872     },
2873     
2874     clearIOSView: function()
2875     {
2876         this.inputEl().dom.innerHTML = '';
2877         
2878         this.ios_options = [];
2879     },
2880     
2881     setIOSValue: function(v)
2882     {
2883         this.value = v;
2884         
2885         if(!this.ios_options){
2886             return;
2887         }
2888         
2889         Roo.each(this.ios_options, function(opts){
2890            
2891            opts.el.dom.removeAttribute('selected');
2892            
2893            if(opts.data[this.valueField] != v){
2894                return;
2895            }
2896            
2897            opts.el.dom.setAttribute('selected', true);
2898            
2899         }, this);
2900     }
2901
2902     /** 
2903     * @cfg {Boolean} grow 
2904     * @hide 
2905     */
2906     /** 
2907     * @cfg {Number} growMin 
2908     * @hide 
2909     */
2910     /** 
2911     * @cfg {Number} growMax 
2912     * @hide 
2913     */
2914     /**
2915      * @hide
2916      * @method autoSize
2917      */
2918 });
2919
2920 Roo.apply(Roo.bootstrap.ComboBox,  {
2921     
2922     header : {
2923         tag: 'div',
2924         cls: 'modal-header',
2925         cn: [
2926             {
2927                 tag: 'h4',
2928                 cls: 'modal-title'
2929             }
2930         ]
2931     },
2932     
2933     body : {
2934         tag: 'div',
2935         cls: 'modal-body',
2936         cn: [
2937             {
2938                 tag: 'ul',
2939                 cls: 'list-group'
2940             }
2941         ]
2942     },
2943     
2944     listItemRadio : {
2945         tag: 'li',
2946         cls: 'list-group-item',
2947         cn: [
2948             {
2949                 tag: 'span',
2950                 cls: 'roo-combobox-list-group-item-value'
2951             },
2952             {
2953                 tag: 'div',
2954                 cls: 'roo-combobox-list-group-item-box pull-xs-right radio-inline radio radio-info',
2955                 cn: [
2956                     {
2957                         tag: 'input',
2958                         type: 'radio'
2959                     },
2960                     {
2961                         tag: 'label'
2962                     }
2963                 ]
2964             }
2965         ]
2966     },
2967     
2968     listItemCheckbox : {
2969         tag: 'li',
2970         cls: 'list-group-item',
2971         cn: [
2972             {
2973                 tag: 'span',
2974                 cls: 'roo-combobox-list-group-item-value'
2975             },
2976             {
2977                 tag: 'div',
2978                 cls: 'roo-combobox-list-group-item-box pull-xs-right checkbox-inline checkbox checkbox-info',
2979                 cn: [
2980                     {
2981                         tag: 'input',
2982                         type: 'checkbox'
2983                     },
2984                     {
2985                         tag: 'label'
2986                     }
2987                 ]
2988             }
2989         ]
2990     },
2991     
2992     emptyResult : {
2993         tag: 'div',
2994         cls: 'alert alert-danger roo-combobox-touch-view-empty-result'
2995     },
2996     
2997     footer : {
2998         tag: 'div',
2999         cls: 'modal-footer',
3000         cn: [
3001             {
3002                 tag: 'div',
3003                 cls: 'row',
3004                 cn: [
3005                     {
3006                         tag: 'div',
3007                         cls: 'col-xs-6 text-left',
3008                         cn: {
3009                             tag: 'button',
3010                             cls: 'btn btn-danger roo-touch-view-cancel',
3011                             html: 'Cancel'
3012                         }
3013                     },
3014                     {
3015                         tag: 'div',
3016                         cls: 'col-xs-6 text-right',
3017                         cn: {
3018                             tag: 'button',
3019                             cls: 'btn btn-success roo-touch-view-ok',
3020                             html: 'OK'
3021                         }
3022                     }
3023                 ]
3024             }
3025         ]
3026         
3027     }
3028 });
3029
3030 Roo.apply(Roo.bootstrap.ComboBox,  {
3031     
3032     touchViewTemplate : {
3033         tag: 'div',
3034         cls: 'modal fade roo-combobox-touch-view',
3035         cn: [
3036             {
3037                 tag: 'div',
3038                 cls: 'modal-dialog',
3039                 style : 'position:fixed', // we have to fix position....
3040                 cn: [
3041                     {
3042                         tag: 'div',
3043                         cls: 'modal-content',
3044                         cn: [
3045                             Roo.bootstrap.ComboBox.header,
3046                             Roo.bootstrap.ComboBox.body,
3047                             Roo.bootstrap.ComboBox.footer
3048                         ]
3049                     }
3050                 ]
3051             }
3052         ]
3053     }
3054 });