var gl_show_ajax_indicator = false;
//全局变量
var arrOptions = new Array();
var strLastValue = "";
var bMadeRequest;
var theTextBox;
var objLastActive;
var currentValueSelected = -1;
var bNoResults = false;
var isTiming = false;

//定制输入前提示框，并为其动态分配属性
$(document).ready(function(){
    var htm = "<ul id = 'suggest_output' class = 'suggest'><div id='be_replace'></div></ul>";
    $(".suggest-wrap").append(htm);
    document.search_form.keyword.obj = SetProperties(document.search_form.keyword,
        document.search_form.keyword_choose,
        true,true,true,true,"请点击查询按钮查找您想要的结果:)",false,null,1
        );
});
//创建一个定制的对象
function SetProperties(xElem, xHidden,
    xignoreCase, xmatchAnywhere, xmatchTextBoxWidth,
    xshowNoMatchMessage, xnoMatchingDataMessage, xuseTimeout, xtheVisibleTime, xToLink){
    var props={
        elem: xElem,
        hidden: xHidden,
        regExFlags: ((xignoreCase) ? "i" : ""),
        regExAny: ((xmatchAnywhere) ? "^" : ""),
        matchAnywhere: xmatchAnywhere,
        matchTextBoxWidth: xmatchTextBoxWidth,
        theVisibleTime: xtheVisibleTime,
        showNoMatchMessage: xshowNoMatchMessage,
        noMatchingDataMessage: xnoMatchingDataMessage,
        useTimeout: xuseTimeout,
        isToLink: xToLink
    };
    AddHandler(xElem);
    return props;
}
//附加事件处理函数
var isOpera=(navigator.userAgent.toLowerCase().indexOf("opera") != -1);
var isIE=(navigator.userAgent.toLowerCase().indexOf("msie") != -1)
function AddHandler(objText){
    objText.onkeyup = GiveOptions;
    if(isIE)objText.onkeypress = catch_enter;
    if(isOpera)objText.onkeypress = catch_enter;
}
//用于捕获ie浏览器的回车键	
function catch_enter(){
    var intKey = -1;
    //ie浏览器
    if(window.event){
        intKey = event.keyCode;
        theTextBox = event.srcElement;
    }
    if (objLastActive == theTextBox) {//问题很多
        if (intKey == 13) {//回车
            GrabHighlighted();
            theTextBox.blur();
            return false;
        }
    }
}
//检测用户按键的JavaScript代码
function GiveOptions(e){
    var intKey = -1;
    //ie浏览器
    if(window.event){
        intKey = event.keyCode;
        theTextBox = event.srcElement;
    }
    //firefox浏览器
    else{
        intKey = e.which;
        theTextBox = e.target;
    }
    if(theTextBox.obj.useTimeout){//使用定时器
        if(isTiming)EraseTimeout();
        StartTimeout();
    }
    if(theTextBox.value.length == 0 && !isOpera){
        arrOptions = new Array();
        HideTheBox();
        strLastValue = "";
        return false;
    }
    if(objLastActive == theTextBox){//问题很多
        if(intKey == 13){//回车
            GrabHighlighted();
            theTextBox.blur();
            return false;
        }
        else if(intKey == 38){//down
            MoveHighlight(-1);
            return false;
        }
        else if(intKey == 40){//up
            MoveHighlight(1);
            return false;
        }
        else if(intKey == 37 || intKey == 39){
            return false;
        }
    }
    if(objLastActive != theTextBox || theTextBox.value.indexOf(strLastValue)!= 0 || ((arrOptions.length == 0 || arrOptions.length == 15) && !bNoResults) || (theTextBox.value.length != strLastValue.length)){
        objLastActive = theTextBox;
        bMadeRequest = true;
        TypeAhead(theTextBox.value.replace(/\s+/g,""));
    }
    else if(!bMadeRequest){
    //BuildList(theTextBox.value);
    }
    strLastValue = theTextBox.value.replace(/\s+/g,"");
}
//将数据发送到服务器的Ajax功能
function TypeAhead(xStrText){
    $.post( "/food/suggest_search",{
        keyword: xStrText
    },
    function(data){
        BuildChoices(data);
    }
    );
}
//将responseText属性转换为JavaScript数组
function BuildChoices(strText){
    arrOptions = strText.split(',');
    for (i = 0; i < arrOptions.length; i++) {
        arrOptions[i] = arrOptions[i].split(";");
    }
    BuildList(strLastValue);
    bMadeRequest = false;
}
//将结果格式化为可显示的格式
function BuildList(theText){
    SetElementPosition(theTextBox);
    var theMatche = MakeMatches(theText);
    theMatches = "<span id='be_replace'>"+theMatche.join().replace(/\,/gi,"")+"</span>";
    if (theMatche.length > 0){
        $("#be_replace").replaceWith(theMatches);
        $("#OptionsList_0").addClass("hover");
        currentValueSelected = 0;
        bNoResults = false;
    }
    else{
        currentValueSelected = -1;
        bNoResults = true;
        if (theTextBox.obj.showNoMatchMessage) {
            innerHTML = "<span class = 'stress' id='be_replace'>" + theTextBox.obj.noMatchingDataMessage + "</span>";//需要改动
            $("#be_replace").replaceWith(innerHTML);
        }
        else
            HideTheBox();
    }
}
//使用正则表达式限制结果数量
var countForId = 0;
function MakeMatches(xCompareStr){
    countForId = 0;
    var matchArray = new Array();
    var regExp = new RegExp(xCompareStr, theTextBox.obj.regExFlags);
    for(i=0;i<arrOptions.length-1;i++){
        if (matchArray.length < 10) {
            var theMatch = arrOptions[i][0].match(regExp) || arrOptions[i][1].match(regExp);
            if (theMatch) {
                matchArray[matchArray.length] = CreateUnderline(arrOptions[i][0], xCompareStr, i);
            }
        }
        else break;
    }
    return matchArray;
}
 
