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