$(document).ready(function () {
    var b = {
        "box-shadow": "#888 5px 2px 13px",
        "-webkit-box-shadow": "#888 5px 2px 13px",
        "-moz-box-shadow": "#888 5px 2px 13px"
    };
    $("#suggestions").css(b);
    $("#suggestions").hover(function () {
        $(this).addClass("sover")
    }, function () {
        $(this).removeClass("sover")
    });
    $("input").blur(function () {
        $("#suggestions").fadeOut()
    });
    //$(document).keydown(function (c) {
    $('#inputString').keydown(function (c) {
		var code = (c.keyCode ? c.keyCode : c.which)
        switch (code) {
        case 38:
            navigate("up");
            break;
        case 40:
            navigate("down");
            break;
        case 13:
			gotcurr=false
            if (typeof(currentUrl) != "undefined") {
                if (currentUrl != "") {
					gotcurr=true
                    window.location = currentUrl
                }
            }
			if(!gotcurr)search()
            break
        }
    });
    for (var a = 0; a < $("#suggestions div li a").size(); a++) {
        $("#suggestions div li a").eq(a).data("number", a)
    }
});

function navigate(a) {
    if ($("#suggestions div .itemhover").size() == 0)
        currentSelection = -1
    if (a == "up" && currentSelection != -1){
        currentSelection--
    } else if (a == "down") {
		if (currentSelection != $("#suggestions div li a").size() - 1) {
			currentSelection++
		}
    }
    setSelected(currentSelection)
}
function setSelected(a) {
    $("#suggestions div li").removeClass("itemhover");
    $("#suggestions div li").eq(a).addClass("itemhover");
    currentUrl = $("#suggestions div li a").eq(a).attr("href")
}
function showText(a, b) {
    if (a == "focus") {
        if (b.value == "Buscar")
            b.value = ""
    } else if (a == "blur") {
        if (b.value == "")
			b.value = "Buscar"
    }
}
function search() {
    var a = "http://www.consul.com.br/home/resultado.aspx?TextoBusca=" + document.forms[0].inputString.value;
    window.location = a
}
function cancelSubmit(b) {
    var b = b || event;
    var a = b.keyCode;
    if (a == 13) {
        return false
    }
/*    if (a >= 33 && a <= 47) {
        a = 0;
        return false
    }
    if (a >= 58 && a <= 64) {
        a = 0;
        return false
    }
    if (a >= 91 && a <= 96) {
        a = 0;
        return false
    }
    if (a >= 123 && a <= 127) {
        a = 0;
        return false
    }*/
}
function regexEscape(a) {
    var b = ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "^", "&", "%", "#", "@", "$"];
    var c = new RegExp("(\\" + b.join("|\\") + ")", "g");
    return a.replace(c, "")
}

window.ajaxCache={}
window.lastSearchContent=false

function lookup(inputString, e) {
	function success(data) {
		if(window.lastSearchContent==window.lastConn)return
		window.lastSearchContent=window.lastConn
		window.ajaxCache[window.lastConn]=data
		$("#suggestions").html("");
		dados = eval("(" + data.d + ")");
		$("#suggestions").fadeIn();
		var sHtml = "";
		var lastCategory = "";
		var ilastCategory = "";
		jQuery.each(dados, function (i, x) {
			if (x.CategoriaNome == "Produtos") {
				if (x.CategoriaNome != lastCategory) {
					sHtml += '<div class="categoryprod">';
					sHtml += "<h4>" + x.CategoriaNome + "</h4>";
					sHtml += "<ul>";
					ilastCategory = x.CategoriaNome
				}
			} else {
				if (lastCategory != "") {
					if (x.CategoriaNome != lastCategory) {
						sHtml += "</ul>";
						sHtml += "</div>"
					}
				}
				if (x.CategoriaNome != lastCategory) {
					sHtml += "<div>";
					sHtml += "<h4>" + x.CategoriaNome + "</h4>";
					sHtml += "<ul>"
				}
				ilastCategory = x.CategoriaNome
			}
			sHtml += "<li>";

			if (x.CategoriaNome == 'Produtos') {
				sHtml += '<img src="' + url_site + x.Foto + '"  alt="' + x.Nome + '" height="46px" width="46px" />';
			}
						
			sHtml += "<h3>" + x.Nome + "</h3>";
			sHtml += '<a href="' + x.Url + '" title="' + x.Nome + '" class="bs_descricao"><p>' + x.Descricao + "</p></a>";
			sHtml += "</li>";
			if (x.CategoriaNome != ilastCategory) {
				sHtml += "</ul>";
				sHtml += "</div>"
			}
			lastCategory = x.CategoriaNome
		});
		if (lastCategory != "") {
			sHtml += "</ul>";
			sHtml += "</div>"
		}
		sHtml += '<a href="' + url_site + "/home/resultado.aspx?TextoBusca=" + inputString + '" title="ver todos os resultados" class="bt"><span>ver todos os resultados</span></a>';
		$("#suggestions").html(sHtml);
		$("#suggestions li").click(function () {
			location = $(this).find("a:eq(0)").attr("href")
		});
		$("#busca").removeClass("loading")
	}
    var url_site = "http://www.consul.com.br";
    var e = e || event;
    var _keyCode = e.keyCode;
    var token = regexEscape(inputString);
    if (inputString.length == 0) {
        $("#suggestions").fadeOut();
        return false
    } else {
		window.lastConn=token
	    if(window.ajaxCache[token]){
            success(window.ajaxCache[token])
		}else{
			if (inputString.replace(/\s/g, "").length >= 3) {
				if ((_keyCode == 8) || (_keyCode == 39) || (_keyCode >= 48 && _keyCode <= 57) || (_keyCode >= 65 && _keyCode <= 90) || (_keyCode >= 97 && _keyCode <= 122)) {
					$("#busca").addClass("loading");
					$.ajax({
						type: "POST",
						url: url_site + "/WSBuscaSugerida.asmx/ExecutaBuscaSugeridaIndice",
						cache: true,
						data: "{'parametro':'" + token + "','portal':'CONSUL'}",
						contentType: "application/json; charset=utf-8",
						dataType: "json",
						success: success,
						error: function (data) {
							$("#busca").removeClass("loading");
							return false
						}
					})
				} else {
					return false
				}
			}
		}
    }
};
