/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

function novaConsulta() {        
    esconderResultado();
    esconderContagem();
    $("#numZe").val("0");
    $("#numMunicipio").val("0");    
}

//window.alert("Código O.K. 1!");
function configurarPagina() {
    // window.alert("parent" + parent.document.title);
    if (parent.document.title != "Eleições 2008") {
        // window.alert("Fora do FRAME!");
        window.location = "http://www.tre-sp.gov.br/eleicoes/2008/index.htm?mrj";
    }
    esconderResultado();
    carregarZonaEleitoral();
    carregarMunicipio();
    $("#btnConsultarPorMunicipio").click(function() {
        consultarPorMunicipio();
    });
    $("#btnConsultarPorZe").click(function() {
        consultarPorZe();
    });
    $("#btnLimparConsulta").click(function() {
        novaConsulta();
    });
    return (true);
}
//window.alert("Código O.K. 2!");
function carregarZonaEleitoral() {
    $("#numZe").html("<option value='0'>A carregar...</option>");
    $.ajax({
        type: "GET",
        url: "database/ze.xml",
        data: "",
        async: true,
        success:     
            /* /$.post("config/config.xml"
    , {}
    , */function (response) {        
            //window.alert("Config XML" + $(response).text());
            $("#numZe").html("<option value='0'>-- selecionar --</option>");
            $(response).find("ze").each(function() {
                $(this).attr("numZe");
                $("#numZe").append("<option value='" +
                    $(this).attr("numZe") +
                    "'>" + $(this).text() + "</option>");
            });
        }
        /* , "xml"); */,
        error: function() {
            avisarErroServico();
        }
    });   
    /* /$("#numZe").change(function () {
        $("#escolhaConsulta").html($("#numZe option[@selected]").html());
    }); */
}
//window.alert("Código O.K. 3!");
function carregarMunicipio() {
    $("#numMunicipio").html("<option value='0'>A carregar...</option>");
    $.ajax({
        type: "GET",
        url: "database/municipio.xml",
        data: "",
        async: true,
        success:     
            /* /$.post("config/config.xml"
    , {}
    , */function (response) {        
            //window.alert("Config XML" + $(response).text());
            $("#numMunicipio").html("<option value='0'>-- selecionar --</option>");
            $(response).find("municipio").each(function() {            
                $("#numMunicipio").append("<option value='" +
                    $(this).attr("codigo") +
                    "'>" + $(this).attr("nome") + "</option>");
            });
        }
        /* , "xml"); */,
        error: function() {
            avisarErroServico();
        
        }        
    });     
    /* /$("#numMunicipio").change(function () {
        $("#escolhaConsulta").html($("#numMunicipio option[@selected]").html());
    }); */
}
//window.alert("Código O.K. 4\n\!");

function consultarPorMunicipio() {
    //window.alert("Arquivo ZE: " + obterNomeArquivoMunicipio());
    if ($("#numMunicipio").val() == "0") {
        window.alert("Selecione um município da lista.");
        $("#numMunicipio").focus();
        return (false);
    }
    esconderContagem();
    $("#textoExplicativo").html("");
    $("#textoExplicativo").html("Mesas Receptoras de Justificativa para " + $("#numMunicipio option[@selected]").html());
    exibirEspera();
    $("#corpoResultado").html("");
    $.ajax({
        type: "GET",
        url: "" + obterNomeArquivoMunicipio(),
        data: "",
        async: true,
        success:
            function (response) {
            //window.alert("1:  Rodou o serviço!");
            // window.alert("Config XML - por ZE\n" + $(response).text());
            $("#corpoResultado").html("");
            //window.alert("Código do Município" + $(response).find("mrj").find("COD_MUNICIPIO").text());
            //window.alert("filtro:\n" + "mrj>NUMERO:('" + $("#numMunicipio").val() + "')");
            // $(response).find("mrj").filter(function () { return ($(this).find("COD_MUNICIPIO").text() == $("#numMunicipio").val()) }).each(function(){
            var qtdTotal = 0;
            $(response).find("mrj").each(function(){
                //window.alert("texto do XML: \n" + $(this).text());
                var etiquetaLocal = "Local"
                var local = $(this).find("NOM_LOCAL").text()
                     + "<br>Endereço:" //  + $(this).find("NOM_LOCAL").text()
                     + "<br>" + $(this).find("DES_ENDERECO").text();
                if ($(this).attr("indPreenchimentoManual") == "S") {
                    $("#textoExplicativo").html("Entre em contato com a Zona Eleitoral abaixo:");
                    etiquetaLocal = "Endereço"
                    local = "" + $(this).find("NOM_LOCAL").text()
                      //  + $(this).find("NOM_LOCAL").text()
                     + "<br>" + $(this).find("DES_ENDERECO").text();
                }
                $("#corpoResultado").append("<tr>"
                    + "<td>"
                    + "<table width=\"100%\" class=\"tbl_mun200\">"
                    + "<tbody>"
                    + "<tr>"
                    + "<td align=\"right\" width=\"60px\">Zona</td><td>" + $(this).find("NUM_ZONA").text() + "ª " + $(this).find("NOM_ZONA").text() + "</td>"
                    + "</tr>"
                    + "<tr>"
                    + "<td align=\"right\">Município</td><td>" + $(this).find("NOM_MUNICIPIO").text() + "</td>"
                    + "</tr>"
                    + "<tr>"
                    + "<td align=\"right\" valign=\"top\">" + etiquetaLocal + "</td>"
                    + "<td>"
                    + local
                // + "<br>BAIRRO " + $(this).find("NOM_BAIRRO").text()
                    + "</td>"
                    + "</tr>"
                    + "</tbody>"
                    + "</table>"
                    + "</td>"
                    + "</tr>");
                    qtdTotal++;
            });            
            exibirResultado();
            if (qtdTotal > 1) {
                $("#contagem").html("Total encontrado: " + qtdTotal);
                exibirContagem();
            }
        },
        error: function() {
            avisarErroServico();
            // consultarAlternativaMunicipio();
        }
    })
    return true;
}  

