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