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