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