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     addicon : false,
296     editicon: false,
297     
298     
299     // private
300     onRender : function(ct, position){
301         Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
302         if(this.hiddenName){
303             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
304                     'before', true);
305             this.hiddenField.value =
306                 this.hiddenValue !== undefined ? this.hiddenValue :
307                 this.value !== undefined ? this.value : '';
308
309             // prevent input submission
310             this.el.dom.removeAttribute('name');
311         }
312         if(Roo.isGecko){
313             this.el.dom.setAttribute('autocomplete', 'off');
314         }
315
316         var cls = 'x-combo-list';
317
318         this.list = new Roo.Layer({
319             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
320         });
321
322         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
323         this.list.setWidth(lw);
324         this.list.swallowEvent('mousewheel');
325         this.assetHeight = 0;
326
327         if(this.title){
328             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
329             this.assetHeight += this.header.getHeight();
330         }
331
332         this.innerList = this.list.createChild({cls:cls+'-inner'});
333         this.innerList.on('mouseover', this.onViewOver, this);
334         this.innerList.on('mousemove', this.onViewMove, this);
335         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
336         
337         if(this.allowBlank && !this.pageSize && !this.disableClear){
338             this.footer = this.list.createChild({cls:cls+'-ft'});
339             this.pageTb = new Roo.Toolbar(this.footer);
340            
341         }
342         if(this.pageSize){
343             this.footer = this.list.createChild({cls:cls+'-ft'});
344             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
345                     {pageSize: this.pageSize});
346             
347         }
348         
349         if (this.pageTb && this.allowBlank && !this.disableClear) {
350             var _this = this;
351             this.pageTb.add(new Roo.Toolbar.Fill(), {
352                 cls: 'x-btn-icon x-btn-clear',
353                 text: '&#160;',
354                 handler: function()
355                 {
356                     _this.collapse();
357                     _this.clearValue();
358                     _this.onSelect(false, -1);
359                 }
360             });
361         }
362         if (this.footer) {
363             this.assetHeight += this.footer.getHeight();
364         }
365         
366
367         if(!this.tpl){
368             this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
369         }
370
371         this.view = new Roo.View(this.innerList, this.tpl, {
372             singleSelect:true, store: this.store, selectedClass: this.selectedClass
373         });
374
375         this.view.on('click', this.onViewClick, this);
376
377         this.store.on('beforeload', this.onBeforeLoad, this);
378         this.store.on('load', this.onLoad, this);
379         this.store.on('loadexception', this.collapse, this);
380
381         if(this.resizable){
382             this.resizer = new Roo.Resizable(this.list,  {
383                pinned:true, handles:'se'
384             });
385             this.resizer.on('resize', function(r, w, h){
386                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
387                 this.listWidth = w;
388                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
389                 this.restrictHeight();
390             }, this);
391             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
392         }
393         if(!this.editable){
394             this.editable = true;
395             this.setEditable(false);
396         }  
397         
398         
399         if (typeof(this.events.add.listeners) != 'undefined') {
400             
401             this.addicon = this.wrap.createChild(
402                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
403        
404             this.addicon.on('click', function(e) {
405                 this.fireEvent('add', this);
406             }, this);
407         }
408         if (typeof(this.events.edit.listeners) != 'undefined') {
409             
410             this.editicon = this.wrap.createChild(
411                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
412             if (this.addicon) {
413                 this.editicon.setStyle('margin-left', '40px');
414             }
415             this.editicon.on('click', function(e) {
416                 if (this.lastData) {
417                     // should we fire if nothing is selected..
418                     this.fireEvent('edit', this, this.lastData );
419                 }
420             }, this);
421         }
422         
423         
424         
425     },
426
427     // private
428     initEvents : function(){
429         Roo.form.ComboBox.superclass.initEvents.call(this);
430
431         this.keyNav = new Roo.KeyNav(this.el, {
432             "up" : function(e){
433                 this.inKeyMode = true;
434                 this.selectPrev();
435             },
436
437             "down" : function(e){
438                 if(!this.isExpanded()){
439                     this.onTriggerClick();
440                 }else{
441                     this.inKeyMode = true;
442                     this.selectNext();
443                 }
444             },
445
446             "enter" : function(e){
447                 this.onViewClick();
448                 //return true;
449             },
450
451             "esc" : function(e){
452                 this.collapse();
453             },
454
455             "tab" : function(e){
456                 this.onViewClick(false);
457                 return true;
458             },
459
460             scope : this,
461
462             doRelay : function(foo, bar, hname){
463                 if(hname == 'down' || this.scope.isExpanded()){
464                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
465                 }
466                 return true;
467             },
468
469             forceKeyDown: true
470         });
471         this.queryDelay = Math.max(this.queryDelay || 10,
472                 this.mode == 'local' ? 10 : 250);
473         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
474         if(this.typeAhead){
475             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
476         }
477         if(this.editable !== false){
478             this.el.on("keyup", this.onKeyUp, this);
479         }
480         if(this.forceSelection){
481             this.on('blur', this.doForce, this);
482         }
483     },
484
485     onDestroy : function(){
486         if(this.view){
487             this.view.setStore(null);
488             this.view.el.removeAllListeners();
489             this.view.el.remove();
490             this.view.purgeListeners();
491         }
492         if(this.list){
493             this.list.destroy();
494         }
495         if(this.store){
496             this.store.un('beforeload', this.onBeforeLoad, this);
497             this.store.un('load', this.onLoad, this);
498             this.store.un('loadexception', this.collapse, this);
499         }
500         Roo.form.ComboBox.superclass.onDestroy.call(this);
501     },
502
503     // private
504     fireKey : function(e){
505         if(e.isNavKeyPress() && !this.list.isVisible()){
506             this.fireEvent("specialkey", this, e);
507         }
508     },
509
510     // private
511     onResize: function(w, h){
512         Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
513         if(this.list && this.listWidth === undefined){
514             var lw = Math.max(w, this.minListWidth);
515             this.list.setWidth(lw);
516             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
517         }
518         
519         if(typeof w == 'number'){
520             var tw = this.trigger.getWidth();
521             tw += this.addicon ? this.addicon.getWidth() : 0;
522             tw += this.editicon ? this.editicon.getWidth() : 0;
523             this.el.setWidth(
524                 this.adjustWidth('input', 
525                     w - tw
526                 )
527             );
528             
529             this.trigger.setX(w-tw);
530         }
531     
532         
533     },
534
535     /**
536      * Allow or prevent the user from directly editing the field text.  If false is passed,
537      * the user will only be able to select from the items defined in the dropdown list.  This method
538      * is the runtime equivalent of setting the 'editable' config option at config time.
539      * @param {Boolean} value True to allow the user to directly edit the field text
540      */
541     setEditable : function(value){
542         if(value == this.editable){
543             return;
544         }
545         this.editable = value;
546         if(!value){
547             this.el.dom.setAttribute('readOnly', true);
548             this.el.on('mousedown', this.onTriggerClick,  this);
549             this.el.addClass('x-combo-noedit');
550         }else{
551             this.el.dom.setAttribute('readOnly', false);
552             this.el.un('mousedown', this.onTriggerClick,  this);
553             this.el.removeClass('x-combo-noedit');
554         }
555     },
556
557     // private
558     onBeforeLoad : function(){
559         if(!this.hasFocus){
560             return;
561         }
562         this.innerList.update(this.loadingText ?
563                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
564         this.restrictHeight();
565         this.selectedIndex = -1;
566     },
567
568     // private
569     onLoad : function(){
570         if(!this.hasFocus){
571             return;
572         }
573         if(this.store.getCount() > 0){
574             this.expand();
575             this.restrictHeight();
576             if(this.lastQuery == this.allQuery){
577                 if(this.editable){
578                     this.el.dom.select();
579                 }
580                 if(!this.selectByValue(this.value, true)){
581                     this.select(0, true);
582                 }
583             }else{
584                 this.selectNext();
585                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
586                     this.taTask.delay(this.typeAheadDelay);
587                 }
588             }
589         }else{
590             this.onEmptyResults();
591         }
592         //this.el.focus();
593     },
594
595     // private
596     onTypeAhead : function(){
597         if(this.store.getCount() > 0){
598             var r = this.store.getAt(0);
599             var newValue = r.data[this.displayField];
600             var len = newValue.length;
601             var selStart = this.getRawValue().length;
602             if(selStart != len){
603                 this.setRawValue(newValue);
604                 this.selectText(selStart, newValue.length);
605             }
606         }
607     },
608
609     // private
610     onSelect : function(record, index){
611         if(this.fireEvent('beforeselect', this, record, index) !== false){
612             this.setFromData(index > -1 ? record.data : false);
613             this.collapse();
614             this.fireEvent('select', this, record, index);
615         }
616     },
617
618     /**
619      * Returns the currently selected field value or empty string if no value is set.
620      * @return {String} value The selected value
621      */
622     getValue : function(){
623         if(this.valueField){
624             return typeof this.value != 'undefined' ? this.value : '';
625         }else{
626             return Roo.form.ComboBox.superclass.getValue.call(this);
627         }
628     },
629
630     /**
631      * Clears any text/value currently set in the field
632      */
633     clearValue : function(){
634         if(this.hiddenField){
635             this.hiddenField.value = '';
636         }
637         this.value = '';
638         this.setRawValue('');
639         this.lastSelectionText = '';
640         this.applyEmptyText();
641     },
642
643     /**
644      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
645      * will be displayed in the field.  If the value does not match the data value of an existing item,
646      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
647      * Otherwise the field will be blank (although the value will still be set).
648      * @param {String} value The value to match
649      */
650     setValue : function(v){
651         var text = v;
652         if(this.valueField){
653             var r = this.findRecord(this.valueField, v);
654             if(r){
655                 text = r.data[this.displayField];
656             }else if(this.valueNotFoundText !== undefined){
657                 text = this.valueNotFoundText;
658             }
659         }
660         this.lastSelectionText = text;
661         if(this.hiddenField){
662             this.hiddenField.value = v;
663         }
664         Roo.form.ComboBox.superclass.setValue.call(this, text);
665         this.value = v;
666     },
667     /**
668      * @property {Object} the last set data for the element
669      */
670     
671     lastData : false,
672     /**
673      * Sets the value of the field based on a object which is related to the record format for the store.
674      * @param {Object} value the value to set as. or false on reset?
675      */
676     setFromData : function(o){
677         var dv = ''; // display value
678         var vv = ''; // value value..
679         this.lastData = o;
680         if (this.displayField) {
681             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
682         } else {
683             // this is an error condition!!!
684             console.log('no value field set for '+ this.name);
685         }
686         
687         if(this.valueField){
688             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
689         }
690         if(this.hiddenField){
691             this.hiddenField.value = vv;
692             
693             this.lastSelectionText = dv;
694             Roo.form.ComboBox.superclass.setValue.call(this, dv);
695             this.value = vv;
696             return;
697         }
698         // no hidden field.. - we store the value in 'value', but still display
699         // display field!!!!
700         this.lastSelectionText = dv;
701         Roo.form.ComboBox.superclass.setValue.call(this, dv);
702         this.value = vv;
703         
704         
705     },
706     // private
707     reset : function(){
708         // overridden so that last data is reset..
709         this.setValue(this.originalValue);
710         this.clearInvalid();
711         this.lastData = false;
712     },
713     // private
714     findRecord : function(prop, value){
715         var record;
716         if(this.store.getCount() > 0){
717             this.store.each(function(r){
718                 if(r.data[prop] == value){
719                     record = r;
720                     return false;
721                 }
722             });
723         }
724         return record;
725     },
726
727     // private
728     onViewMove : function(e, t){
729         this.inKeyMode = false;
730     },
731
732     // private
733     onViewOver : function(e, t){
734         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
735             return;
736         }
737         var item = this.view.findItemFromChild(t);
738         if(item){
739             var index = this.view.indexOf(item);
740             this.select(index, false);
741         }
742     },
743
744     // private
745     onViewClick : function(doFocus){
746         var index = this.view.getSelectedIndexes()[0];
747         var r = this.store.getAt(index);
748         if(r){
749             this.onSelect(r, index);
750         }
751         if(doFocus !== false && !this.blockFocus){
752             this.el.focus();
753         }
754     },
755
756     // private
757     restrictHeight : function(){
758         this.innerList.dom.style.height = '';
759         var inner = this.innerList.dom;
760         var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
761         this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
762         this.list.beginUpdate();
763         this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
764         this.list.alignTo(this.el, this.listAlign);
765         this.list.endUpdate();
766     },
767
768     // private
769     onEmptyResults : function(){
770         this.collapse();
771     },
772
773     /**
774      * Returns true if the dropdown list is expanded, else false.
775      */
776     isExpanded : function(){
777         return this.list.isVisible();
778     },
779
780     /**
781      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
782      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
783      * @param {String} value The data value of the item to select
784      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
785      * selected item if it is not currently in view (defaults to true)
786      * @return {Boolean} True if the value matched an item in the list, else false
787      */
788     selectByValue : function(v, scrollIntoView){
789         if(v !== undefined && v !== null){
790             var r = this.findRecord(this.valueField || this.displayField, v);
791             if(r){
792                 this.select(this.store.indexOf(r), scrollIntoView);
793                 return true;
794             }
795         }
796         return false;
797     },
798
799     /**
800      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
801      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
802      * @param {Number} index The zero-based index of the list item to select
803      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
804      * selected item if it is not currently in view (defaults to true)
805      */
806     select : function(index, scrollIntoView){
807         this.selectedIndex = index;
808         this.view.select(index);
809         if(scrollIntoView !== false){
810             var el = this.view.getNode(index);
811             if(el){
812                 this.innerList.scrollChildIntoView(el, false);
813             }
814         }
815     },
816
817     // private
818     selectNext : function(){
819         var ct = this.store.getCount();
820         if(ct > 0){
821             if(this.selectedIndex == -1){
822                 this.select(0);
823             }else if(this.selectedIndex < ct-1){
824                 this.select(this.selectedIndex+1);
825             }
826         }
827     },
828
829     // private
830     selectPrev : function(){
831         var ct = this.store.getCount();
832         if(ct > 0){
833             if(this.selectedIndex == -1){
834                 this.select(0);
835             }else if(this.selectedIndex != 0){
836                 this.select(this.selectedIndex-1);
837             }
838         }
839     },
840
841     // private
842     onKeyUp : function(e){
843         if(this.editable !== false && !e.isSpecialKey()){
844             this.lastKey = e.getKey();
845             this.dqTask.delay(this.queryDelay);
846         }
847     },
848
849     // private
850     validateBlur : function(){
851         return !this.list || !this.list.isVisible();   
852     },
853
854     // private
855     initQuery : function(){
856         this.doQuery(this.getRawValue());
857     },
858
859     // private
860     doForce : function(){
861         if(this.el.dom.value.length > 0){
862             this.el.dom.value =
863                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
864             this.applyEmptyText();
865         }
866     },
867
868     /**
869      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
870      * query allowing the query action to be canceled if needed.
871      * @param {String} query The SQL query to execute
872      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
873      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
874      * saved in the current store (defaults to false)
875      */
876     doQuery : function(q, forceAll){
877         if(q === undefined || q === null){
878             q = '';
879         }
880         var qe = {
881             query: q,
882             forceAll: forceAll,
883             combo: this,
884             cancel:false
885         };
886         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
887             return false;
888         }
889         q = qe.query;
890         forceAll = qe.forceAll;
891         if(forceAll === true || (q.length >= this.minChars)){
892             if(this.lastQuery != q){
893                 this.lastQuery = q;
894                 if(this.mode == 'local'){
895                     this.selectedIndex = -1;
896                     if(forceAll){
897                         this.store.clearFilter();
898                     }else{
899                         this.store.filter(this.displayField, q);
900                     }
901                     this.onLoad();
902                 }else{
903                     this.store.baseParams[this.queryParam] = q;
904                     this.store.load({
905                         params: this.getParams(q)
906                     });
907                     this.expand();
908                 }
909             }else{
910                 this.selectedIndex = -1;
911                 this.onLoad();   
912             }
913         }
914     },
915
916     // private
917     getParams : function(q){
918         var p = {};
919         //p[this.queryParam] = q;
920         if(this.pageSize){
921             p.start = 0;
922             p.limit = this.pageSize;
923         }
924         return p;
925     },
926
927     /**
928      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
929      */
930     collapse : function(){
931         if(!this.isExpanded()){
932             return;
933         }
934         this.list.hide();
935         Roo.get(document).un('mousedown', this.collapseIf, this);
936         Roo.get(document).un('mousewheel', this.collapseIf, this);
937         this.fireEvent('collapse', this);
938     },
939
940     // private
941     collapseIf : function(e){
942         if(!e.within(this.wrap) && !e.within(this.list)){
943             this.collapse();
944         }
945     },
946
947     /**
948      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
949      */
950     expand : function(){
951         if(this.isExpanded() || !this.hasFocus){
952             return;
953         }
954         this.list.alignTo(this.el, this.listAlign);
955         this.list.show();
956         Roo.get(document).on('mousedown', this.collapseIf, this);
957         Roo.get(document).on('mousewheel', this.collapseIf, this);
958         this.fireEvent('expand', this);
959     },
960
961     // private
962     // Implements the default empty TriggerField.onTriggerClick function
963     onTriggerClick : function(){
964         if(this.disabled){
965             return;
966         }
967         if(this.isExpanded()){
968             this.collapse();
969             if (!this.blockFocus) {
970                 this.el.focus();
971             }
972             
973         }else {
974             this.hasFocus = true;
975             if(this.triggerAction == 'all') {
976                 this.doQuery(this.allQuery, true);
977             } else {
978                 this.doQuery(this.getRawValue());
979             }
980             if (!this.blockFocus) {
981                 this.el.focus();
982             }
983         }
984     }
985
986     /** 
987     * @cfg {Boolean} grow 
988     * @hide 
989     */
990     /** 
991     * @cfg {Number} growMin 
992     * @hide 
993     */
994     /** 
995     * @cfg {Number} growMax 
996     * @hide 
997     */
998     /**
999      * @hide
1000      * @method autoSize
1001      */
1002 });