// http://www.extjs.com/forum/showthread.php?t=48601

Ext.namespace('Ext.ux.form');

Ext.ux.form.SearchCombo = function(config) {
	Ext.ux.form.SearchCombo.superclass.constructor.call(this, config);
}

Ext.extend(Ext.ux.form.SearchCombo, Ext.form.ComboBox, {

initEvents : function(){
	Ext.form.ComboBox.superclass.initEvents.call(this);
	this.keyNav = new Ext.KeyNav(this.el, {
		"up" : function(e){
			this.inKeyMode = true;
			this.selectPrev();
		},
		"down" : function(e){
			if(!this.isExpanded()){
				this.onTriggerClick();
			}else{
				this.inKeyMode = true;
				this.selectNext();
			}
		},
		"enter" : function(e){
			this.onViewClick();
			this.delayedCheck = true;
			this.unsetDelayCheck.defer(10, this);
		},
		"esc" : function(e){
			this.collapse();
		},
		"tab" : function(e){
			if(this.forceSelection) {
				this.onViewClick(false);
			} else {
				this.collapse();
			}
			return true;
		},
		scope : this,
		doRelay : function(foo, bar, hname){
			if(hname == 'down' || this.scope.isExpanded()){
			   return Ext.KeyNav.prototype.doRelay.apply(this, arguments);
			}
			return true;
		},
		forceKeyDown : true
	});
	this.queryDelay = Math.max(this.queryDelay || 10,
			this.mode == 'local' ? 10 : 250);
	this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
	if(this.typeAhead){
		this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this);
	}
	if(this.editable !== false){
		this.el.on("keyup", this.onKeyUp, this);
	}
	if(this.forceSelection){
		this.on('blur', this.doForce, this);
	}
},

onLoad : function(){
	if(!this.hasFocus){
		return;
	}
	if(this.store.getCount() > 0){
		this.expand();
		this.restrictHeight();
		if(this.lastQuery == this.allQuery){
			if(this.editable){
				this.el.dom.select();
			}
			//if(!this.selectByValue(this.value, true)){
			//	this.select(0, true);
			//}
		}else{
			//this.selectNext();
			if(this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE){
				this.taTask.delay(this.typeAheadDelay);
			}
		}
	}else{
		this.onEmptyResults();
	}
}

});

Ext.reg('search-combobox', Ext.ux.form.SearchCombo);

