Roo/form/ComboBox.js
[roojs1] / Roo / form / ComboBox.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12
13 /**
14  * @class Roo.form.ComboBox
15  * @extends Roo.form.TriggerField
16  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
17  * @constructor
18  * Create a new ComboBox.
19  * @param {Object} config Configuration options
20  */
21 Roo.form.ComboBox = function(config){
22     Roo.form.ComboBox.superclass.constructor.call(this, config);
23     this.addEvents({
24         /**
25          * @event expand
26          * Fires when the dropdown list is expanded
27              * @param {Roo.form.ComboBox} combo This combo box
28              */
29         'expand' : true,
30         /**
31          * @event collapse
32          * Fires when the dropdown list is collapsed
33              * @param {Roo.form.ComboBox} combo This combo box
34              */
35         'collapse' : true,
36         /**
37          * @event beforeselect
38          * Fires before a list item is selected. Return false to cancel the selection.
39              * @param {Roo.form.ComboBox} combo This combo box
40              * @param {Roo.data.Record} record The data record returned from the underlying store
41              * @param {Number} index The index of the selected item in the dropdown list
42              */
43         'beforeselect' : true,
44         /**
45          * @event select
46          * Fires when a list item is selected
47              * @param {Roo.form.ComboBox} combo This combo box
48              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
49              * @param {Number} index The index of the selected item in the dropdown list
50              */
51         'select' : true,
52         /**
53          * @event beforequery
54          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
55          * The event object passed has these properties:
56              * @param {Roo.form.ComboBox} combo This combo box
57              * @param {String} query The query
58              * @param {Boolean} forceAll true to force "all" query
59              * @param {Boolean} cancel true to cancel the query
60              * @param {Object} e The query event object
61              */
62         'beforequery': true,
63          /**
64          * @event add
65          * Fires when the 'add' icon is pressed (add a listener to enable add button)
66              * @param {Roo.form.ComboBox} combo This combo box
67              */
68         'add' : true,
69         /**
70          * @event add
71          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
72              * @param {Roo.form.ComboBox} combo This combo box
73              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
74              */
75         'edit' : true
76         
77         
78     });
79     if(this.transform){
80         this.allowDomMove = false;
81         var s = Roo.getDom(this.transform);
82         if(!this.hiddenName){
83             this.hiddenName = s.name;
84         }
85         if(!this.store){
86             this.mode = 'local';
87             var d = [], opts = s.options;
88             for(var i = 0, len = opts.length;i < len; i++){
89                 var o = opts[i];
90                 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
91                 if(o.selected) {
92                     this.value = value;
93                 }
94                 d.push([value, o.text]);
95             }
96             this.store = new Roo.data.SimpleStore({
97                 'id': 0,
98                 fields: ['value', 'text'],
99                 data : d
100             });
101             this.valueField = 'value';
102             this.displayField = 'text';
103         }
104         s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
105         if(!this.lazyRender){
106             this.target = true;
107             this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
108             s.parentNode.removeChild(s); // remove it
109             this.render(this.el.parentNode);
110         }else{
111             s.parentNode.removeChild(s); // remove it
112         }
113
114     }
115     if (this.store) {
116         this.store = Roo.factory(this.store, Roo.data);
117     }
118     
119     this.selectedIndex = -1;
120     if(this.mode == 'local'){
121         if(config.queryDelay === undefined){
122             this.queryDelay = 10;
123         }
124         if(config.minChars === undefined){
125             this.minChars = 0;
126         }
127     }
128 };
129
130 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
131     /**
132      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
133      */
134     /**
135      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
136      * rendering into an Roo.Editor, defaults to false)
137      */
138     /**
139      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
140      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
141      */
142     /**
143      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
144      */
145     /**
146      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
147      * the dropdown list (defaults to undefined, with no header element)
148      */
149
150      /**
151      * @cfg {String/Roo.Template} tpl The template to use to render the output
152      */
153      
154     // private
155     defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
156     /**
157      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
158      */
159     listWidth: undefined,
160     /**
161      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
162      * mode = 'remote' or 'text' if mode = 'local')
163      */
164     displayField: undefined,
165     /**
166      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
167      * mode = 'remote' or 'value' if mode = 'local'). 
168      * Note: use of a valueField requires the user make a selection
169      * in order for a value to be mapped.
170      */
171     valueField: undefined,
172     /**
173      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
174      * field's data value (defaults to the underlying DOM element's name)
175      */
176     hiddenName: undefined,
177     /**
178      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
179      */
180     listClass: '',
181     /**
182      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
183      */
184     selectedClass: 'x-combo-selected',
185     /**
186      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
187      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
188      * which displays a downward arrow icon).
189      */
190     triggerClass : 'x-form-arrow-trigger',
191     /**
192      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
193      */
194     shadow:'sides',
195     /**
196      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
197      * anchor positions (defaults to 'tl-bl')
198      */
199     listAlign: 'tl-bl?',
200     /**
201      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
202      */
203     maxHeight: 300,
204     /**
205      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
206      * query specified by the allQuery config option (defaults to 'query')
207      */
208     triggerAction: 'query',
209     /**
210      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
211      * (defaults to 4, does not apply if editable = false)
212      */
213     minChars : 4,
214     /**
215      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
216      * delay (typeAheadDelay) if it matches a known value (defaults to false)
217      */
218     typeAhead: false,
219     /**
220      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
221      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
222      */
223     queryDelay: 500,
224     /**
225      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
226      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
227      */
228     pageSize: 0,
229     /**
230      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
231      * when editable = true (defaults to false)
232      */
233     selectOnFocus:false,
234     /**
235      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
236      */
237     queryParam: 'query',
238     /**
239      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
240      * when mode = 'remote' (defaults to 'Loading...')
241      */
242     loadingText: 'Loading...',
243     /**
244      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
245      */
246     resizable: false,
247     /**
248      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
249      */
250     handleHeight : 8,
251     /**
252      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
253      * traditional select (defaults to true)
254      */
255     editable: true,
256     /**
257      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
258      */
259     allQuery: '',
260     /**
261      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
262      */
263     mode: 'remote',
264     /**
265      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
266      * listWidth has a higher value)
267      */
268     minListWidth : 70,
269     /**
270      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
271      * allow the user to set arbitrary text into the field (defaults to false)
272      */
273     forceSelection:false,
274     /**
275      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
276      * if typeAhead = true (defaults to 250)
277      */
278     typeAheadDelay : 250,
279     /**
280      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
281      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
282      */
283     valueNotFoundText : undefined,
284     /**
285      * @cfg {bool} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
286      */
287     blockFocus : false,
288     
289     /**
290      * @cfg {bool} disableClear Disable showing of clear button.
291      */
292     disableClear : false,
293     
294     // private
295     onRender : function(ct, position){
296         Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
297         if(this.hiddenName){
298             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
299                     'before', true);
300             this.hiddenField.value =
301                 this.hiddenValue !== undefined ? this.hiddenValue :
302                 this.value !== undefined ? this.value : '';
303
304             // prevent input submission
305             this.el.dom.removeAttribute('name');
306         }
307         if(Roo.isGecko){
308             this.el.dom.setAttribute('autocomplete', 'off');
309         }
310
311         var cls = 'x-combo-list';
312
313         this.list = new Roo.Layer({
314             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
315         });
316
317         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
318         this.list.setWidth(lw);
319         this.list.swallowEvent('mousewheel');
320         this.assetHeight = 0;
321
322         if(this.title){
323             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
324             this.assetHeight += this.header.getHeight();
325         }
326
327         this.innerList = this.list.createChild({cls:cls+'-inner'});
328         this.innerList.on('mouseover', this.onViewOver, this);
329         this.innerList.on('mousemove', this.onViewMove, this);
330         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
331         
332         if(this.allowBlank && !this.pageSize && !this.disableClear){
333             this.footer = this.list.createChild({cls:cls+'-ft'});
334             this.pageTb = new Roo.Toolbar(this.footer);
335            
336         }
337         if(this.pageSize){
338             this.footer = this.list.createChild({cls:cls+'-ft'});
339             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
340                     {pageSize: this.pageSize});
341             
342         }
343         
344         if (this.pageTb && this.allowBlank && !this.disableClear) {
345             var _this = this;
346             this.pageTb.add(new Roo.Toolbar.Fill(), {
347                 cls: 'x-btn-icon x-btn-clear',
348                 text: '&#160;',
349                 handler: function()
350                 {
351                     _this.collapse();
352                     _this.clearValue();
353                     _this.onSelect(false, -1);
354                 }
355             });
356         }
357         if (this.footer) {
358             this.assetHeight += this.footer.getHeight();
359         }
360         
361
362         if(!this.tpl){
363             this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
364         }
365
366         this.view = new Roo.View(this.innerList, this.tpl, {
367             singleSelect:true, store: this.store, selectedClass: this.selectedClass
368         });
369
370         this.view.on('click', this.onViewClick, this);
371
372         this.store.on('beforeload', this.onBeforeLoad, this);
373         this.store.on('load', this.onLoad, this);
374         this.store.on('loadexception', this.collapse, this);
375
376         if(this.resizable){
377             this.resizer = new Roo.Resizable(this.list,  {
378                pinned:true, handles:'se'
379             });
380             this.resizer.on('resize', function(r, w, h){
381                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
382                 this.listWidth = w;
383                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
384                 this.restrictHeight();
385             }, this);
386             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
387         }
388         if(!this.editable){
389             this.editable = true;
390             this.setEditable(false);
391         }  
392         
393         
394         if (typeof(this.events.add.listeners) != 'undefined') {
395             
396             this.addicon = this.wrap.createChild(
397                 {tag: 'img', src: Ext.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
398        
399             this.adder.on('click', function(e) {
400                 this.fireEvent('adderclick', this, e);
401             }, this);
402         }
403         
404         
405         
406         
407     },
408
409     // private
410     initEvents : function(){
411         Roo.form.ComboBox.superclass.initEvents.call(this);
412
413         this.keyNav = new Roo.KeyNav(this.el, {
414             "up" : function(e){
415                 this.inKeyMode = true;
416                 this.selectPrev();
417             },
418
419             "down" : function(e){
420                 if(!this.isExpanded()){
421                     this.onTriggerClick();
422                 }else{
423                     this.inKeyMode = true;
424                     this.selectNext();
425                 }
426             },
427
428             "enter" : function(e){
429                 this.onViewClick();
430                 //return true;
431             },
432
433             "esc" : function(e){
434                 this.collapse();
435             },
436
437             "tab" : function(e){
438                 this.onViewClick(false);
439                 return true;
440             },
441
442             scope : this,
443
444             doRelay : function(foo, bar, hname){
445                 if(hname == 'down' || this.scope.isExpanded()){
446                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
447                 }
448                 return true;
449             },
450
451             forceKeyDown: true
452         });
453         this.queryDelay = Math.max(this.queryDelay || 10,
454                 this.mode == 'local' ? 10 : 250);
455         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
456         if(this.typeAhead){
457             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
458         }
459         if(this.editable !== false){
460             this.el.on("keyup", this.onKeyUp, this);
461         }
462         if(this.forceSelection){
463             this.on('blur', this.doForce, this);
464         }
465     },
466
467     onDestroy : function(){
468         if(this.view){
469             this.view.setStore(null);
470             this.view.el.removeAllListeners();
471             this.view.el.remove();
472             this.view.purgeListeners();
473         }
474         if(this.list){
475             this.list.destroy();
476         }
477         if(this.store){
478             this.store.un('beforeload', this.onBeforeLoad, this);
479             this.store.un('load', this.onLoad, this);
480             this.store.un('loadexception', this.collapse, this);
481         }
482         Roo.form.ComboBox.superclass.onDestroy.call(this);
483     },
484
485     // private
486     fireKey : function(e){
487         if(e.isNavKeyPress() && !this.list.isVisible()){
488             this.fireEvent("specialkey", this, e);
489         }
490     },
491
492     // private
493     onResize: function(w, h){
494         Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
495         if(this.list && this.listWidth === undefined){
496             var lw = Math.max(w, this.minListWidth);
497             this.list.setWidth(lw);
498             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
499         }
500     },
501
502     /**
503      * Allow or prevent the user from directly editing the field text.  If false is passed,
504      * the user will only be able to select from the items defined in the dropdown list.  This method
505      * is the runtime equivalent of setting the 'editable' config option at config time.
506      * @param {Boolean} value True to allow the user to directly edit the field text
507      */
508     setEditable : function(value){
509         if(value == this.editable){
510             return;
511         }
512         this.editable = value;
513         if(!value){
514             this.el.dom.setAttribute('readOnly', true);
515             this.el.on('mousedown', this.onTriggerClick,  this);
516             this.el.addClass('x-combo-noedit');
517         }else{
518             this.el.dom.setAttribute('readOnly', false);
519             this.el.un('mousedown', this.onTriggerClick,  this);
520             this.el.removeClass('x-combo-noedit');
521         }
522     },
523
524     // private
525     onBeforeLoad : function(){
526         if(!this.hasFocus){
527             return;
528         }
529         this.innerList.update(this.loadingText ?
530                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
531         this.restrictHeight();
532         this.selectedIndex = -1;
533     },
534
535     // private
536     onLoad : function(){
537         if(!this.hasFocus){
538             return;
539         }
540         if(this.store.getCount() > 0){
541             this.expand();
542             this.restrictHeight();
543             if(this.lastQuery == this.allQuery){
544                 if(this.editable){
545                     this.el.dom.select();
546                 }
547                 if(!this.selectByValue(this.value, true)){
548                     this.select(0, true);
549                 }
550             }else{
551                 this.selectNext();
552                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
553                     this.taTask.delay(this.typeAheadDelay);
554                 }
555             }
556         }else{
557             this.onEmptyResults();
558         }
559         //this.el.focus();
560     },
561
562     // private
563     onTypeAhead : function(){
564         if(this.store.getCount() > 0){
565             var r = this.store.getAt(0);
566             var newValue = r.data[this.displayField];
567             var len = newValue.length;
568             var selStart = this.getRawValue().length;
569             if(selStart != len){
570                 this.setRawValue(newValue);
571                 this.selectText(selStart, newValue.length);
572             }
573         }
574     },
575
576     // private
577     onSelect : function(record, index){
578         if(this.fireEvent('beforeselect', this, record, index) !== false){
579             this.setFromData(index > -1 ? record.data : false);
580             this.collapse();
581             this.fireEvent('select', this, record, index);
582         }
583     },
584
585     /**
586      * Returns the currently selected field value or empty string if no value is set.
587      * @return {String} value The selected value
588      */
589     getValue : function(){
590         if(this.valueField){
591             return typeof this.value != 'undefined' ? this.value : '';
592         }else{
593             return Roo.form.ComboBox.superclass.getValue.call(this);
594         }
595     },
596
597     /**
598      * Clears any text/value currently set in the field
599      */
600     clearValue : function(){
601         if(this.hiddenField){
602             this.hiddenField.value = '';
603         }
604         this.value = '';
605         this.setRawValue('');
606         this.lastSelectionText = '';
607         this.applyEmptyText();
608     },
609
610     /**
611      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
612      * will be displayed in the field.  If the value does not match the data value of an existing item,
613      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
614      * Otherwise the field will be blank (although the value will still be set).
615      * @param {String} value The value to match
616      */
617     setValue : function(v){
618         var text = v;
619         if(this.valueField){
620             var r = this.findRecord(this.valueField, v);
621             if(r){
622                 text = r.data[this.displayField];
623             }else if(this.valueNotFoundText !== undefined){
624                 text = this.valueNotFoundText;
625             }
626         }
627         this.lastSelectionText = text;
628         if(this.hiddenField){
629             this.hiddenField.value = v;
630         }
631         Roo.form.ComboBox.superclass.setValue.call(this, text);
632         this.value = v;
633     },
634     /**
635      * @property {Object} the last set data for the element
636      */
637     
638     lastData : false,
639     /**
640      * Sets the value of the field based on a object which is related to the record format for the store.
641      * @param {Object} value the value to set as. or false on reset?
642      */
643     setFromData : function(o){
644         var dv = ''; // display value
645         var vv = ''; // value value..
646         this.lastData = o;
647         if (this.displayField) {
648             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
649         } else {
650             // this is an error condition!!!
651             console.log('no value field set for '+ this.name);
652         }
653         
654         if(this.valueField){
655             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
656         }
657         if(this.hiddenField){
658             this.hiddenField.value = vv;
659             
660             this.lastSelectionText = dv;
661             Roo.form.ComboBox.superclass.setValue.call(this, dv);
662             this.value = vv;
663             return;
664         }
665         // no hidden field.. - we store the value in 'value', but still display
666         // display field!!!!
667         this.lastSelectionText = dv;
668         Roo.form.ComboBox.superclass.setValue.call(this, dv);
669         this.value = vv;
670         
671         
672     },
673     // private
674     reset : function(){
675         // overridden so that last data is reset..
676         this.setValue(this.originalValue);
677         this.clearInvalid();
678         this.lastData = false;
679     },
680     // private
681     findRecord : function(prop, value){
682         var record;
683         if(this.store.getCount() > 0){
684             this.store.each(function(r){
685                 if(r.data[prop] == value){
686                     record = r;
687                     return false;
688                 }
689             });
690         }
691         return record;
692     },
693
694     // private
695     onViewMove : function(e, t){
696         this.inKeyMode = false;
697     },
698
699     // private
700     onViewOver : function(e, t){
701         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
702             return;
703         }
704         var item = this.view.findItemFromChild(t);
705         if(item){
706             var index = this.view.indexOf(item);
707             this.select(index, false);
708         }
709     },
710
711     // private
712     onViewClick : function(doFocus){
713         var index = this.view.getSelectedIndexes()[0];
714         var r = this.store.getAt(index);
715         if(r){
716             this.onSelect(r, index);
717         }
718         if(doFocus !== false && !this.blockFocus){
719             this.el.focus();
720         }
721     },
722
723     // private
724     restrictHeight : function(){
725         this.innerList.dom.style.height = '';
726         var inner = this.innerList.dom;
727         var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
728         this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
729         this.list.beginUpdate();
730         this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
731         this.list.alignTo(this.el, this.listAlign);
732         this.list.endUpdate();
733     },
734
735     // private
736     onEmptyResults : function(){
737         this.collapse();
738     },
739
740     /**
741      * Returns true if the dropdown list is expanded, else false.
742      */
743     isExpanded : function(){
744         return this.list.isVisible();
745     },
746
747     /**
748      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
749      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
750      * @param {String} value The data value of the item to select
751      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
752      * selected item if it is not currently in view (defaults to true)
753      * @return {Boolean} True if the value matched an item in the list, else false
754      */
755     selectByValue : function(v, scrollIntoView){
756         if(v !== undefined && v !== null){
757             var r = this.findRecord(this.valueField || this.displayField, v);
758             if(r){
759                 this.select(this.store.indexOf(r), scrollIntoView);
760                 return true;
761             }
762         }
763         return false;
764     },
765
766     /**
767      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
768      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
769      * @param {Number} index The zero-based index of the list item to select
770      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
771      * selected item if it is not currently in view (defaults to true)
772      */
773     select : function(index, scrollIntoView){
774         this.selectedIndex = index;
775         this.view.select(index);
776         if(scrollIntoView !== false){
777             var el = this.view.getNode(index);
778             if(el){
779                 this.innerList.scrollChildIntoView(el, false);
780             }
781         }
782     },
783
784     // private
785     selectNext : function(){
786         var ct = this.store.getCount();
787         if(ct > 0){
788             if(this.selectedIndex == -1){
789                 this.select(0);
790             }else if(this.selectedIndex < ct-1){
791                 this.select(this.selectedIndex+1);
792             }
793         }
794     },
795
796     // private
797     selectPrev : function(){
798         var ct = this.store.getCount();
799         if(ct > 0){
800             if(this.selectedIndex == -1){
801                 this.select(0);
802             }else if(this.selectedIndex != 0){
803                 this.select(this.selectedIndex-1);
804             }
805         }
806     },
807
808     // private
809     onKeyUp : function(e){
810         if(this.editable !== false && !e.isSpecialKey()){
811             this.lastKey = e.getKey();
812             this.dqTask.delay(this.queryDelay);
813         }
814     },
815
816     // private
817     validateBlur : function(){
818         return !this.list || !this.list.isVisible();   
819     },
820
821     // private
822     initQuery : function(){
823         this.doQuery(this.getRawValue());
824     },
825
826     // private
827     doForce : function(){
828         if(this.el.dom.value.length > 0){
829             this.el.dom.value =
830                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
831             this.applyEmptyText();
832         }
833     },
834
835     /**
836      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
837      * query allowing the query action to be canceled if needed.
838      * @param {String} query The SQL query to execute
839      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
840      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
841      * saved in the current store (defaults to false)
842      */
843     doQuery : function(q, forceAll){
844         if(q === undefined || q === null){
845             q = '';
846         }
847         var qe = {
848             query: q,
849             forceAll: forceAll,
850             combo: this,
851             cancel:false
852         };
853         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
854             return false;
855         }
856         q = qe.query;
857         forceAll = qe.forceAll;
858         if(forceAll === true || (q.length >= this.minChars)){
859             if(this.lastQuery != q){
860                 this.lastQuery = q;
861                 if(this.mode == 'local'){
862                     this.selectedIndex = -1;
863                     if(forceAll){
864                         this.store.clearFilter();
865                     }else{
866                         this.store.filter(this.displayField, q);
867                     }
868                     this.onLoad();
869                 }else{
870                     this.store.baseParams[this.queryParam] = q;
871                     this.store.load({
872                         params: this.getParams(q)
873                     });
874                     this.expand();
875                 }
876             }else{
877                 this.selectedIndex = -1;
878                 this.onLoad();   
879             }
880         }
881     },
882
883     // private
884     getParams : function(q){
885         var p = {};
886         //p[this.queryParam] = q;
887         if(this.pageSize){
888             p.start = 0;
889             p.limit = this.pageSize;
890         }
891         return p;
892     },
893
894     /**
895      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
896      */
897     collapse : function(){
898         if(!this.isExpanded()){
899             return;
900         }
901         this.list.hide();
902         Roo.get(document).un('mousedown', this.collapseIf, this);
903         Roo.get(document).un('mousewheel', this.collapseIf, this);
904         this.fireEvent('collapse', this);
905     },
906
907     // private
908     collapseIf : function(e){
909         if(!e.within(this.wrap) && !e.within(this.list)){
910             this.collapse();
911         }
912     },
913
914     /**
915      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
916      */
917     expand : function(){
918         if(this.isExpanded() || !this.hasFocus){
919             return;
920         }
921         this.list.alignTo(this.el, this.listAlign);
922         this.list.show();
923         Roo.get(document).on('mousedown', this.collapseIf, this);
924         Roo.get(document).on('mousewheel', this.collapseIf, this);
925         this.fireEvent('expand', this);
926     },
927
928     // private
929     // Implements the default empty TriggerField.onTriggerClick function
930     onTriggerClick : function(){
931         if(this.disabled){
932             return;
933         }
934         if(this.isExpanded()){
935             this.collapse();
936             if (!this.blockFocus) {
937                 this.el.focus();
938             }
939             
940         }else {
941             this.hasFocus = true;
942             if(this.triggerAction == 'all') {
943                 this.doQuery(this.allQuery, true);
944             } else {
945                 this.doQuery(this.getRawValue());
946             }
947             if (!this.blockFocus) {
948                 this.el.focus();
949             }
950         }
951     }
952
953     /** 
954     * @cfg {Boolean} grow 
955     * @hide 
956     */
957     /** 
958     * @cfg {Number} growMin 
959     * @hide 
960     */
961     /** 
962     * @cfg {Number} growMax 
963     * @hide 
964     */
965     /**
966      * @hide
967      * @method autoSize
968      */
969 });