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