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