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