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