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