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