function consultarPorZe() {
    //window.alert("Arquivo ZE: " + obterNomeArquivoZe());    
    if ($("#numZe").val() == "0") {
        window.alert("Selecione uma zona eleitoral da lista.");
        $("#numZe").focus();
        return (false);
    }
    esconderContagem();
   $("#textoExplicativo").html("");
   $("#textoExplicativo").html("Locais Receptoras de Justificativa para " + $("#numZe option[@selected]").html());
    exibirEspera();
    $("#corpoResultado").html("");
    $.ajax({
        type: "GET",
        url: "" + obterNomeArquivoZe(),
        data: "",
        async: true,
        success:     
            function (response) {
            //window.alert("1:  Rodou o serviço!");
            // window.alert("Config XML - por ZE\n" + $(response).text());        
            $("#corpoResultado").html("");
            //window.alert("filtro:\n" + "mrj>NUMERO:('" + $("#numZe").val() + "')");
            // $(response).find("mrj").filter(function () { return ($(this).find("NUMERO").text() == $("#numZe").val()) }).each(function(){
            var qtdTotal = 0;
            $(response).find("mrj").each(function(){
                //window.alert("texto do XML: \n" + $(this).text());
                var etiquetaLocal = "Local";
                var local = $(this).find("NOM_LOCAL").text()
                     + "<br>Endereço:" //  + $(this).find("NOM_LOCAL").text()
                     + "<br>" + $(this).find("DES_ENDERECO").text();
                if ($(this).attr("indPreenchimentoManual") == "S") {
                    $("#textoExplicativo").html("Entre em contato com a Zona Eleitoral abaixo:");
                    etiquetaLocal = "Endereço";
                    local = "" + $(this).find("NOM_LOCAL").text()
                      //  + $(this).find("NOM_LOCAL").text()
                     + "<br>" + $(this).find("DES_ENDERECO").text();
                }
                $("#corpoResultado").append("<tr>"
                    + "<td>"
                    + "<table width=\"100%\" class=\"tbl_mun200\">"
                    + "<tbody>"
                    + "<tr>"
                    + "<td align=\"right\" width=\"60px\">Zona</td><td>" + $(this).find("NUM_ZONA").text() + "ª " + $(this).find("NOM_ZONA").text() + "</td>"
                    + "</tr>"
                    + "<tr>"
                    + "<td align=\"right\">Município</td><td>" + $(this).find("NOM_MUNICIPIO").text() + "</td>"
                    + "</tr>"
                    + "<tr>"
                    + "<td align=\"right\" valign=\"top\">" + etiquetaLocal + "</td>"
                    + "<td>"
                    + local
                // + "<br>BAIRRO " + $(this).find("NOM_BAIRRO").text()
                    + "</td>"
                    + "</tr>"
                    + "</tbody>"
                    + "</table>"
                    + "</td>"
                    + "</tr>");
                   qtdTotal++;
            });            
            if (qtdTotal > 1) {
                $("#contagem").html("Total encontrado: " + qtdTotal);
                exibirContagem();
            }
            exibirResultado();
        },
        error: function() {
            avisarErroServico();
            // consultarAlternativaZe();
        }
    })   
    return true;
}

