Merge branch 'master' of http://git.roojs.com/roojs1
[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  * @constructor
17  * Create a new ComboBox.
18  * @param {Object} config Configuration options
19  */
20 Roo.bootstrap.ComboBox = function(config){
21     Roo.bootstrap.ComboBox.superclass.constructor.call(this, config);
22     this.addEvents({
23         /**
24          * @event expand
25          * Fires when the dropdown list is expanded
26              * @param {Roo.bootstrap.ComboBox} combo This combo box
27              */
28         'expand' : true,
29         /**
30          * @event collapse
31          * Fires when the dropdown list is collapsed
32              * @param {Roo.bootstrap.ComboBox} combo This combo box
33              */
34         'collapse' : true,
35         /**
36          * @event beforeselect
37          * Fires before a list item is selected. Return false to cancel the selection.
38              * @param {Roo.bootstrap.ComboBox} combo This combo box
39              * @param {Roo.data.Record} record The data record returned from the underlying store
40              * @param {Number} index The index of the selected item in the dropdown list
41              */
42         'beforeselect' : true,
43         /**
44          * @event select
45          * Fires when a list item is selected
46              * @param {Roo.bootstrap.ComboBox} combo This combo box
47              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
48              * @param {Number} index The index of the selected item in the dropdown list
49              */
50         'select' : true,
51         /**
52          * @event beforequery
53          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
54          * The event object passed has these properties:
55              * @param {Roo.bootstrap.ComboBox} combo This combo box
56              * @param {String} query The query
57              * @param {Boolean} forceAll true to force "all" query
58              * @param {Boolean} cancel true to cancel the query
59              * @param {Object} e The query event object
60              */
61         'beforequery': true,
62          /**
63          * @event add
64          * Fires when the 'add' icon is pressed (add a listener to enable add button)
65              * @param {Roo.bootstrap.ComboBox} combo This combo box
66              */
67         'add' : true,
68         /**
69          * @event edit
70          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
71              * @param {Roo.bootstrap.ComboBox} combo This combo box
72              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
73              */
74         'edit' : true,
75         /**
76          * @event remove
77          * Fires when the remove value from the combobox array
78              * @param {Roo.bootstrap.ComboBox} combo This combo box
79              */
80         'remove' : true
81         
82     });
83     
84     this.item = [];
85     this.tickItems = [];
86     
87     this.selectedIndex = -1;
88     if(this.mode == 'local'){
89         if(config.queryDelay === undefined){
90             this.queryDelay = 10;
91         }
92         if(config.minChars === undefined){
93             this.minChars = 0;
94         }
95     }
96 };
97
98 Roo.extend(Roo.bootstrap.ComboBox, Roo.bootstrap.TriggerField, {
99      
100     /**
101      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
102      * rendering into an Roo.Editor, defaults to false)
103      */
104     /**
105      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
106      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
107      */
108     /**
109      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
110      */
111     /**
112      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
113      * the dropdown list (defaults to undefined, with no header element)
114      */
115
116      /**
117      * @cfg {String/Roo.Template} tpl The template to use to render the output
118      */
119      
120      /**
121      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
122      */
123     listWidth: undefined,
124     /**
125      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
126      * mode = 'remote' or 'text' if mode = 'local')
127      */
128     displayField: undefined,
129     /**
130      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
131      * mode = 'remote' or 'value' if mode = 'local'). 
132      * Note: use of a valueField requires the user make a selection
133      * in order for a value to be mapped.
134      */
135     valueField: undefined,
136     
137     
138     /**
139      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
140      * field's data value (defaults to the underlying DOM element's name)
141      */
142     hiddenName: undefined,
143     /**
144      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
145      */
146     listClass: '',
147     /**
148      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
149      */
150     selectedClass: 'active',
151     
152     /**
153      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
154      */
155     shadow:'sides',
156     /**
157      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
158      * anchor positions (defaults to 'tl-bl')
159      */
160     listAlign: 'tl-bl?',
161     /**
162      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
163      */
164     maxHeight: 300,
165     /**
166      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
167      * query specified by the allQuery config option (defaults to 'query')
168      */
169     triggerAction: 'query',
170     /**
171      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
172      * (defaults to 4, does not apply if editable = false)
173      */
174     minChars : 4,
175     /**
176      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
177      * delay (typeAheadDelay) if it matches a known value (defaults to false)
178      */
179     typeAhead: false,
180     /**
181      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
182      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
183      */
184     queryDelay: 500,
185     /**
186      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
187      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
188      */
189     pageSize: 0,
190     /**
191      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
192      * when editable = true (defaults to false)
193      */
194     selectOnFocus:false,
195     /**
196      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
197      */
198     queryParam: 'query',
199     /**
200      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
201      * when mode = 'remote' (defaults to 'Loading...')
202      */
203     loadingText: 'Loading...',
204     /**
205      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
206      */
207     resizable: false,
208     /**
209      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
210      */
211     handleHeight : 8,
212     /**
213      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
214      * traditional select (defaults to true)
215      */
216     editable: true,
217     /**
218      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
219      */
220     allQuery: '',
221     /**
222      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
223      */
224     mode: 'remote',
225     /**
226      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
227      * listWidth has a higher value)
228      */
229     minListWidth : 70,
230     /**
231      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
232      * allow the user to set arbitrary text into the field (defaults to false)
233      */
234     forceSelection:false,
235     /**
236      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
237      * if typeAhead = true (defaults to 250)
238      */
239     typeAheadDelay : 250,
240     /**
241      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
242      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
243      */
244     valueNotFoundText : undefined,
245     /**
246      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
247      */
248     blockFocus : false,
249     
250     /**
251      * @cfg {Boolean} disableClear Disable showing of clear button.
252      */
253     disableClear : false,
254     /**
255      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
256      */
257     alwaysQuery : false,
258     
259     /**
260      * @cfg {Boolean} multiple  (true|false) ComboBobArray, default false
261      */
262     multiple : false,
263     
264     //private
265     addicon : false,
266     editicon: false,
267     
268     page: 0,
269     hasQuery: false,
270     append: false,
271     loadNext: false,
272     autoFocus : true,
273     tickable : false,
274     btnPosition : 'right',
275     triggerList : true,
276     showToggleBtn : true,
277     // element that contains real text value.. (when hidden is used..)
278     
279     getAutoCreate : function()
280     {
281         var cfg = false;
282         
283         /*
284          *  Normal ComboBox
285          */
286         if(!this.tickable){
287             cfg = Roo.bootstrap.ComboBox.superclass.getAutoCreate.call(this);
288             return cfg;
289         }
290         
291         /*
292          *  ComboBox with tickable selections
293          */
294              
295         var align = this.labelAlign || this.parentLabelAlign();
296         
297         cfg = {
298             cls : 'form-group roo-combobox-tickable' //input-group
299         };
300         
301         
302         var buttons = {
303             tag : 'div',
304             cls : 'tickable-buttons',
305             cn : [
306                 {
307                     tag : 'button',
308                     type : 'button',
309                     cls : 'btn btn-link btn-edit pull-' + this.btnPosition,
310                     html : 'Edit'
311                 },
312                 {
313                     tag : 'button',
314                     type : 'button',
315                     name : 'ok',
316                     cls : 'btn btn-link btn-ok pull-' + this.btnPosition,
317                     html : 'Done'
318                 },
319                 {
320                     tag : 'button',
321                     type : 'button',
322                     name : 'cancel',
323                     cls : 'btn btn-link btn-cancel pull-' + this.btnPosition,
324                     html : 'Cancel'
325                 }
326             ]
327         };
328         
329         var _this = this;
330         Roo.each(buttons.cn, function(c){
331             if (_this.size) {
332                 c.cls += ' btn-' + _this.size;
333             }
334
335             if (_this.disabled) {
336                 c.disabled = true;
337             }
338         });
339         
340         var box = {
341             tag: 'div',
342             cn: [
343                 {
344                     tag: 'input',
345                     type : 'hidden',
346                     cls: 'form-hidden-field'
347                 },
348                 {
349                     tag: 'ul',
350                     cls: 'select2-choices',
351                     cn:[
352                         {
353                             tag: 'li',
354                             cls: 'select2-search-field',
355                             cn: [
356
357                                 buttons
358                             ]
359                         }
360                     ]
361                 }
362             ]
363         }
364         
365         var combobox = {
366             cls: 'select2-container input-group select2-container-multi',
367             cn: [
368                 box
369 //                {
370 //                    tag: 'ul',
371 //                    cls: 'typeahead typeahead-long dropdown-menu',
372 //                    style: 'display:none; max-height:' + this.maxHeight + 'px;'
373 //                }
374             ]
375         };
376         
377         if (align ==='left' && this.fieldLabel.length) {
378             
379                 Roo.log("left and has label");
380                 cfg.cn = [
381                     
382                     {
383                         tag: 'label',
384                         'for' :  id,
385                         cls : 'control-label col-sm-' + this.labelWidth,
386                         html : this.fieldLabel
387                         
388                     },
389                     {
390                         cls : "col-sm-" + (12 - this.labelWidth), 
391                         cn: [
392                             combobox
393                         ]
394                     }
395                     
396                 ];
397         } else if ( this.fieldLabel.length) {
398                 Roo.log(" label");
399                  cfg.cn = [
400                    
401                     {
402                         tag: 'label',
403                         //cls : 'input-group-addon',
404                         html : this.fieldLabel
405                         
406                     },
407                     
408                     combobox
409                     
410                 ];
411
412         } else {
413             
414                 Roo.log(" no label && no align");
415                 cfg = combobox
416                      
417                 
418         }
419          
420         var settings=this;
421         ['xs','sm','md','lg'].map(function(size){
422             if (settings[size]) {
423                 cfg.cls += ' col-' + size + '-' + settings[size];
424             }
425         });
426         
427         return cfg;
428         
429     },
430     
431     // private
432     initEvents: function()
433     {
434         
435         if (!this.store) {
436             throw "can not find store for combo";
437         }
438         this.store = Roo.factory(this.store, Roo.data);
439         
440         if(this.tickable){
441             this.initTickableEvents();
442             return;
443         }
444         
445         Roo.bootstrap.ComboBox.superclass.initEvents.call(this);
446         
447         if(this.hiddenName){
448             
449             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
450             
451             this.hiddenField.dom.value =
452                 this.hiddenValue !== undefined ? this.hiddenValue :
453                 this.value !== undefined ? this.value : '';
454
455             // prevent input submission
456             this.el.dom.removeAttribute('name');
457             this.hiddenField.dom.setAttribute('name', this.hiddenName);
458              
459              
460         }
461         //if(Roo.isGecko){
462         //    this.el.dom.setAttribute('autocomplete', 'off');
463         //}
464         
465         var cls = 'x-combo-list';
466         
467         //this.list = new Roo.Layer({
468         //    shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
469         //});
470         
471         var _this = this;
472         
473         (function(){
474             var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
475             _this.list.setWidth(lw);
476         }).defer(100);
477         
478         this.list.on('mouseover', this.onViewOver, this);
479         this.list.on('mousemove', this.onViewMove, this);
480         
481         this.list.on('scroll', this.onViewScroll, this);
482         
483         /*
484         this.list.swallowEvent('mousewheel');
485         this.assetHeight = 0;
486
487         if(this.title){
488             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
489             this.assetHeight += this.header.getHeight();
490         }
491
492         this.innerList = this.list.createChild({cls:cls+'-inner'});
493         this.innerList.on('mouseover', this.onViewOver, this);
494         this.innerList.on('mousemove', this.onViewMove, this);
495         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
496         
497         if(this.allowBlank && !this.pageSize && !this.disableClear){
498             this.footer = this.list.createChild({cls:cls+'-ft'});
499             this.pageTb = new Roo.Toolbar(this.footer);
500            
501         }
502         if(this.pageSize){
503             this.footer = this.list.createChild({cls:cls+'-ft'});
504             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
505                     {pageSize: this.pageSize});
506             
507         }
508         
509         if (this.pageTb && this.allowBlank && !this.disableClear) {
510             var _this = this;
511             this.pageTb.add(new Roo.Toolbar.Fill(), {
512                 cls: 'x-btn-icon x-btn-clear',
513                 text: ' ',
514                 handler: function()
515                 {
516                     _this.collapse();
517                     _this.clearValue();
518                     _this.onSelect(false, -1);
519                 }
520             });
521         }
522         if (this.footer) {
523             this.assetHeight += this.footer.getHeight();
524         }
525         */
526             
527         if(!this.tpl){
528             this.tpl = '<li><a href="#">{' + this.displayField + '}</a></li>';
529         }
530
531         this.view = new Roo.View(this.list, this.tpl, {
532             singleSelect:true, store: this.store, selectedClass: this.selectedClass
533         });
534         //this.view.wrapEl.setDisplayed(false);
535         this.view.on('click', this.onViewClick, this);
536         
537         
538         
539         this.store.on('beforeload', this.onBeforeLoad, this);
540         this.store.on('load', this.onLoad, this);
541         this.store.on('loadexception', this.onLoadException, this);
542         /*
543         if(this.resizable){
544             this.resizer = new Roo.Resizable(this.list,  {
545                pinned:true, handles:'se'
546             });
547             this.resizer.on('resize', function(r, w, h){
548                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
549                 this.listWidth = w;
550                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
551                 this.restrictHeight();
552             }, this);
553             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
554         }
555         */
556         if(!this.editable){
557             this.editable = true;
558             this.setEditable(false);
559         }
560         
561         /*
562         
563         if (typeof(this.events.add.listeners) != 'undefined') {
564             
565             this.addicon = this.wrap.createChild(
566                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
567        
568             this.addicon.on('click', function(e) {
569                 this.fireEvent('add', this);
570             }, this);
571         }
572         if (typeof(this.events.edit.listeners) != 'undefined') {
573             
574             this.editicon = this.wrap.createChild(
575                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
576             if (this.addicon) {
577                 this.editicon.setStyle('margin-left', '40px');
578             }
579             this.editicon.on('click', function(e) {
580                 
581                 // we fire even  if inothing is selected..
582                 this.fireEvent('edit', this, this.lastData );
583                 
584             }, this);
585         }
586         */
587         
588         this.keyNav = new Roo.KeyNav(this.inputEl(), {
589             "up" : function(e){
590                 this.inKeyMode = true;
591                 this.selectPrev();
592             },
593
594             "down" : function(e){
595                 if(!this.isExpanded()){
596                     this.onTriggerClick();
597                 }else{
598                     this.inKeyMode = true;
599                     this.selectNext();
600                 }
601             },
602
603             "enter" : function(e){
604 //                this.onViewClick();
605                 //return true;
606                 this.collapse();
607                 
608                 if(this.fireEvent("specialkey", this, e)){
609                     this.onViewClick(false);
610                 }
611                 
612                 return true;
613             },
614
615             "esc" : function(e){
616                 this.collapse();
617             },
618
619             "tab" : function(e){
620                 this.collapse();
621                 
622                 if(this.fireEvent("specialkey", this, e)){
623                     this.onViewClick(false);
624                 }
625                 
626                 return true;
627             },
628
629             scope : this,
630
631             doRelay : function(foo, bar, hname){
632                 if(hname == 'down' || this.scope.isExpanded()){
633                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
634                 }
635                 return true;
636             },
637
638             forceKeyDown: true
639         });
640         
641         
642         this.queryDelay = Math.max(this.queryDelay || 10,
643                 this.mode == 'local' ? 10 : 250);
644         
645         
646         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
647         
648         if(this.typeAhead){
649             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
650         }
651         if(this.editable !== false){
652             this.inputEl().on("keyup", this.onKeyUp, this);
653         }
654         if(this.forceSelection){
655             this.inputEl().on('blur', this.doForce, this);
656         }
657         
658         if(this.multiple){
659             this.choices = this.el.select('ul.select2-choices', true).first();
660             this.searchField = this.el.select('ul li.select2-search-field', true).first();
661         }
662     },
663     
664     initTickableEvents: function()
665     {   
666         this.createList();
667         
668         if(this.hiddenName){
669             
670             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
671             
672             this.hiddenField.dom.value =
673                 this.hiddenValue !== undefined ? this.hiddenValue :
674                 this.value !== undefined ? this.value : '';
675
676             // prevent input submission
677             this.el.dom.removeAttribute('name');
678             this.hiddenField.dom.setAttribute('name', this.hiddenName);
679              
680              
681         }
682         
683 //        this.list = this.el.select('ul.dropdown-menu',true).first();
684         
685         this.choices = this.el.select('ul.select2-choices', true).first();
686         this.searchField = this.el.select('ul li.select2-search-field', true).first();
687         if(this.triggerList){
688             this.searchField.on("click", this.onSearchFieldClick, this, {preventDefault:true});
689         }
690          
691         this.trigger = this.el.select('.tickable-buttons > .btn-edit', true).first();
692         this.trigger.on("click", this.onTickableTriggerClick, this, {preventDefault:true});
693         
694         this.okBtn = this.el.select('.tickable-buttons > .btn-ok', true).first();
695         this.cancelBtn = this.el.select('.tickable-buttons > .btn-cancel', true).first();
696         
697         this.okBtn.on('click', this.onTickableFooterButtonClick, this, this.okBtn);
698         this.cancelBtn.on('click', this.onTickableFooterButtonClick, this, this.cancelBtn);
699         
700         this.trigger.setVisibilityMode(Roo.Element.DISPLAY);
701         this.okBtn.setVisibilityMode(Roo.Element.DISPLAY);
702         this.cancelBtn.setVisibilityMode(Roo.Element.DISPLAY);
703         
704         this.okBtn.hide();
705         this.cancelBtn.hide();
706         
707         var _this = this;
708         
709         (function(){
710             var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
711             _this.list.setWidth(lw);
712         }).defer(100);
713         
714         this.list.on('mouseover', this.onViewOver, this);
715         this.list.on('mousemove', this.onViewMove, this);
716         
717         this.list.on('scroll', this.onViewScroll, this);
718         
719         if(!this.tpl){
720             this.tpl = '<li class="select2-result"><div class="checkbox"><input id="{roo-id}" type="checkbox" {roo-data-checked}><label for="{roo-id}"><b>{' + this.displayField + '}</b></label></li>';
721         }
722
723         this.view = new Roo.View(this.list, this.tpl, {
724             singleSelect:true, tickable:true, parent:this, store: this.store, selectedClass: this.selectedClass
725         });
726         
727         //this.view.wrapEl.setDisplayed(false);
728         this.view.on('click', this.onViewClick, this);
729         
730         
731         
732         this.store.on('beforeload', this.onBeforeLoad, this);
733         this.store.on('load', this.onLoad, this);
734         this.store.on('loadexception', this.onLoadException, this);
735         
736 //        this.keyNav = new Roo.KeyNav(this.inputEl(), {
737 //            "up" : function(e){
738 //                this.inKeyMode = true;
739 //                this.selectPrev();
740 //            },
741 //
742 //            "down" : function(e){
743 //                if(!this.isExpanded()){
744 //                    this.onTriggerClick();
745 //                }else{
746 //                    this.inKeyMode = true;
747 //                    this.selectNext();
748 //                }
749 //            },
750 //
751 //            "enter" : function(e){
752 ////                this.onViewClick();
753 //                //return true;
754 //                this.collapse();
755 //                
756 //                if(this.fireEvent("specialkey", this, e)){
757 //                    this.onViewClick(false);
758 //                }
759 //                
760 //                return true;
761 //            },
762 //
763 //            "esc" : function(e){
764 //                this.collapse();
765 //            },
766 //
767 //            "tab" : function(e){
768 //                this.collapse();
769 //                
770 //                if(this.fireEvent("specialkey", this, e)){
771 //                    this.onViewClick(false);
772 //                }
773 //                
774 //                return true;
775 //            },
776 //
777 //            scope : this,
778 //
779 //            doRelay : function(foo, bar, hname){
780 //                if(hname == 'down' || this.scope.isExpanded()){
781 //                   return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
782 //                }
783 //                return true;
784 //            },
785 //
786 //            forceKeyDown: true
787 //        });
788         
789         
790         this.queryDelay = Math.max(this.queryDelay || 10,
791                 this.mode == 'local' ? 10 : 250);
792         
793         
794         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
795         
796         if(this.typeAhead){
797             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
798         }
799     },
800
801     onDestroy : function(){
802         if(this.view){
803             this.view.setStore(null);
804             this.view.el.removeAllListeners();
805             this.view.el.remove();
806             this.view.purgeListeners();
807         }
808         if(this.list){
809             this.list.dom.innerHTML  = '';
810         }
811         
812         if(this.store){
813             this.store.un('beforeload', this.onBeforeLoad, this);
814             this.store.un('load', this.onLoad, this);
815             this.store.un('loadexception', this.onLoadException, this);
816         }
817         Roo.bootstrap.ComboBox.superclass.onDestroy.call(this);
818     },
819
820     // private
821     fireKey : function(e){
822         if(e.isNavKeyPress() && !this.list.isVisible()){
823             this.fireEvent("specialkey", this, e);
824         }
825     },
826
827     // private
828     onResize: function(w, h){
829 //        Roo.bootstrap.ComboBox.superclass.onResize.apply(this, arguments);
830 //        
831 //        if(typeof w != 'number'){
832 //            // we do not handle it!?!?
833 //            return;
834 //        }
835 //        var tw = this.trigger.getWidth();
836 //       // tw += this.addicon ? this.addicon.getWidth() : 0;
837 //       // tw += this.editicon ? this.editicon.getWidth() : 0;
838 //        var x = w - tw;
839 //        this.inputEl().setWidth( this.adjustWidth('input', x));
840 //            
841 //        //this.trigger.setStyle('left', x+'px');
842 //        
843 //        if(this.list && this.listWidth === undefined){
844 //            var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
845 //            this.list.setWidth(lw);
846 //            this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
847 //        }
848         
849     
850         
851     },
852
853     /**
854      * Allow or prevent the user from directly editing the field text.  If false is passed,
855      * the user will only be able to select from the items defined in the dropdown list.  This method
856      * is the runtime equivalent of setting the 'editable' config option at config time.
857      * @param {Boolean} value True to allow the user to directly edit the field text
858      */
859     setEditable : function(value){
860         if(value == this.editable){
861             return;
862         }
863         this.editable = value;
864         if(!value){
865             this.inputEl().dom.setAttribute('readOnly', true);
866             this.inputEl().on('mousedown', this.onTriggerClick,  this);
867             this.inputEl().addClass('x-combo-noedit');
868         }else{
869             this.inputEl().dom.setAttribute('readOnly', false);
870             this.inputEl().un('mousedown', this.onTriggerClick,  this);
871             this.inputEl().removeClass('x-combo-noedit');
872         }
873     },
874
875     // private
876     
877     onBeforeLoad : function(combo,opts){
878         if(!this.hasFocus){
879             return;
880         }
881          if (!opts.add) {
882             this.list.dom.innerHTML = '<li class="loading-indicator">'+(this.loadingText||'loading')+'</li>' ;
883          }
884 //        this.restrictHeight();
885         this.selectedIndex = -1;
886     },
887
888     // private
889     onLoad : function(){
890         
891         this.hasQuery = false;
892         
893         if(!this.hasFocus){
894             return;
895         }
896         
897         if(typeof(this.loading) !== 'undefined' && this.loading !== null){
898             this.loading.hide();
899         }
900         
901         if(this.store.getCount() > 0){
902             this.expand();
903 //            this.restrictHeight();
904             if(this.lastQuery == this.allQuery){
905                 if(this.editable && !this.tickable){
906                     this.inputEl().dom.select();
907                 }
908                 if(!this.selectByValue(this.value, true) && this.autoFocus){
909                     this.select(0, true);
910                 }
911             }else{
912                 if(this.autoFocus){
913                     this.selectNext();
914                 }
915                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
916                     this.taTask.delay(this.typeAheadDelay);
917                 }
918             }
919         }else{
920             this.onEmptyResults();
921         }
922         
923         //this.el.focus();
924     },
925     // private
926     onLoadException : function()
927     {
928         this.hasQuery = false;
929         
930         if(typeof(this.loading) !== 'undefined' && this.loading !== null){
931             this.loading.hide();
932         }
933         
934         this.collapse();
935         Roo.log(this.store.reader.jsonData);
936         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
937             // fixme
938             //Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
939         }
940         
941         
942     },
943     // private
944     onTypeAhead : function(){
945         if(this.store.getCount() > 0){
946             var r = this.store.getAt(0);
947             var newValue = r.data[this.displayField];
948             var len = newValue.length;
949             var selStart = this.getRawValue().length;
950             
951             if(selStart != len){
952                 this.setRawValue(newValue);
953                 this.selectText(selStart, newValue.length);
954             }
955         }
956     },
957
958     // private
959     onSelect : function(record, index){
960         
961         if(this.fireEvent('beforeselect', this, record, index) !== false){
962         
963             this.setFromData(index > -1 ? record.data : false);
964             
965             this.collapse();
966             this.fireEvent('select', this, record, index);
967         }
968     },
969
970     /**
971      * Returns the currently selected field value or empty string if no value is set.
972      * @return {String} value The selected value
973      */
974     getValue : function(){
975         
976         if(this.multiple){
977             return (this.hiddenField) ? this.hiddenField.dom.value : this.value;
978         }
979         
980         if(this.valueField){
981             return typeof this.value != 'undefined' ? this.value : '';
982         }else{
983             return Roo.bootstrap.ComboBox.superclass.getValue.call(this);
984         }
985     },
986
987     /**
988      * Clears any text/value currently set in the field
989      */
990     clearValue : function(){
991         if(this.hiddenField){
992             this.hiddenField.dom.value = '';
993         }
994         this.value = '';
995         this.setRawValue('');
996         this.lastSelectionText = '';
997         
998     },
999
1000     /**
1001      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
1002      * will be displayed in the field.  If the value does not match the data value of an existing item,
1003      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
1004      * Otherwise the field will be blank (although the value will still be set).
1005      * @param {String} value The value to match
1006      */
1007     setValue : function(v){
1008         if(this.multiple){
1009             this.syncValue();
1010             return;
1011         }
1012         
1013         var text = v;
1014         if(this.valueField){
1015             var r = this.findRecord(this.valueField, v);
1016             if(r){
1017                 text = r.data[this.displayField];
1018             }else if(this.valueNotFoundText !== undefined){
1019                 text = this.valueNotFoundText;
1020             }
1021         }
1022         this.lastSelectionText = text;
1023         if(this.hiddenField){
1024             this.hiddenField.dom.value = v;
1025         }
1026         Roo.bootstrap.ComboBox.superclass.setValue.call(this, text);
1027         this.value = v;
1028     },
1029     /**
1030      * @property {Object} the last set data for the element
1031      */
1032     
1033     lastData : false,
1034     /**
1035      * Sets the value of the field based on a object which is related to the record format for the store.
1036      * @param {Object} value the value to set as. or false on reset?
1037      */
1038     setFromData : function(o){
1039         
1040         if(this.multiple){
1041             if(typeof o.display_name !== 'string'){
1042                 for(var i=0;i<o.display_name.length;i++){
1043                     this.addItem({'id':o.id[i],'display_name':o.display_name[i]});
1044                 }
1045                 return;
1046             }
1047             this.addItem(o);
1048             return;
1049         }
1050             
1051         var dv = ''; // display value
1052         var vv = ''; // value value..
1053         this.lastData = o;
1054         if (this.displayField) {
1055             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
1056         } else {
1057             // this is an error condition!!!
1058             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
1059         }
1060         
1061         if(this.valueField){
1062             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
1063         }
1064         
1065         if(this.hiddenField){
1066             this.hiddenField.dom.value = vv;
1067             
1068             this.lastSelectionText = dv;
1069             Roo.bootstrap.ComboBox.superclass.setValue.call(this, dv);
1070             this.value = vv;
1071             return;
1072         }
1073         // no hidden field.. - we store the value in 'value', but still display
1074         // display field!!!!
1075         this.lastSelectionText = dv;
1076         Roo.bootstrap.ComboBox.superclass.setValue.call(this, dv);
1077         this.value = vv;
1078         
1079         
1080     },
1081     // private
1082     reset : function(){
1083         // overridden so that last data is reset..
1084         this.setValue(this.originalValue);
1085         this.clearInvalid();
1086         this.lastData = false;
1087         if (this.view) {
1088             this.view.clearSelections();
1089         }
1090     },
1091     // private
1092     findRecord : function(prop, value){
1093         var record;
1094         if(this.store.getCount() > 0){
1095             this.store.each(function(r){
1096                 if(r.data[prop] == value){
1097                     record = r;
1098                     return false;
1099                 }
1100                 return true;
1101             });
1102         }
1103         return record;
1104     },
1105     
1106     getName: function()
1107     {
1108         // returns hidden if it's set..
1109         if (!this.rendered) {return ''};
1110         return !this.hiddenName && this.inputEl().dom.name  ? this.inputEl().dom.name : (this.hiddenName || '');
1111         
1112     },
1113     // private
1114     onViewMove : function(e, t){
1115         this.inKeyMode = false;
1116     },
1117
1118     // private
1119     onViewOver : function(e, t){
1120         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
1121             return;
1122         }
1123         var item = this.view.findItemFromChild(t);
1124         
1125         if(item){
1126             var index = this.view.indexOf(item);
1127             this.select(index, false);
1128         }
1129     },
1130
1131     // private
1132     onViewClick : function(view, doFocus, el, e)
1133     {
1134         var index = this.view.getSelectedIndexes()[0];
1135         
1136         var r = this.store.getAt(index);
1137         
1138         if(this.tickable){
1139             
1140             if(e.getTarget().nodeName.toLowerCase() != 'input'){
1141                 return;
1142             }
1143             
1144             var rm = false;
1145             var _this = this;
1146             
1147             Roo.each(this.tickItems, function(v,k){
1148                 
1149                 if(typeof(v) != 'undefined' && v[_this.valueField] == r.data[_this.valueField]){
1150                     _this.tickItems.splice(k, 1);
1151                     rm = true;
1152                     return;
1153                 }
1154             })
1155             
1156             if(rm){
1157                 return;
1158             }
1159             
1160             this.tickItems.push(r.data);
1161             return;
1162         }
1163         
1164         if(r){
1165             this.onSelect(r, index);
1166         }
1167         if(doFocus !== false && !this.blockFocus){
1168             this.inputEl().focus();
1169         }
1170     },
1171
1172     // private
1173     restrictHeight : function(){
1174         //this.innerList.dom.style.height = '';
1175         //var inner = this.innerList.dom;
1176         //var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
1177         //this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
1178         //this.list.beginUpdate();
1179         //this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
1180         this.list.alignTo(this.inputEl(), this.listAlign);
1181         this.list.alignTo(this.inputEl(), this.listAlign);
1182         //this.list.endUpdate();
1183     },
1184
1185     // private
1186     onEmptyResults : function(){
1187         this.collapse();
1188     },
1189
1190     /**
1191      * Returns true if the dropdown list is expanded, else false.
1192      */
1193     isExpanded : function(){
1194         return this.list.isVisible();
1195     },
1196
1197     /**
1198      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
1199      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
1200      * @param {String} value The data value of the item to select
1201      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
1202      * selected item if it is not currently in view (defaults to true)
1203      * @return {Boolean} True if the value matched an item in the list, else false
1204      */
1205     selectByValue : function(v, scrollIntoView){
1206         if(v !== undefined && v !== null){
1207             var r = this.findRecord(this.valueField || this.displayField, v);
1208             if(r){
1209                 this.select(this.store.indexOf(r), scrollIntoView);
1210                 return true;
1211             }
1212         }
1213         return false;
1214     },
1215
1216     /**
1217      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
1218      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
1219      * @param {Number} index The zero-based index of the list item to select
1220      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
1221      * selected item if it is not currently in view (defaults to true)
1222      */
1223     select : function(index, scrollIntoView){
1224         this.selectedIndex = index;
1225         this.view.select(index);
1226         if(scrollIntoView !== false){
1227             var el = this.view.getNode(index);
1228             if(el && !this.multiple && !this.tickable){
1229                 this.list.scrollChildIntoView(el, false);
1230             }
1231         }
1232     },
1233
1234     // private
1235     selectNext : function(){
1236         var ct = this.store.getCount();
1237         if(ct > 0){
1238             if(this.selectedIndex == -1){
1239                 this.select(0);
1240             }else if(this.selectedIndex < ct-1){
1241                 this.select(this.selectedIndex+1);
1242             }
1243         }
1244     },
1245
1246     // private
1247     selectPrev : function(){
1248         var ct = this.store.getCount();
1249         if(ct > 0){
1250             if(this.selectedIndex == -1){
1251                 this.select(0);
1252             }else if(this.selectedIndex != 0){
1253                 this.select(this.selectedIndex-1);
1254             }
1255         }
1256     },
1257
1258     // private
1259     onKeyUp : function(e){
1260         if(this.editable !== false && !e.isSpecialKey()){
1261             this.lastKey = e.getKey();
1262             this.dqTask.delay(this.queryDelay);
1263         }
1264     },
1265
1266     // private
1267     validateBlur : function(){
1268         return !this.list || !this.list.isVisible();   
1269     },
1270
1271     // private
1272     initQuery : function(){
1273         this.doQuery(this.getRawValue());
1274     },
1275
1276     // private
1277     doForce : function(){
1278         if(this.inputEl().dom.value.length > 0){
1279             this.inputEl().dom.value =
1280                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
1281              
1282         }
1283     },
1284
1285     /**
1286      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
1287      * query allowing the query action to be canceled if needed.
1288      * @param {String} query The SQL query to execute
1289      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
1290      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
1291      * saved in the current store (defaults to false)
1292      */
1293     doQuery : function(q, forceAll){
1294         
1295         if(q === undefined || q === null){
1296             q = '';
1297         }
1298         var qe = {
1299             query: q,
1300             forceAll: forceAll,
1301             combo: this,
1302             cancel:false
1303         };
1304         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
1305             return false;
1306         }
1307         q = qe.query;
1308         
1309         forceAll = qe.forceAll;
1310         if(forceAll === true || (q.length >= this.minChars)){
1311             
1312             this.hasQuery = true;
1313             
1314             if(this.lastQuery != q || this.alwaysQuery){
1315                 this.lastQuery = q;
1316                 if(this.mode == 'local'){
1317                     this.selectedIndex = -1;
1318                     if(forceAll){
1319                         this.store.clearFilter();
1320                     }else{
1321                         this.store.filter(this.displayField, q);
1322                     }
1323                     this.onLoad();
1324                 }else{
1325                     this.store.baseParams[this.queryParam] = q;
1326                     
1327                     var options = {params : this.getParams(q)};
1328                     
1329                     if(this.loadNext){
1330                         options.add = true;
1331                         options.params.start = this.page * this.pageSize;
1332                     }
1333                     
1334                     this.store.load(options);
1335                     /*
1336                      *  this code will make the page width larger, at the beginning, the list not align correctly, 
1337                      *  we should expand the list on onLoad
1338                      *  so command out it
1339                      */
1340 //                    this.expand();
1341                 }
1342             }else{
1343                 this.selectedIndex = -1;
1344                 this.onLoad();   
1345             }
1346         }
1347         
1348         this.loadNext = false;
1349     },
1350
1351     // private
1352     getParams : function(q){
1353         var p = {};
1354         //p[this.queryParam] = q;
1355         
1356         if(this.pageSize){
1357             p.start = 0;
1358             p.limit = this.pageSize;
1359         }
1360         return p;
1361     },
1362
1363     /**
1364      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
1365      */
1366     collapse : function(){
1367         if(!this.isExpanded()){
1368             return;
1369         }
1370         
1371         this.hasFocus = false;
1372         
1373         this.list.hide();
1374         
1375         if(this.tickable){
1376             this.okBtn.hide();
1377             this.cancelBtn.hide();
1378             this.trigger.show();
1379         }
1380         
1381         Roo.get(document).un('mousedown', this.collapseIf, this);
1382         Roo.get(document).un('mousewheel', this.collapseIf, this);
1383         if (!this.editable) {
1384             Roo.get(document).un('keydown', this.listKeyPress, this);
1385         }
1386         this.fireEvent('collapse', this);
1387     },
1388
1389     // private
1390     collapseIf : function(e){
1391         var in_combo  = e.within(this.el);
1392         var in_list =  e.within(this.list);
1393         var is_list = (Roo.get(e.getTarget()).id == this.list.id) ? true : false;
1394         
1395         if (in_combo || in_list || is_list) {
1396             //e.stopPropagation();
1397             return;
1398         }
1399         
1400         if(this.tickable){
1401             this.onTickableFooterButtonClick(e, false, false);
1402         }
1403
1404         this.collapse();
1405         
1406     },
1407
1408     /**
1409      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
1410      */
1411     expand : function(){
1412        
1413         if(this.isExpanded() || !this.hasFocus){
1414             return;
1415         }
1416         
1417         var lw = this.listWidth || Math.max(this.inputEl().getWidth(), this.minListWidth);
1418         this.list.setWidth(lw);
1419         
1420         
1421          Roo.log('expand');
1422         
1423         this.list.show();
1424         
1425         this.restrictHeight();
1426         
1427         if(this.tickable){
1428             
1429             this.tickItems = Roo.apply([], this.item);
1430             
1431             this.okBtn.show();
1432             this.cancelBtn.show();
1433             this.trigger.hide();
1434             
1435         }
1436         
1437         Roo.get(document).on('mousedown', this.collapseIf, this);
1438         Roo.get(document).on('mousewheel', this.collapseIf, this);
1439         if (!this.editable) {
1440             Roo.get(document).on('keydown', this.listKeyPress, this);
1441         }
1442         
1443         this.fireEvent('expand', this);
1444     },
1445
1446     // private
1447     // Implements the default empty TriggerField.onTriggerClick function
1448     onTriggerClick : function(e)
1449     {
1450         Roo.log('trigger click');
1451         
1452         if(this.disabled || !this.triggerList){
1453             return;
1454         }
1455         
1456         this.page = 0;
1457         this.loadNext = false;
1458         
1459         if(this.isExpanded()){
1460             this.collapse();
1461             if (!this.blockFocus) {
1462                 this.inputEl().focus();
1463             }
1464             
1465         }else {
1466             this.hasFocus = true;
1467             if(this.triggerAction == 'all') {
1468                 this.doQuery(this.allQuery, true);
1469             } else {
1470                 this.doQuery(this.getRawValue());
1471             }
1472             if (!this.blockFocus) {
1473                 this.inputEl().focus();
1474             }
1475         }
1476     },
1477     
1478     onTickableTriggerClick : function(e)
1479     {
1480         if(this.disabled){
1481             return;
1482         }
1483         
1484         this.page = 0;
1485         this.loadNext = false;
1486         this.hasFocus = true;
1487         
1488         if(this.triggerAction == 'all') {
1489             this.doQuery(this.allQuery, true);
1490         } else {
1491             this.doQuery(this.getRawValue());
1492         }
1493     },
1494     
1495     onSearchFieldClick : function(e)
1496     {
1497         if(this.hasFocus || this.disabled || e.getTarget().nodeName.toLowerCase() == 'button'){
1498             return;
1499         }
1500         
1501         this.page = 0;
1502         this.loadNext = false;
1503         this.hasFocus = true;
1504         
1505         if(this.triggerAction == 'all') {
1506             this.doQuery(this.allQuery, true);
1507         } else {
1508             this.doQuery(this.getRawValue());
1509         }
1510     },
1511     
1512     listKeyPress : function(e)
1513     {
1514         //Roo.log('listkeypress');
1515         // scroll to first matching element based on key pres..
1516         if (e.isSpecialKey()) {
1517             return false;
1518         }
1519         var k = String.fromCharCode(e.getKey()).toUpperCase();
1520         //Roo.log(k);
1521         var match  = false;
1522         var csel = this.view.getSelectedNodes();
1523         var cselitem = false;
1524         if (csel.length) {
1525             var ix = this.view.indexOf(csel[0]);
1526             cselitem  = this.store.getAt(ix);
1527             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
1528                 cselitem = false;
1529             }
1530             
1531         }
1532         
1533         this.store.each(function(v) { 
1534             if (cselitem) {
1535                 // start at existing selection.
1536                 if (cselitem.id == v.id) {
1537                     cselitem = false;
1538                 }
1539                 return true;
1540             }
1541                 
1542             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
1543                 match = this.store.indexOf(v);
1544                 return false;
1545             }
1546             return true;
1547         }, this);
1548         
1549         if (match === false) {
1550             return true; // no more action?
1551         }
1552         // scroll to?
1553         this.view.select(match);
1554         var sn = Roo.get(this.view.getSelectedNodes()[0])
1555         //sn.scrollIntoView(sn.dom.parentNode, false);
1556     },
1557     
1558     onViewScroll : function(e, t){
1559         
1560         if(this.view.el.getScroll().top < this.view.el.dom.scrollHeight - this.view.el.dom.clientHeight || !this.hasFocus || !this.append || this.hasQuery){
1561             return;
1562         }
1563         
1564         this.hasQuery = true;
1565         
1566         this.loading = this.list.select('.loading', true).first();
1567         
1568         if(this.loading === null){
1569             this.list.createChild({
1570                 tag: 'div',
1571                 cls: 'loading select2-more-results select2-active',
1572                 html: 'Loading more results...'
1573             })
1574             
1575             this.loading = this.list.select('.loading', true).first();
1576             
1577             this.loading.setVisibilityMode(Roo.Element.DISPLAY);
1578             
1579             this.loading.hide();
1580         }
1581         
1582         this.loading.show();
1583         
1584         var _combo = this;
1585         
1586         this.page++;
1587         this.loadNext = true;
1588         
1589         (function() { _combo.doQuery(_combo.allQuery, true); }).defer(500);
1590         
1591         return;
1592     },
1593     
1594     addItem : function(o)
1595     {   
1596         var dv = ''; // display value
1597         
1598         if (this.displayField) {
1599             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
1600         } else {
1601             // this is an error condition!!!
1602             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
1603         }
1604         
1605         if(!dv.length){
1606             return;
1607         }
1608         
1609         var choice = this.choices.createChild({
1610             tag: 'li',
1611             cls: 'select2-search-choice',
1612             cn: [
1613                 {
1614                     tag: 'div',
1615                     html: dv
1616                 },
1617                 {
1618                     tag: 'a',
1619                     href: '#',
1620                     cls: 'select2-search-choice-close',
1621                     tabindex: '-1'
1622                 }
1623             ]
1624             
1625         }, this.searchField);
1626         
1627         var close = choice.select('a.select2-search-choice-close', true).first()
1628         
1629         close.on('click', this.onRemoveItem, this, { item : choice, data : o} );
1630         
1631         this.item.push(o);
1632         
1633         this.lastData = o;
1634         
1635         this.syncValue();
1636         
1637         this.inputEl().dom.value = '';
1638         
1639     },
1640     
1641     onRemoveItem : function(e, _self, o)
1642     {
1643         e.preventDefault();
1644         var index = this.item.indexOf(o.data) * 1;
1645         
1646         if( index < 0){
1647             Roo.log('not this item?!');
1648             return;
1649         }
1650         
1651         this.item.splice(index, 1);
1652         o.item.remove();
1653         
1654         this.syncValue();
1655         
1656         this.fireEvent('remove', this, e);
1657         
1658     },
1659     
1660     syncValue : function()
1661     {
1662         if(!this.item.length){
1663             this.clearValue();
1664             return;
1665         }
1666             
1667         var value = [];
1668         var _this = this;
1669         Roo.each(this.item, function(i){
1670             if(_this.valueField){
1671                 value.push(i[_this.valueField]);
1672                 return;
1673             }
1674
1675             value.push(i);
1676         });
1677
1678         this.value = value.join(',');
1679
1680         if(this.hiddenField){
1681             this.hiddenField.dom.value = this.value;
1682         }
1683     },
1684     
1685     clearItem : function()
1686     {
1687         if(!this.multiple){
1688             return;
1689         }
1690         
1691         this.item = [];
1692         
1693         Roo.each(this.choices.select('>li.select2-search-choice', true).elements, function(c){
1694            c.remove();
1695         });
1696         
1697         this.syncValue();
1698     },
1699     
1700     inputEl: function ()
1701     {
1702         if(this.tickable){
1703             return this.searchField;
1704         }
1705         return this.el.select('input.form-control',true).first();
1706     },
1707     
1708     
1709     onTickableFooterButtonClick : function(e, btn, el)
1710     {
1711         e.preventDefault();
1712         
1713         if(btn && btn.name == 'cancel'){
1714             this.tickItems = Roo.apply([], this.item);
1715             this.collapse();
1716             return;
1717         }
1718         
1719         this.clearItem();
1720         
1721         var _this = this;
1722         
1723         Roo.each(this.tickItems, function(o){
1724             _this.addItem(o);
1725         });
1726         
1727         this.collapse();
1728         
1729     }
1730     
1731     
1732
1733     /** 
1734     * @cfg {Boolean} grow 
1735     * @hide 
1736     */
1737     /** 
1738     * @cfg {Number} growMin 
1739     * @hide 
1740     */
1741     /** 
1742     * @cfg {Number} growMax 
1743     * @hide 
1744     */
1745     /**
1746      * @hide
1747      * @method autoSize
1748      */
1749 });