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