function avisarNaoEncontrado() {  
    avisar("<br><b>Eleitor não encontrado.</b><br>&nbsp;");
}

function avisarErroServico() {  
    avisar("<br><b>Não foi possível comunicar-se com o serviço de Locais de Justificativa.</b><br>&nbsp;");
}

function avisar(texto) {
    $("#textoAviso").html(texto);   
    $("#aviso").show();
    esconderResultadoAlternativo();
    $("#espera").hide();                        
    $("#resultado").hide();                         
}

function exibirResultado() {  
    $("#aviso").hide();
    $("#espera").hide();                        
    $("#resultado").show("slow");                         
}

function esconderResultado() {  
    $("#aviso").hide();
    $("#espera").hide();                        
    $("#resultado").hide();                         
}

function exibirContagem() {    
    $("#linhaContagem").show("slow");                        
}
function esconderContagem() {    
    $("#linhaContagem").hide();                        
}

function exibirEspera() {
    $("#aviso").hide();
    $("#resultado").hide();            
    esconderResultadoAlternativo()
    $("#espera").show();                        
    esconderContagem();
}

function exibirResultadoAlternativo() {
    $("#resultadoAlternativo").show();
}

function esconderResultadoAlternativo() {
    $("#resultadoAlternativo").hide();
}

function obterNomeArquivoMunicipio() {
    $.ajax({
        type: "GET",
        url: "config/faixa.xml",
        data: "",
        async: false,
        success:     
            function (response) {                
            $(response).find("faixa>municipio").each(function () {
                /*            if (parseFloat($("#numMunicipio").val()) >= parseFloat($(this).attr("numInicial"))
                    && parseFloat($("#numMunicipio").val()) <= parseFloat($(this).attr("numFinal"))) {
                $("#nomArquivo").val($(this).attr("nomeArquivo"));
            } */
                var numMunic = $("#numMunicipio").val();
                while (numMunic.length < 3) {
                    numMunic = "0" + numMunic;
                }
                $("#nomArquivo").val($(this).attr("nomeArquivo") + numMunic + ".xml");        
            });
        },
        error: function() {
            avisarErroServico();
        }
    });   
    
    return ($("#nomArquivo").val());   
}

function obterNomeArquivoZe() {
    $.ajax({
        type: "GET",
        url: "config/faixa.xml",
        data: "",
        async: false,
        success:     
            function (response) {                
            $(response).find("faixa>ze").each(function () {
                /* window.alert("ZE float:" + parseFloat($("#numZe").val()));
            window.alert("ZE inicial FLOAT:" + parseFloat($(this).attr("numInicial")));
            window.alert("ZE final FLOAT:" + parseFloat($(this).attr("numFinal"))); */
                //    if (parseFloat($("#numZe").val()) >= parseFloat($(this).attr("numInicial"))
                //            && parseFloat($("#numZe").val()) <= parseFloat($(this).attr("numFinal"))) {                
                /* window.alert("Esta ZE: está neste arquivo" + $(this).attr("nomeArquivo")); */
                //        $("#nomArquivo").val($(this).attr("nomeArquivo"));
                //    }        
                var numZe = $("#numZe").val();
                while (numZe.length < 3) {
                    numZe = "0" + numZe;
                }
                $("#nomArquivo").val($(this).attr("nomeArquivo") + numZe + ".xml");        
        
            });
        },
        error: function() {
            avisarErroServico();
        }
    });   
    
    return ($("#nomArquivo").val());
}

function obterNomeArquivoAlternativoMunicipio() {
    $.ajax({
        type: "GET",
        url: "config/faixa.xml",
        data: "",
        async: false,
        success:     
            function (response) {                
            $(response).find("faixa>municipio_alt").each(function () {
                /*            if (parseFloat($("#numMunicipio").val()) >= parseFloat($(this).attr("numInicial"))
                    && parseFloat($("#numMunicipio").val()) <= parseFloat($(this).attr("numFinal"))) {
                $("#nomArquivo").val($(this).attr("nomeArquivo"));
            } */
                //window.alert("Nome do arquivo FONTE:" + $(this).attr("nomeArquivo") + parseInt($("#numMunicipio").val()) + ".htm");
                $("#nomArquivo").val($(this).attr("nomeArquivo") + parseInt($("#numMunicipio").val()) + ".htm");        
            });
        },
        error: function() {
            avisarErroServico();
        }
    });   
    //window.alert("Nome do arquivo HTML: " + $("#nomArquivo").val());
    return ($("#nomArquivo").val());   
}

