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