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