function obterNomeArquivoAlternativoZe() {
    $.ajax({
        type: "GET",
        url: "config/faixa.xml",
        data: "",
        async: false,
        success:     
            function (response) {                
            $(response).find("faixa>ze_alt").each(function () {
                /* window.alert("ZE float:" + parseFloat($("#numZe").val()));
            window.alert("ZE inicial FLOAT:" + parseFloat($(this).attr("numInicial")));
            window.alert("ZE final FLOAT:" + parseFloat($(this).attr("numFinal"))); */
                //    if (parseFloat($("#numZe").val()) >= parseFloat($(this).attr("numInicial"))
                //            && parseFloat($("#numZe").val()) <= parseFloat($(this).attr("numFinal"))) {                
                /* window.alert("Esta ZE: está neste arquivo" + $(this).attr("nomeArquivo")); */
                //        $("#nomArquivo").val($(this).attr("nomeArquivo"));
                //    }
                //window.alert("Nome do arquivo: FONTE " + $(this).attr("nomeArquivo") + parseInt($("#numZe").val()) + ".htm");
                $("#nomArquivo").val($(this).attr("nomeArquivo") + parseInt($("#numZe").val()) + ".htm");        
            });
        },
        error: function() {
            avisarErroServico();
        }
    });   
    //window.alert("Nome do arquivo: HTML " + $("#nomArquivo").val());
    return ($("#nomArquivo").val());
}

function consultarAlternativaMunicipio() {
    exibirEspera();

    $.ajax({
        type: "GET",
        url: "" + obterNomeArquivoAlternativoMunicipio(),
        data: "",
        async: true,        
        datatype: "xml",
        success:
            function (response) {
            //window.alert("1:  Rodou o serviço alternativo para Municípios!");
            $("#textoExplicativo").html("Entre em contato com alguma das Zonas Eleitorais abaixo:")
            $("#resultadoAlternativo").attr({ src: "" + obterNomeArquivoAlternativoMunicipio() }); 
            //window.alert("Alternativo por Município \n" + $(response).text());
            //$("#corpoResultado").html("");
            // window.alert("Alternativo: Município" + $(response).find("mrj").find("COD_MUNICIPIO").text());
            //window.alert("Alternativo: Município");
            //window.alert("filtro:\n" + "mrj>NUMERO:('" + $("#numMunicipio").val() + "')");
            // $(response).find("mrj").filter(function () { return ($(this).find("COD_MUNICIPIO").text() == $("#numMunicipio").val()) }).each(function(){
            /* $(response).find("html").each(function(){
                window.alert("texto do XML: \n" + $(this).text());
                $("#corpoResultado").append("");
            });*/
            exibirResultadoAlternativo();
            exibirResultado();
        }     
        , error: function() {
            avisarErroServico();
        }    
    });
}  

function consultarAlternativaZe() {
    exibirEspera();
    $.ajax({
        type: "GET",
        url: "" + obterNomeArquivoAlternativoZe(),
        data: "",
        datatype: "xml",
        async: true,
        success:     
            function (response) {            
            // window.alert("Alternativo HTML - por ZE\n" + $(response).text());        
            //window.alert("1:  Rodou o serviço alternativo para ZE!");  
            $("#resultadoAlternativo").attr({ src: "" + obterNomeArquivoAlternativoZe() }); 
            $("#textoExplicativo").html("Entre em contato com alguma das Zonas Eleitorais abaixo:")
            //window.alert("1:  Rodou o serviço!");            
            //window.alert("Alternativo: ZE");        
            //$("#corpoResultado").html("");
            //$("#resultado").html($(response).text());            
            //window.alert("filtro:\n" + "mrj>NUMERO:('" + $("#numZe").val() + "')");
            // $(response).find("mrj").filter(function () { return ($(this).find("NUMERO").text() == $("#numZe").val()) }).each(function(){
            /* $(response).find  ("html").each(function(){
                window.alert("texto do XML: \n" + $(this).text());
                $("#corpoResultado").append("");
            });*/
            exibirResultadoAlternativo()
            exibirResultado();
        },
        error: function() {
            avisarErroServico();
        }
    })   
}

