
var obXML_HTTP, obTipoDeLogradouro, obLogradouro, obBairro, obCidade, obEstado;

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function UpMenu(obImagem)
{
    try
    {
        var obData = new Date();
        obImagem.id = obData.getMilliseconds();
        stSRC = obImagem.src;
        if (stSRC.charAt(stSRC.length - 5) != '2')
        {
            stSRC = stSRC.substring(0, stSRC.length - 4) + '_2.gif';
            obImagem.src = stSRC;
        }
        if (obImagem.style.backgroundPosition == '')
            inHeight = 40;
        else
            inHeight = obImagem.style.backgroundPosition.split(" ")[1].split("p")[0];
        while (inHeight > 0)
        {
            inTimeoutUp = setTimeout("PosMenuShow('" + obImagem.id + "', 0, " + inHeight + ")", (10 * (40 - inHeight)));
            inHeight = inHeight - 1;
        }
    } catch (e)
    {
        alert('[UpMenu] ' + e);
    }
}

function PosMenuShow(stId, inWidth, inHeight)
{
    try
    {
        if ((stId == undefined) || (document.getElementById(stId) == undefined) || (document.getElementById(stId) == null))
            return;
        document.getElementById(stId).style.backgroundPosition = inWidth + 'px ' + inHeight + 'px';
    } catch (e)
    {
        alert('[PosMenuShow] Posicao [' + inWidth + ', ' + inHeight + ']\n' + e);
    }
}

