roojs-ui.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     // private
606     onLoadException : function()
607     {
608         this.collapse();
609         Roo.log(this.store.reader.jsonData);
610         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
611             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
612         }
613         
614         
615     },
616     // private
617     onTypeAhead : function(){
618         if(this.store.getCount() > 0){
619             var r = this.store.getAt(0);
620             var newValue = r.data[this.displayField];
621             var len = newValue.length;
622             var selStart = this.getRawValue().length;
623             if(selStart != len){
624                 this.setRawValue(newValue);
625                 this.selectText(selStart, newValue.length);
626             }
627         }
628     },
629
630     // private
631     onSelect : function(record, index){
632         if(this.fireEvent('beforeselect', this, record, index) !== false){
633             this.setFromData(index > -1 ? record.data : false);
634             this.collapse();
635             this.fireEvent('select', this, record, index);
636         }
637     },
638
639     /**
640      * Returns the currently selected field value or empty string if no value is set.
641      * @return {String} value The selected value
642      */
643     getValue : function(){
644         if(this.valueField){
645             return typeof this.value != 'undefined' ? this.value : '';
646         }
647         return Roo.form.ComboBox.superclass.getValue.call(this);
648     },
649
650     /**
651      * Clears any text/value currently set in the field
652      */
653     clearValue : function(){
654         if(this.hiddenField){
655             this.hiddenField.value = '';
656         }
657         this.value = '';
658         this.setRawValue('');
659         this.lastSelectionText = '';
660         
661     },
662
663     /**
664      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
665      * will be displayed in the field.  If the value does not match the data value of an existing item,
666      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
667      * Otherwise the field will be blank (although the value will still be set).
668      * @param {String} value The value to match
669      */
670     setValue : function(v){
671         var text = v;
672         if(this.valueField){
673             var r = this.findRecord(this.valueField, v);
674             if(r){
675                 text = r.data[this.displayField];
676             }else if(this.valueNotFoundText !== undefined){
677                 text = this.valueNotFoundText;
678             }
679         }
680         this.lastSelectionText = text;
681         if(this.hiddenField){
682             this.hiddenField.value = v;
683         }
684         Roo.form.ComboBox.superclass.setValue.call(this, text);
685         this.value = v;
686     },
687     /**
688      * @property {Object} the last set data for the element
689      */
690     
691     lastData : false,
692     /**
693      * Sets the value of the field based on a object which is related to the record format for the store.
694      * @param {Object} value the value to set as. or false on reset?
695      */
696     setFromData : function(o){
697         var dv = ''; // display value
698         var vv = ''; // value value..
699         this.lastData = o;
700         if (this.displayField) {
701             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
702         } else {
703             // this is an error condition!!!
704             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
705         }
706         
707         if(this.valueField){
708             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
709         }
710         if(this.hiddenField){
711             this.hiddenField.value = vv;
712             
713             this.lastSelectionText = dv;
714             Roo.form.ComboBox.superclass.setValue.call(this, dv);
715             this.value = vv;
716             return;
717         }
718         // no hidden field.. - we store the value in 'value', but still display
719         // display field!!!!
720         this.lastSelectionText = dv;
721         Roo.form.ComboBox.superclass.setValue.call(this, dv);
722         this.value = vv;
723         
724         
725     },
726     // private
727     reset : function(){
728         // overridden so that last data is reset..
729         this.setValue(this.resetValue);
730         this.originalValue = this.getValue();
731         this.clearInvalid();
732         this.lastData = false;
733         if (this.view) {
734             this.view.clearSelections();
735         }
736     },
737     // private
738     findRecord : function(prop, value){
739         var record;
740         if(this.store.getCount() > 0){
741             this.store.each(function(r){
742                 if(r.data[prop] == value){
743                     record = r;
744                     return false;
745                 }
746                 return true;
747             });
748         }
749         return record;
750     },
751     
752     getName: function()
753     {
754         // returns hidden if it's set..
755         if (!this.rendered) {return ''};
756         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
757         
758     },
759     // private
760     onViewMove : function(e, t){
761         this.inKeyMode = false;
762     },
763
764     // private
765     onViewOver : function(e, t){
766         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
767             return;
768         }
769         var item = this.view.findItemFromChild(t);
770         if(item){
771             var index = this.view.indexOf(item);
772             this.select(index, false);
773         }
774     },
775
776     // private
777     onViewClick : function(doFocus)
778     {
779         var index = this.view.getSelectedIndexes()[0];
780         var r = this.store.getAt(index);
781         if(r){
782             this.onSelect(r, index);
783         }
784         if(doFocus !== false && !this.blockFocus){
785             this.el.focus();
786         }
787     },
788
789     // private
790     restrictHeight : function(){
791         this.innerList.dom.style.height = '';
792         var inner = this.innerList.dom;
793         var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
794         this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
795         this.list.beginUpdate();
796         this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
797         this.list.alignTo(this.el, this.listAlign);
798         this.list.endUpdate();
799     },
800
801     // private
802     onEmptyResults : function(){
803         this.collapse();
804     },
805
806     /**
807      * Returns true if the dropdown list is expanded, else false.
808      */
809     isExpanded : function(){
810         return this.list.isVisible();
811     },
812
813     /**
814      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
815      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
816      * @param {String} value The data value of the item to select
817      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
818      * selected item if it is not currently in view (defaults to true)
819      * @return {Boolean} True if the value matched an item in the list, else false
820      */
821     selectByValue : function(v, scrollIntoView){
822         if(v !== undefined && v !== null){
823             var r = this.findRecord(this.valueField || this.displayField, v);
824             if(r){
825                 this.select(this.store.indexOf(r), scrollIntoView);
826                 return true;
827             }
828         }
829         return false;
830     },
831
832     /**
833      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
834      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
835      * @param {Number} index The zero-based index of the list item to select
836      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
837      * selected item if it is not currently in view (defaults to true)
838      */
839     select : function(index, scrollIntoView){
840         this.selectedIndex = index;
841         this.view.select(index);
842         if(scrollIntoView !== false){
843             var el = this.view.getNode(index);
844             if(el){
845                 this.innerList.scrollChildIntoView(el, false);
846             }
847         }
848     },
849
850     // private
851     selectNext : function(){
852         var ct = this.store.getCount();
853         if(ct > 0){
854             if(this.selectedIndex == -1){
855                 this.select(0);
856             }else if(this.selectedIndex < ct-1){
857                 this.select(this.selectedIndex+1);
858             }
859         }
860     },
861
862     // private
863     selectPrev : function(){
864         var ct = this.store.getCount();
865         if(ct > 0){
866             if(this.selectedIndex == -1){
867                 this.select(0);
868             }else if(this.selectedIndex != 0){
869                 this.select(this.selectedIndex-1);
870             }
871         }
872     },
873
874     // private
875     onKeyUp : function(e){
876         if(this.editable !== false && !e.isSpecialKey()){
877             this.lastKey = e.getKey();
878             this.dqTask.delay(this.queryDelay);
879         }
880     },
881
882     // private
883     validateBlur : function(){
884         return !this.list || !this.list.isVisible();   
885     },
886
887     // private
888     initQuery : function(){
889         this.doQuery(this.getRawValue());
890     },
891
892     // private
893     doForce : function(){
894         if(this.el.dom.value.length > 0){
895             this.el.dom.value =
896                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
897              
898         }
899     },
900
901     /**
902      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
903      * query allowing the query action to be canceled if needed.
904      * @param {String} query The SQL query to execute
905      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
906      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
907      * saved in the current store (defaults to false)
908      */
909     doQuery : function(q, forceAll){
910         if(q === undefined || q === null){
911             q = '';
912         }
913         var qe = {
914             query: q,
915             forceAll: forceAll,
916             combo: this,
917             cancel:false
918         };
919         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
920             return false;
921         }
922         q = qe.query;
923         forceAll = qe.forceAll;
924         if(forceAll === true || (q.length >= this.minChars)){
925             if(this.lastQuery != q || this.alwaysQuery){
926                 this.lastQuery = q;
927                 if(this.mode == 'local'){
928                     this.selectedIndex = -1;
929                     if(forceAll){
930                         this.store.clearFilter();
931                     }else{
932                         this.store.filter(this.displayField, q);
933                     }
934                     this.onLoad();
935                 }else{
936                     this.store.baseParams[this.queryParam] = q;
937                     this.store.load({
938                         params: this.getParams(q)
939                     });
940                     this.expand();
941                 }
942             }else{
943                 this.selectedIndex = -1;
944                 this.onLoad();   
945             }
946         }
947     },
948
949     // private
950     getParams : function(q){
951         var p = {};
952         //p[this.queryParam] = q;
953         if(this.pageSize){
954             p.start = 0;
955             p.limit = this.pageSize;
956         }
957         return p;
958     },
959
960     /**
961      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
962      */
963     collapse : function(){
964         if(!this.isExpanded()){
965             return;
966         }
967         this.list.hide();
968         Roo.get(document).un('mousedown', this.collapseIf, this);
969         Roo.get(document).un('mousewheel', this.collapseIf, this);
970         if (!this.editable) {
971             Roo.get(document).un('keydown', this.listKeyPress, this);
972         }
973         this.fireEvent('collapse', this);
974     },
975
976     // private
977     collapseIf : function(e){
978         if(!e.within(this.wrap) && !e.within(this.list)){
979             this.collapse();
980         }
981     },
982
983     /**
984      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
985      */
986     expand : function(){
987         if(this.isExpanded() || !this.hasFocus){
988             return;
989         }
990         this.list.alignTo(this.el, this.listAlign);
991         this.list.show();
992         Roo.get(document).on('mousedown', this.collapseIf, this);
993         Roo.get(document).on('mousewheel', this.collapseIf, this);
994         if (!this.editable) {
995             Roo.get(document).on('keydown', this.listKeyPress, this);
996         }
997         
998         this.fireEvent('expand', this);
999     },
1000
1001     // private
1002     // Implements the default empty TriggerField.onTriggerClick function
1003     onTriggerClick : function(){
1004         if(this.disabled){
1005             return;
1006         }
1007         if(this.isExpanded()){
1008             this.collapse();
1009             if (!this.blockFocus) {
1010                 this.el.focus();
1011             }
1012             
1013         }else {
1014             this.hasFocus = true;
1015             if(this.triggerAction == 'all') {
1016                 this.doQuery(this.allQuery, true);
1017             } else {
1018                 this.doQuery(this.getRawValue());
1019             }
1020             if (!this.blockFocus) {
1021                 this.el.focus();
1022             }
1023         }
1024     },
1025     listKeyPress : function(e)
1026     {
1027         //Roo.log('listkeypress');
1028         // scroll to first matching element based on key pres..
1029         if (e.isSpecialKey()) {
1030             return false;
1031         }
1032         var k = String.fromCharCode(e.getKey()).toUpperCase();
1033         //Roo.log(k);
1034         var match  = false;
1035         var csel = this.view.getSelectedNodes();
1036         var cselitem = false;
1037         if (csel.length) {
1038             var ix = this.view.indexOf(csel[0]);
1039             cselitem  = this.store.getAt(ix);
1040             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
1041                 cselitem = false;
1042             }
1043             
1044         }
1045         
1046         this.store.each(function(v) { 
1047             if (cselitem) {
1048                 // start at existing selection.
1049                 if (cselitem.id == v.id) {
1050                     cselitem = false;
1051                 }
1052                 return;
1053             }
1054                 
1055             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
1056                 match = this.store.indexOf(v);
1057                 return false;
1058             }
1059         }, this);
1060         
1061         if (match === false) {
1062             return true; // no more action?
1063         }
1064         // scroll to?
1065         this.view.select(match);
1066         var sn = Roo.get(this.view.getSelectedNodes()[0]);
1067         sn.scrollIntoView(sn.dom.parentNode, false);
1068     } 
1069
1070     /** 
1071     * @cfg {Boolean} grow 
1072     * @hide 
1073     */
1074     /** 
1075     * @cfg {Number} growMin 
1076     * @hide 
1077     */
1078     /** 
1079     * @cfg {Number} growMax 
1080     * @hide 
1081     */
1082     /**
1083      * @hide
1084      * @method autoSize
1085      */
1086 });