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