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