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