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