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