/*
 * js library needed:
 * jQuery
 */
Ext.BLANK_IMAGE_URL = "/javascript/extjs/resources/images/default/s.gif";

/**
 * class SuggestComBox
 * 1. When user input words, this combox will get the words user type and show suggest;
 * 2. it total number returns, the last line is total number.
 * config:
 * totalTpl	{string/Template} 	whether show the total number of the candidates keywords
 * phrase	{boolean}			if it is true, it will always
 * keypress {function}			when cursor in the input, this function will execute after user press any key 
 */
Ext.form.SuggestComboBox = function(config) {

	Ext.form.SuggestComboBox.superclass.constructor.call(this, config);
	this.tpl = new Ext.Template('<div class="suggest-item">{' + this.displayField + '}</div>');
	if (config.keypress) {
		this.keypress = config.keypress;
	}
	config.onSelect = function(record){ // override default onSelect to do redirect
		if (!this.phrase) {
			var v = this.el.getValue();
			var b = this._getWordBoundary(this.el);
			$(this.el.dom).val(v.substring(0, b.start) + record.data.k + v.substring(b.end));
		}
	}
};

Ext.extend(Ext.form.SuggestComboBox, Ext.form.ComboBox, {
	_getWordBoundary : function(el) {
		var v = el.getValue();
		var dom = el.dom;
		var s = dom.selectionStart;
		var e = dom.selectionEnd;
		if (s == e) {
			if (s > 0 && s <= v.length && v[s-1] != ' ') { //cursor in a word
			    while (s > 0 && v[s-1] != ' ') s--;
			    while (e < v.length && v[e] != ' ') e ++;
			}
		}
		return {start: s, end: e};
    },
	getRawValue : function() {
		if (!this.phrase) {
			var v = this.el.getValue();
			var b = this._getWordBoundary(this.el);
			return v.substring(b.start, b.end);
		} else {
			return Ext.form.SuggestComboBox.superclass.getRawValue.call(this);
		}
    },
    expand : function() {
	    Ext.form.SuggestComboBox.superclass.expand.call(this);
	    // add total items string
	    if (this.view.el.dom && this.store.totalLength) {
	    	if (this.showTotal) {
	    		if (!this.totalTpl) {
					this.totalTpl = new Ext.Template('<div class="total-item">{strTotal}</div>');
				}
	    		var strTotal = '<b>' + this.store.totalLength + '</b> ';
	    		if (this.store.totalLength < 2) {
	    			strTotal += 'Item ...';
	    		} else {
	    			strTotal += 'Items ...';
	    		}
	    		this.totalTpl.append(this.view.el.dom, {strTotal: strTotal});
		    }
	    }
	    // add events
	    $("div.suggest-item", this.view.el.dom).each(function(i) {
	    	$(this).mouseout(function() {
	    		$(this).removeClass('suggest-item-mouseover');
	    	});
	    	$(this).mouseover(function() {
	    		$(this).addClass('suggest-item-mouseover');
	    	});
	    });
	    $(this.el.dom).keyup(this.keypress);
    },
    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();
        }
    },
    initEvents : function(){
        Ext.form.SuggestComboBox.superclass.initEvents.call(this);

		var setSuggestInput = function() {
			var item = this.store.data.items[this.selectedIndex];
			if (item && item.data[this.displayField]) {
				$(this.el.dom).val(item.data[this.displayField]);
			}
		}
        this.keyNav = new Ext.KeyNav(this.el, {
            "up" 	: setSuggestInput,
            "down" 	: setSuggestInput,
            "enter" : function(e) {
            },
            scope : this
        });
    },
    onViewClick : function(doFocus){
		Ext.form.SuggestComboBox.superclass.onViewClick.call(this);
		// dont stuck the 'enter' event
		this.form.submit();
    }
});