function GetXmlHttpObject()
{
    var obXML_HTTP_AUX = null;
    try
    {
        // Firefox, Opera 8.0+, Safari
        obXML_HTTP_AUX = new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            obXML_HTTP_AUX = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            obXML_HTTP_AUX = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return obXML_HTTP_AUX;
}

function CalcularFrete()
{
    obCEP = document.getElementById("cep_destino");
    inTipoFrete = document.getElementById("tipo_frete").value;
    FormataCEP(obCEP);
    stCEP = obCEP.value;
    if (stCEP.length == 0)
        return;
    stCEP = GetNumeros(stCEP);
    if (stCEP.length != 8)
    {
        alert ('CEP [' + stCEP + '] inválido');
        return;
    }
    var stURL = "calcula_frete.php?cep_destino=" + stCEP + "&tipo_frete=" + inTipoFrete;
    obXML_HTTP = GetXmlHttpObject();
    if (obXML_HTTP != null)
    {
        if (document.getElementById("resultado-calcula-frete-conteudo") != null)
        {
            document.getElementById("resultado-calcula-frete-conteudo").innerHTML = "<b>Processando ...</b>";
            document.getElementById("resultado-calcula-frete-conteudo").style.display = "block";
        }
        obXML_HTTP.onreadystatechange = StateChange_CalcularFrete;
        obXML_HTTP.open("GET", stURL, true);
        obXML_HTTP.send(null);
    }
    else
    {
        alert("Esse Browser não possui suporte para XMLHTTP.");
    }
}

function StateChange_CalcularFrete()
{
    try
    {
        if ((obXML_HTTP.readyState == 4) || (obXML_HTTP.readyState == "complete"))
        {// 4 = "loaded"
            obXML_DOC = obXML_HTTP.responseXML;
            if (obXML_DOC == null)
            {
                if (document.getElementById("resultado-calcula-frete-conteudo") != null)
                {
                    document.getElementById("resultado-calcula-frete-conteudo").innerHTML = "Resposta incorreta [obXML_DOC is null]";
                }
            }
            else
            {
                inResultado = obXML_DOC.getElementsByTagName("resultado_calcula_frete")[0].childNodes[0].nodeValue;
                if (inResultado == 1)
                {
                    stServico = obXML_DOC.getElementsByTagName("servico")[0].childNodes[0].nodeValue;
                    stOrigem  = obXML_DOC.getElementsByTagName("origem")[0].childNodes[0].nodeValue;
                    stDestino = obXML_DOC.getElementsByTagName("destino")[0].childNodes[0].nodeValue;
                    stTarifa  = obXML_DOC.getElementsByTagName("tarifa")[0].childNodes[0].nodeValue;
                    if (document.getElementById("resultado-calcula-frete-conteudo") != null)
                    {
                        document.getElementById("resultado-calcula-frete-conteudo").innerHTML = "<b>Serviço : " + stServico + "<br />Destino : " + stDestino + "<br />Tarifa(R$) : " + stTarifa + "</b><br />";
                    }
                    document.getElementById("cep_destino").value = "";
                }
                else
                {
                    if (document.getElementById("resultado-calcula-frete-conteudo") != null)
                    {
                        document.getElementById("resultado-calcula-frete-conteudo").innerHTML = "<font color=\"red\"><b>" + obXML_DOC.getElementsByTagName("erro")[0].childNodes[0].nodeValue + "</b></font>";
                    }
                }

                inResultado        = obXML_DOC.getElementsByTagName("resultado")[0].childNodes[0].nodeValue;
                if (inResultado == 1)
                {
                    stLogradouro  = obXML_DOC.getElementsByTagName("tipo_logradouro")[0].childNodes[0].nodeValue + ' ' + obXML_DOC.getElementsByTagName("logradouro")[0].childNodes[0].nodeValue;
                    stBairro      = obXML_DOC.getElementsByTagName("bairro")[0].childNodes[0].nodeValue;
                    stCidade      = obXML_DOC.getElementsByTagName("cidade")[0].childNodes[0].nodeValue;
                    stEstado      = obXML_DOC.getElementsByTagName("uf")[0].childNodes[0].nodeValue;
                    document.getElementById("resultado-calcula-frete-conteudo").innerHTML = document.getElementById("resultado-calcula-frete-conteudo").innerHTML + "<b><br />Logradouro : " + stLogradouro + "<br />Bairro : " + stBairro + "<br />Cidade : " + stCidade + "-" + stEstado + "</b>";
                }
                else if (inResultado == 2)
                {
                    stCidade = obXML_DOC.getElementsByTagName("cidade")[0].childNodes[0].nodeValue;
                    stEstado = obXML_DOC.getElementsByTagName("uf")[0].childNodes[0].nodeValue;
                    document.getElementById("resultado-calcula-frete-conteudo").innerHTML = document.getElementById("resultado-calcula-frete-conteudo").innerHTML + "<b><br />Cidade : " + stCidade + "-" + stEstado + "</b>";
                }
                else
                {
                    alert(obXML_DOC.getElementsByTagName("resultado_txt")[0].childNodes[0].nodeValue + '\nErro Número ' + inResultado);
                }
            }
            document.getElementById("resultado-calcula-frete-conteudo").style.display = "block";
        }
    } catch (e)
    {
        if (document.getElementById("resultado-calcula-frete-conteudo") != null)
        {
            document.getElementById("resultado-calcula-frete-conteudo").innerHTML = "";
            document.getElementById("resultado-calcula-frete-conteudo").style.display = "none";
        }
        alert (e);
        document.getElementById("cep_destino").value = "";
    }
}

function GetNumeros(stEntrada)
{
    stSaida = "";
    for (inPosicao = 0 ; inPosicao < stEntrada.length ; inPosicao++)
    {
        if ((stEntrada.charCodeAt(inPosicao) >= "0".charCodeAt(0)) && (stEntrada.charCodeAt(inPosicao) <= "9".charCodeAt(0)))
            stSaida = stSaida.concat(stEntrada.charAt(inPosicao));
    }
    return stSaida;
}

function FormataCEP(obInputText)
{
    stTexto   = obInputText.value;
    stNumeros = GetNumeros(stTexto);
    stText = "";
    for (inPosicao = 0 ; ((inPosicao < stNumeros.length) && (inPosicao < 8)) ; inPosicao++)
    {
        if (inPosicao == 5)
            stText = stText.concat("-");
        stText = stText.concat(stNumeros.charAt(inPosicao));
    }
    obInputText.value = stText;
}

function BuscaDetalhes(inId){
    var stURL = "busca-informacao.php?id=" + inId;
    obXML_HTTP = GetXmlHttpObject();
    if (obXML_HTTP != null)
    {
        obXML_HTTP.onreadystatechange = StateChange_BuscaDetalhes;
        obXML_HTTP.open("GET", stURL, true);
        obXML_HTTP.send(null);
    }
    else
    {
        alert("Esse Browser não possui suporte para XMLHTTP.");
    }
}

function StateChange_BuscaDetalhes()
{
    try
    {
        document.getElementById("div-detalhes").style.display = 'block';
        document.getElementById("div-detalhes").style.top = '' + yOffSet + 'px';
        obDestinoResultado= document.getElementById("div-detalhes-conteudo");
        if (obDestinoResultado == null)
        {
            alert('Objeto de resposta não encontrado.');
            return;
        }
        switch (obXML_HTTP.readyState) {
            case 0:
                obDestinoResultado.innerHTML = "<b>Inicializando ...</b>";
                break;
            case 1:
                obDestinoResultado.innerHTML = "<b>Inicializado ...</b>";
                break;
            case 2:
                obDestinoResultado.innerHTML = "<b>Enviando ...</b>";
                break;
            case 3:
                obDestinoResultado.innerHTML = "<b>Processando ...</b>";
                break;
            case 4:
                if (obXML_HTTP.responseText == "")
                    document.getElementById("div-detalhes").style.display = 'none';
                else
                    obDestinoResultado.innerHTML = obXML_HTTP.responseText;
                break;
        }
    } catch (e)
    {
        alert (e);
    }
}