//动态查找未定位元素的位置
function SetElementPosition(theTextBoxInt){
    if(theTextBoxInt.obj.matchTextBoxWidth)
        $("#suggest_output").css("width",$(theTextBox.obj.elem).width());
    $("#suggest_output").css("display","block");
}
//使用JavaScript执行字符串操作
var undeStart = "<span class = 'stress green1'>";
var undeEnd = "</span>";

var selectSpanStart = "<li onmouseover = 'SetHighColor(this)' ";
var selectSpanEnd = "</li>";

function CreateUnderline(xStr, xTextMatch, xVal){
    selectSpanMid = "onclick = 'SetText(" + xVal + ")'" + "id = 'OptionsList_" + countForId + "' theArrayNumber='" + xVal + "'>";
    var regExp = new RegExp(xTextMatch, theTextBox.obj.regExFlags);
    var aStart = xStr.search(regExp);
    var matchedText = xStr.substring(aStart, aStart + xTextMatch.length);
	
    countForId++;
    return selectSpanStart + selectSpanMid + xStr.replace(regExp, undeStart + matchedText + undeEnd) + selectSpanEnd;
}
//使用JavaScript修改元素的css类名
function MoveHighlight(xDir){
    if(currentValueSelected >= 0){
        newValue = parseInt(currentValueSelected) + parseInt(xDir);
        if(newValue > -1 && newValue < countForId){
            currentValueSelected = newValue;
            SetHighColor(null);
        }
        xVal = document.getElementById("OptionsList_" + currentValueSelected).getAttribute("theArrayNumber");
        theTextBox.value = arrOptions[xVal][0];//set text value
        theTextBox.obj.hidden.value = arrOptions[xVal][0];
    }
}
function SetHighColor(theTextBox){
    if(theTextBox){
        currentValueSelected = theTextBox.id.slice(theTextBox.id.indexOf("_") + 1, theTextBox.id.length);
    }
    for(i = 0; i < countForId; i++){
        document.getElementById('OptionsList_' + i).className = '';
    }
    document.getElementById('OptionsList_' + currentValueSelected).className = 'hover';
}
function SetText(xVal){
    theTextBox.value = arrOptions[xVal][0];//set text value
    theTextBox.obj.hidden.value = arrOptions[xVal][0];
    $("#suggest_output").css("display","none");
    currentValueSelected = -1;//remove the selected index
    if (theTextBox.obj.isToLink == 1) {
        open("/shiwu/" + arrOptions[xVal][1]);
    }
}

function GrabHighlighted(){
    if(currentValueSelected >= 0){
        xVal = document.getElementById("OptionsList_" + currentValueSelected).getAttribute("theArrayNumber");
        SetText(xVal);
        HideTheBox();
    }
}
function HideTheBox(){
    $("#suggest_output").css("display","none");
    currentValueSelected = -1;
//EraseTimeout();
}