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