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