﻿/*
 * jQuery AutoComplete
 *
 * Author: luq885
 * http://blog.csdn.net/luq885 (chinese) 
 *
 * Licensed like jQuery, see http://docs.jquery.com/License
 *
 * 作者：天天无用
 * blog: http://blog.csdn.net/luq885
 *==============================================================
 * 修改者：潘国亮
 *==============================================================
 */
var currentInput;
var key = "";
var isShow = true;
var activeDiv;

var dataRequest = "";//返回数据的分隔符
var kwlength;//关键字最小长度
var autoTab;//是否回车后自动转到下一个文本框
var parameterName;//回传时的参数名
var parameterNameTable;
var parameterNameField;
jQuery.fn.AutoComplete = function(request, option) {
    this.each(function() {
        if (this.tagName.toLowerCase() == "input" && q(this).attr("type").toLowerCase() == "text") {
            q(this).keydown(function(e) {
                selectText(e.keyCode, this);
            });
            q(this).keyup(function(e) {
                searchKey(e.keyCode);
            });
            q(this).blur(function() {
                selected_seggestion_Div = q("#suggestion>div[@class=s_selected]");
                selected_floor_Div = q("#floor>div[@class=f_selected]");
                if (selected_floor_Div.length < 1 && selected_seggestion_Div.length < 1) {
                    hideText();
                    return;
                }
            });
        }
    });
    if (request.length == 0) throw "request is required";
    dataRequest = request;
    kwlength = option.kwlength || 1;
    seperator = option.seperator || ",";
    autoTab = option.autoTab || false;
    parameterName = option.parameterName || "";
    parameterNameTable = option.parameterNameTable || "";
    parameterNameField = option.parameterNameField || "";
    //alert(parameterNameTable);
    //alert(parameterNameField);
    q("body").prepend("<div id='suggestion'class='suggestion'><div id='s_show' onmouseout = q(this).attr('class','s_unselected') onmouseover = s_mouseover(this) style='display:none;'>show</div><div id='s_hide'onmouseout = q(this).attr('class','s_unselected') onmouseover = s_mouseover(this) style='display:none;'>hide</div><div id='floor' class='floor'></div></div>")

    q("#s_show").click(function() {
        isShow = true;
        q("#s_show").hide();
        if (q("#floor").html() != "") {
            q("#s_hide").show();
            q("#floor").show();
        }
    });

    q("#s_hide").click(function() {
        isShow = false;
        q("#s_show").hide();
        q("#s_hide").hide();
        q("#floor").hide();
    });
    q("#floor").hide();
}

function showText() {
    if (q("#txtSearchType").val() != '1') {
        return;
    }
    text = document.getElementById(currentInput.attr("id"));
    div = document.getElementById("suggestion");
    div.style.left = getPos(text,"Left") + "px";
    div.style.top = getPos(text,"Top") + text.offsetHeight +15+ "px";
    div.style.width = text.offsetWidth + "px";
    if (isShow) {
        if (q("#floor").html() != "") {            
            q("#s_hide").show();
        }
        q("#s_show").hide();
        q("#floor").show();
    }
    else {
        q("#s_show").show();
        q("#s_hide").hide();
    }
}

function hideText()
{
    //alert(111);
    q("#s_hide").hide();
    q("#floor").hide();
    q("#floor").html("");
    key="";    
    currentInput = null;
}

function getPos(el,ePro)				
{
    var ePos=0;
    while(el!=null)
    {		
        ePos+=el["offset"+ePro];
        el=el.offsetParent;
    }
    return ePos;
}

function searchKey(keycode)
{
    if(keycode == 38 || keycode == 40 || keycode == 13 || keycode == 27 || keycode == 9) return;    
    if(currentInput != null && (key == "" || currentInput.val() != key) && currentInput.val().length >= kwlength)
    {
//    alert(parameterNameTable);
//    alert(parameterNameField);
    
        var divs = "";
        jQuery.ajax({
            type: "Post",
            dataType: "text",
            url: dataRequest,
            data: parameterNameTable + "&" + parameterNameField + "&" + (parameterName != "" ? parameterName + "=" + currentInput.val() : (currentInput.attr("name") == null ? currentInput.attr("id") + "=" + currentInput.val() : currentInput.serialize())),
            success: function(msg) {
                if (msg.length == 0) {
                    hideText();
                    return;
                }
                var datas = msg.split(seperator);
                q.each(datas, function(i, n) {
                    if (n.length > 0) divs += "<div class=f_unselected onclick=setInput() onmouseout = q(this).attr('class','f_unselected') onmouseover = f_mouseover(this)>" + n + "</div>";
                });
                q("#floor").html(divs);
                    showText();
            }
        });
        //alert(data);
        key = currentInput.val();
    }
    if (key.length == 0 || key.length < kwlength || currentInput.val() == "") hideText();
}
function setInput()
{
 //alert(111);
    selectedDiv = q("#floor>div[@class=f_selected]");
    if(selectedDiv.length<1)
    {
        hideText();
        return;
    }
    currentInput.val(selectedDiv.text());
    hideText();
   
}
function findNextInput(target)
{   
    var index;
    q("input[@type=text]").each(function(i){
        if(q(this).attr("id") == target.attr("id")) index = i;
    });
    return q("input[@type=text]")[ index + 1 ];
}

function selectText(keycode,sInput)
{    
    currentInput = q("#"+sInput.id);
    if(keycode == 13)
    {        
        if(autoTab) q(findNextInput(currentInput)).focus();
        hideText();
        setInput();
            
    }
    if(!isShow) return;
    if(keycode == 27) hideText();
    selectedDiv = q("#floor>div[@class=f_selected]");
    if(selectedDiv.text() != "")
    {
        selectedDiv.attr("class","f_unselected");
        if(keycode == 38)
        {
            if(selectedDiv.prev().text() != "")
            {
                selectedDiv.prev().attr("class", "f_selected");
                currentInput.val(selectedDiv.prev().text());
            }
            else
            {
                q("#floor>div:last").attr("class", "f_selected");
                currentInput.val(q("#floor>div:last").text());                
            }
        }
        else if(keycode == 40)
        {
            if(selectedDiv.next().text() != "")
            {
                selectedDiv.next().attr("class", "f_selected");
                currentInput.val(selectedDiv.next().text());
            }
            else
            {
                q("#floor>div:first").attr("class", "f_selected");
                currentInput.val(q("#floor>div:first").text());                
            }
        }            
    }
    else if(keycode == 38)
    {
        q("#floor>div:last").attr("class", "f_selected");
        currentInput.val(q("#floor>div:last").text());
    }
    else if(keycode == 40)
    {
        q("#floor>div:first").attr("class", "f_selected");
        currentInput.val(q("#floor>div:first").text());        
    }
}

function f_mouseover(f_Div)
{    
    q("#floor").children("div").attr("class","f_unselected");
    q(f_Div).attr("class", "f_selected");
    currentInput.val(q(f_Div).text());
}

function s_mouseover(s_Div) {
    q(s_Div).attr("class", "s_selected");
 }
