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