
/**
 * 自动建议控件
 * @class
 * @scope public
 */
function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, 
							oQueryType,
                            oProvider /*:SuggestionProvider*/) {
    
    /**
     * 选中结果.
     * @scope private
     */   
    this.cur /*:int*/ = -1;

    /**
     * 下拉列表.
     * @scope private
     */
    this.layer = null;
    
    /**
     * 
     * @scope private.
     */
    this.provider /*:SuggestionProvider*/ = oProvider;
    
    /**
     * 输入框文本.
     * @scope private
     */
    this.textbox /*:HTMLInputElement*/ = oTextbox;
    /**
     * 查询类型
     */
    this.queryType = oQueryType;
    
    /**
     * 时间id.
     * @scope private
     */
    this.timeoutId /*:int*/ = null;

    /**
     * The text that the user typed.
     * @scope private
     */
    this.userText /*:String*/ = oTextbox.value;
    
    //初始化控件
    this.init();
    
}

/**
 * 自动建议方法
 * @scope private
 * @param aSuggestions json数据.
 * @param bTypeAhead 是否文本输入框填入第一条建议.
 */
AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/,
                                                     bTypeAhead /*:boolean*/) {
    
    this.cur = -1;
    
    //判断是否有建议列表
    if (aSuggestions.length > 0) {
        if (bTypeAhead) {
           //this.typeAhead(aSuggestions[0].infoName);
        }
        this.showSuggestions(aSuggestions);
    } else {
        this.hideSuggestions();
    }
};

/**
 * 创建下拉列表
 * @scope private
 */
AutoSuggestControl.prototype.createDropDown = function () {


    //下拉列表框div
    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    this.layer.style.width = this.textbox.offsetWidth;
    document.body.appendChild(this.layer);    
    
    var oThis = this;
//    this.layer.onmousedown = 
//    this.layer.onmouseup = 
//    this.layer.onmouseover = function (oEvent) {
//        oEvent = oEvent || window.event;
//        oTarget = oEvent.target || oEvent.srcElement;
//
//        if (oEvent.type == "mousedown") {
//        	//把鼠标选择的建议的值当做关键字
//            oThis.textbox.value = oTarget.name;
//            oThis.hideSuggestions();
//        } else if (oEvent.type == "mouseover") {
//        	//高亮建议
//            oThis.highlightSuggestion(oTarget.parentNode.parentNode.parentNode);
//        } else {
//            oThis.textbox.focus();
//        }
//    };
    
};

/**
 * 获取文本框左坐标.
 * @scope private
 * @return 像素值.
 */
AutoSuggestControl.prototype.getLeft = function () /*:int*/ {

    var oNode = this.textbox;
    var iLeft = 0;
    
    while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;        
    }
    
    return iLeft;
};

/**
 * 获取文本框顶坐标.
 * @scope private
 * @return 像素值.
 */
AutoSuggestControl.prototype.getTop = function () /*:int*/ {

    var oNode = this.textbox;
    var iTop = 0;
    
    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    
    return iTop;
};


AutoSuggestControl.prototype.goToSuggestion = function (iDiff /*:int*/) {
    var cSuggestionNodes = this.layer.childNodes;
    
    if (cSuggestionNodes.length > 0) {
        var oNode = null;
    
        if (iDiff > 0) {
            if (this.cur < cSuggestionNodes.length-1) {
                oNode = cSuggestionNodes[++this.cur];
            }        
        } else {
            if (this.cur > 0) {
                oNode = cSuggestionNodes[--this.cur];
            }    
        }
        
        if (oNode) {
            this.highlightSuggestion(oNode);
            //节点名当做关键字;
            this.textbox.value = oNode.name;
        }
    }
};

/**
 * 键盘 KeyDown 事件
 * @scope private
 * @param .
 */
AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {

    switch(oEvent.keyCode) {
        case 38: //上
            this.goToSuggestion(-1);
            break;
        case 40: //下 
            this.goToSuggestion(1);
            break;
        case 27: //esc
            this.textbox.value = this.userText;
            this.selectRange(this.userText.length, 0);
        case 13: //回车键
        	//根据查询类型进行查询
        	if(this.queryType=="trs"){        		
        		actionValue();
        	}else if(this.queryType == "lifeQuery"){
        		head_actionValue();
        	}
            this.hideSuggestions();
            oEvent.returnValue = false;
            if (oEvent.preventDefault) {
                oEvent.preventDefault();
            }
            break;
    }

};

/**
 * 键盘 keyup 事件.
 * @scope private
 * @param 
 */
AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {

    var iKeyCode = oEvent.keyCode;
    var oThis = this;
    
    //获取选中的文本的值
    this.userText = this.textbox.value;
    
    clearTimeout(this.timeoutId);

    //backspace (8) and delete (46), 
    if (iKeyCode == 8 || iKeyCode == 46) {
        
        this.timeoutId = setTimeout( function () {
            oThis.provider.requestSuggestions(oThis, false);
        }, 250);
        
    //忽略的键盘事件
    } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
        //ignore
    } else {
        //文本框提示
        this.timeoutId = setTimeout( function () {
            oThis.provider.requestSuggestions(oThis, true);
        }, 250);
    }
};

/**
 * 隐藏下拉列表.
 * @scope private
 */
AutoSuggestControl.prototype.hideSuggestions = function () {
    this.layer.style.visibility = "hidden";
};

/**
 * 高亮选中的列表值.
 * @scope private
 * @param .
 */
AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {
    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i];
        if (oNode == oSuggestionNode) {
            oNode.className = "current";
        } else if (oNode.className == "current") {
            oNode.className = "";
        }
    }
};
/**
 * 高亮选中的值，鼠标事件用
 * @param idx
 * @return
 */
AutoSuggestControl.prototype.highlightSuggestionByIdx = function(idx){
	for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i];
        if (i == idx) {
            oNode.className = "current";
        } else if (oNode.className == "current") {
            oNode.className = "";
        }
    }
};
/**
 * 根据索引查询，鼠标事件用
 * @param idx
 * @return
 */
AutoSuggestControl.prototype.queryByIdx = function(idx){

	for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i];
        if (i == idx) {
        	this.textbox.value = oNode.name;
        	
        	//根据查询类型进行查询
        	if(this.queryType=="trs"){        		
        		actionValue();
        	}else if(this.queryType == "lifeQuery"){
        		head_actionValue();
        	}
            this.hideSuggestions();
        }
    }
}

/**
 * 初始化
 * @scope private
 */
AutoSuggestControl.prototype.init = function () {

    var oThis = this;
    //初始化 keyup 事件
    this.textbox.onkeyup = function (oEvent) {

        if (!oEvent) {
            oEvent = window.event;
        }    

        oThis.handleKeyUp(oEvent);
    };
    
    //初始化 keydown事件
    this.textbox.onkeydown = function (oEvent) {

        if (!oEvent) {
            oEvent = window.event;
        }    

        oThis.handleKeyDown(oEvent);
    };
    
    //文本框失去焦点事件  
    this.textbox.onblur = function () {
        oThis.hideSuggestions();
    };
    //创建下拉列表
    this.createDropDown();
};

/**
 * 文本选择范围，文本框提示用.
 * @scope public
 * @param iStart 
 * @param iEnd 
 */
AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iEnd /*:int*/) {

    //Internet Explorer
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange(); 
        oRange.moveStart("character", iStart); 
        oRange.moveEnd("character", iEnd - this.textbox.value.length);      
        oRange.select();
        
    //Mozilla
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iEnd);
    }     
    this.textbox.focus();      
}; 

/**
 * 显示下拉列表框
 * @scope private
 * @param json数据.
 */
AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/) {
    
    var oDiv = null;
    this.layer.innerHTML = "";  //清除以前内容
    
    for (var i=0; i < aSuggestions.length; i++) {
        oDiv = document.createElement("div");
        //oDiv.appendChild(document.createTextNode(aSuggestions[i].infoName_color));
        //name属性用作查询关键字
        oDiv.name = aSuggestions[i].infoName;
        //oTextbox,oTextbox1分别对应到实例化的控件对象
        if(this.queryType=="trs"){
        	if(aSuggestions[i].infoType=="ms"){
        		oDiv.innerHTML="<table width='100%' onmouseover='oTextbox.highlightSuggestionByIdx("+i+")' onmousedown='oTextbox.queryByIdx("+i+")'><tr><td align='left'>"+aSuggestions[i].infoName_color+"</td><td align='right'><img src='./images/trsImage/station_logo.bmp' align='texttop' ></img>"+aSuggestions[i].mtrStnName+"</td></tr></table>";
        	}else{
        		oDiv.innerHTML="<table width='100%' onmouseover='oTextbox.highlightSuggestionByIdx("+i+")' onmousedown='oTextbox.queryByIdx("+i+")'><tr><td align='left'>"+aSuggestions[i].infoName_color+"</td><td align='right'>"+aSuggestions[i].b_typeName+"</td></tr></table>";
        	}
        }else if(this.queryType=="lifeQuery"){
        	if(aSuggestions[i].infoType=="ms"){
        		oDiv.innerHTML="<table width='100%' onmouseover='oTextbox1.highlightSuggestionByIdx("+i+")' onmousedown='oTextbox1.queryByIdx("+i+")'><tr><td align='left'>"+aSuggestions[i].infoName_color+"</td><td align='right'><img src='./images/trsImage/station_logo.bmp' align='texttop' ></img>"+aSuggestions[i].mtrStnName+"</td></tr></table>";
        	}else{
        		oDiv.innerHTML="<table width='100%' onmouseover='oTextbox1.highlightSuggestionByIdx("+i+")' onmousedown='oTextbox1.queryByIdx("+i+")'><tr><td align='left'>"+aSuggestions[i].infoName_color+"</td><td align='right'>"+aSuggestions[i].b_typeName+"</td></tr></table>";
        	}        
        }else if(this.queryType=="startPlace"){
        	if(aSuggestions[i].infoType=="ms"){
        		oDiv.innerHTML="<table width='100%' onmouseover='oStartbox.highlightSuggestionByIdx("+i+")' onmousedown='oStartbox.queryByIdx("+i+")'><tr><td align='left'>"+aSuggestions[i].infoName_color+"</td><td align='right'><img src='./images/trsImage/station_logo.bmp' align='texttop' ></img>"+aSuggestions[i].mtrStnName+"</td></tr></table>";
        	}else{
        		oDiv.innerHTML="<table width='100%' onmouseover='oStartbox.highlightSuggestionByIdx("+i+")' onmousedown='oStartbox.queryByIdx("+i+")'><tr><td align='left'>"+aSuggestions[i].infoName_color+"</td><td align='right'>"+aSuggestions[i].b_typeName+"</td></tr></table>";
        	}        
        }else if(this.queryType=="endPlace"){
        	if(aSuggestions[i].infoType=="ms"){
        		oDiv.innerHTML="<table width='100%' onmouseover='oEndbox.highlightSuggestionByIdx("+i+")' onmousedown='oEndbox.queryByIdx("+i+")'><tr><td align='left'>"+aSuggestions[i].infoName_color+"</td><td align='right'><img src='./images/trsImage/station_logo.bmp' align='texttop' ></img>"+aSuggestions[i].mtrStnName+"</td></tr></table>";
        	}else{
        		oDiv.innerHTML="<table width='100%' onmouseover='oEndbox.highlightSuggestionByIdx("+i+")' onmousedown='oEndbox.queryByIdx("+i+")'><tr><td align='left'>"+aSuggestions[i].infoName_color+"</td><td align='right'>"+aSuggestions[i].b_typeName+"</td></tr></table>";
        	}   
        }
        this.layer.appendChild(oDiv);
    }
    
    this.layer.style.left = this.getLeft() + "px";
    this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px";
    //显示下拉列表
    this.layer.style.visibility = "visible";

};

/**
 * 文本框提示 
 * @scope private
 * @param json数据
 */
AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {

    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        var iLen = this.textbox.value.length; 
        this.textbox.value = sSuggestion; 
        this.selectRange(iLen, sSuggestion.length);
    }
};


/**
 * httpRequest对象
 * @class
 * @scope public
 */
function SuggestionProvider() {
    this.http = zXmlHttp.createRequest();
}

SuggestionProvider.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/,
                                                            bTypeAhead /*:boolean*/) {
    var oHttp = this.http;
                                                           
    if (oHttp.readyState != 0) {
        oHttp.abort();
    } 
    
    var seachWordObj = oAutoSuggestControl.textbox; // 当前输入框对象
    var seachWord = trim(oAutoSuggestControl.userText);
    var autoReg = /[\^\+\-\~\!\@\#\%\&\*\_\|\$]/g;
	for ( var i=0; i<seachWord.length; i++ ) {
		seachWord = seachWord.replace( autoReg, "" );
	}
	var oData = { 
		        requesting: "StatesAndProvinces", 
		        text: seachWord,
		        queryType:oAutoSuggestControl.queryType,
		        limit: 5 
		    };
		    //连接服务
		    oHttp.open("post",  "SuggestServices?txtSearch=" + encodeURI(oData.text)+"&queryType="+oData.queryType, true);
		    oHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		    oHttp.onreadystatechange = function () {
		        if (oHttp.readyState == 4) {
		            //获取json数据
		        	var jsonText = oHttp.responseText;
		        	//alert(jsonText);
		            var aSuggestions = JSON.parse(jsonText);
		           // var aSuggestions = eval('('+jsonText+')');
		            //alert(aSuggestions.toJSONString());
		            //provide suggestions to the control
		            oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);        
		        }    
		    };

		    //发送请求
		    oHttp.send(JSON.stringify(oData));

};

