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