/*Função que corrige um problema quando se utiliza mais de um objeto gridView ou FormView ou GridView, etc
Ao clicar, verifica se a tecla digitada foi enter, caso positivo, 
dispara o evento click do botão correspondente ao campo
*/
function configuraEnter(btnSubmit, evento) {
    if (evento.which || evento.keyCode) {
        if ((evento.which == 13) || (evento.keyCode == 13)) {
            btnSubmit.click();
            return false;
        }
    }
    else {
        return true;
    }
}

/*String que guarda o valor do campo antes de ser alterado*/
function formatarCampo(obj, sMask, evtKeyPress, bBloquearEnter) {
    var i, nCount, sValue, fldLen, mskLen, bolMask, sCod, nTecla;
    if (window.event) { // Internet Explorer
        nTecla = evtKeyPress.keyCode;
        teclaControl = event.ctrlKey;
    }
    else if (evtKeyPress.which) { // Nestcape / firefox
        nTecla = evtKeyPress.which;
        teclaControl = evtKeyPress.ctrlKey;
    }

    if ((nTecla >= 48 && nTecla <= 57) || (nTecla >= 96 && nTecla <= 105)) {

    }
    //Tab
    else if (nTecla == 9) {

    }

    // barras (/) para as datas
    else if (nTecla == 111 || nTecla == 193) {

    }
    else if (nTecla == 35) {

    }
    else if (nTecla == 36) {

    }
    else if (nTecla == 37) {

    }
    else if (nTecla == 39) {

    }
    //enter
    else if (nTecla == 13 && bBloquearEnter == false) {

    }
    //Ctrl
    else if (nTecla == 17) {

    }
    //alt
    else if (nTecla == 18) {

    }
    //windows
    else if (nTecla == 91 || nTecla == 92) {

    }
    //esc
    else if (nTecla == 27) {

    }
    //teclas F1 a F12 
    else if (nTecla >= 112 && nTecla <= 123) {

    }
    //Menu do teclado 
    else if (nTecla == 93) {

    }
    else if (nTecla == 46) {

    }
    //Áspas simples
    else if (nTecla == 109 || nTecla == 189) {

    }
    //número
    else if ((nTecla >= 48 && nTecla <= 57) || (nTecla >= 96 && nTecla <= 105)) {

    }
    else if (nTecla == 8) {
    }
    //PageUp,PageDown, Shift
    else if (nTecla == 33 || nTecla == 34 || nTecla == 16) {
    }
    //Verifica se o usuário está com o Control pressionado e em seguida verifica se as teclas
    //são V,C,X,Z usadas em funções como Colar, copiar, recortar e desfazer
    else if (teclaControl == true) {
        //V,C,X,Z
        if (nTecla == 86 || nTecla == 67 || nTecla == 88 || nTecla == 90) {

        }
    }
    else {
        return false;
    }

    if (nTecla != 8) {
        sValue = obj.value;
        // Limpa todos os caracteres de formatação que
        // já estiverem no campo.
        sValue = sValue.toString().replace("-", "");
        sValue = sValue.toString().replace("-", "");
        sValue = sValue.toString().replace(".", "");
        sValue = sValue.toString().replace(".", "");
        sValue = sValue.toString().replace("/", "");
        sValue = sValue.toString().replace("/", "");
        sValue = sValue.toString().replace("(", "");
        sValue = sValue.toString().replace("(", "");
        sValue = sValue.toString().replace(")", "");
        sValue = sValue.toString().replace(")", "");
        sValue = sValue.toString().replace(" ", "");
        sValue = sValue.toString().replace(" ", "");
        fldLen = sValue.length;
        mskLen = sMask.length;

        i = 0;
        nCount = 0;
        sCod = "";
        mskLen = fldLen;

        while (i <= mskLen) {
            bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
            bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

            if (bolMask) {
                sCod += sMask.charAt(i);
                mskLen++;
            }
            else {
                sCod += sValue.charAt(nCount);
                nCount++;
            }

            i++;
        }
        obj.value = sCod;
        return true;
    }
}
function integer_keyDown(obj, evtKeyPress) {
    var nTecla, teclaControl;
    if (window.event) { // Internet Explorer
        nTecla = evtKeyPress.keyCode;
        teclaControl = evtKeyPress.ctrlKey;
    }
    else if (evtKeyPress.which) { // Nestcape / firefox
        nTecla = evtKeyPress.which;
        teclaControl = evtKeyPress.ctrlKey;
    }

    if ((nTecla >= 48 && nTecla <= 57) || (nTecla >= 96 && nTecla <= 105)) {
        return true;
    }

    //Tab
    else if (nTecla == 9) {
        return true;
    }
    else if (nTecla == 35) {
        return true;
    }
    else if (nTecla == 36) {
        return true;
    }
    else if (nTecla == 37) {
        return true;
    }
    else if (nTecla == 39) {
        return true;
    }
    //enter
    else if (nTecla == 13) {
        return true;
    }
    //Ctrl
    else if (nTecla == 17) {
        return true;
    }
    //alt
    else if (nTecla == 18) {
        return true;
    }
    //windows
    else if (nTecla == 91 || nTecla == 92) {
        return true;
    }
    //esc
    else if (nTecla == 27) {
        return true;
    }
    //teclas F1 a F12 
    else if (nTecla >= 112 && nTecla <= 123) {
        return true;
    }
    //Menu do teclado 
    else if (nTecla == 93) {
        return true;
    }
    else if (nTecla == 46) {
        return true;
    }
    //número
    else if ((nTecla >= 48 && nTecla <= 57) || (nTecla >= 96 && nTecla <= 105)) {
        return true;
    }
    else if (nTecla == 8) {
        return true;
    }
    //PageUp,PageDown, Shift
    else if (nTecla == 33 || nTecla == 34 || nTecla == 16) {
        return true;
    }
    //Verifica se o usuário está com o Control pressionado e em seguida verifica se as teclas
    //são usadas em funções como Colar, copiar, recortar e desfazer
    else if (teclaControl == true) {
        //V,C,X,Z 
        if (nTecla == 86 || nTecla == 67 || nTecla == 88 || nTecla == 90) {
            return true;
        }
    }
    else {
        return false;
    }
}

/* Função que verifica se o campo atingiu os dígitos esperados e seta o foco para o campo informado no parâmetro*/
function setarFocus_keyUp(evento, obj, objSeguinte) {
    var nTecla;
    if (window.event) { // Internet Explorer
        nTecla = evento.keyCode;
    }
    else if (evento.which) { // Nestcape / firefox
        nTecla = evento.which;
    }
    //Verifica se é backspace, , , PageUp, PageDown, Shift
    if (nTecla != 9 && nTecla != 37 && nTecla != 39 && nTecla != 33 && nTecla != 34 && nTecla != 16) {
        if (obj.value.length == obj.maxLength) {
            objSeguinte.focus();
        }
    }
}

function mudarPropriedade(objId, theProp, theValue) { //v9.0
    var obj = null; with (document) {
        if (getElementById)
            obj = getElementById(objId);
    }
    if (obj) {
        if (theValue == true || theValue == false)
            eval("obj.style." + theProp + "=" + theValue);
        else
            eval("obj.style." + theProp + "='" + theValue + "'");
    }
}


function confirmarExclusao(sMsg) {
    if (confirm("Voc\u00ea tem certeza que deseja excluir " + sMsg)) {
        return true;
    }
    else {
        return false;
    }
}

function abrirJanela(url, nomeJanela, parametros) { //v2.0
    window.open(url, nomeJanela, parametros);
}

function validarCpf(sCpf, bAlert) {
    if (bAlert == undefined) {
        bAlert = true;
    }
    if (sCpf.length == 0) {
        alert("Informe o CPF.");
        return false;
    }
    else {
        var s;
        s = sCpf;
        s = s.replace("-", "");
        s = s.replace(".", "");
        s = s.replace(".", "");
        if (s.length != 11) {
            if (bAlert == true) {
                alert("CPF Inv\u00e1lido.");
            }
            return false;
        }
        else {
            var i;
            var c = s.substr(0, 9);
            var dv = s.substr(9, 2);
            var d1 = 0;
            for (i = 0; i < 9; i++) {
                d1 += c.charAt(i) * (10 - i);
            }
            if (d1 == 0) {
                if (bAlert == true) {
                    alert("CPF Inv\u00e1lido.");
                }
                return false;
            }
            else {
                d1 = 11 - (d1 % 11);
                if (d1 > 9) {
                    d1 = 0;
                }
                if (dv.charAt(0) != d1) {
                    if (bAlert == true) {
                        alert("CPF Inv\u00e1lido.");
                    }
                    return false;
                }
                else {
                    d1 *= 2;
                    for (i = 0; i < 9; i++) {
                        d1 += c.charAt(i) * (11 - i);
                    }
                    d1 = 11 - (d1 % 11);
                    if (d1 > 9) {
                        d1 = 0;
                    }
                    if (dv.charAt(1) != d1) {
                        if (bAlert == true) {
                            alert("CPF Inv\u00e1lido.");
                        }
                        return false;
                    }
                    else {
                        //Cpf válido   
                        return true;
                    }
                }
            }
        }
    }
}
/*Função que bloqueia a tecla enter, usada quando na mesma página existe os controles asp.net GridView e DetailsView*/
function bloquearEnter(evtKeyPress) {
    var nTecla;
    if (window.event) { // Internet Explorer
        nTecla = evtKeyPress.keyCode;
    }
    else if (evtKeyPress.which) { // Nestcape / firefox
        nTecla = evtKeyPress.which;
    }
    if (nTecla == 13) {
        return false;
    }
    else {
        return true;
    }
}


/*
Função: Formatar
Decrição: Formata o campo no formato monetário usando o evento onKeyDown
Parâmetros: campo, tammax, teclapres, casasDecimais
campo: objeto que contém a string
tammax: tamanho máximo do campo
teclapres: contém a tecla que foi pressionada
casasDecimais: quantidade de casas decimais
bBloquarEnter: variavel boolean que define se a tecla enter é bloqueada ou não
*/
function formatarValor(campo, tammax, teclaPres, casasDecimais, bBloquearEnter) {
    var tecla;
    if (window.event) { // Internet Explorer
        tecla = teclaPres.keyCode;
    }
    else if (teclaPres.which) { // Nestcape / firefox
        tecla = teclaPres.which;
    }
    if (!numValido(tecla)) {
        return false;
    }
    else {
        var vr = campo.value;
        while (vr.indexOf(",") >= 0 || vr.indexOf(".") >= 0) {
            vr = vr.replace(".", "");
            vr = vr.replace(",", "");
        }
        var tam = vr.length;
        var dec = casasDecimais;
        if (tam < tammax && tecla != 8) {
            tam = vr.length + 1;
        }
        if (tecla == 8) {
            tam = tam - 1;
        }
        if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105) {
            if (tam <= dec) {
                campo.value = vr;
            }
            if ((tam > dec) && (tam <= 5)) {
                campo.value = vr.substr(0, tam - 2) + "," + vr.substr(tam - dec, tam);
            }
            if ((tam >= 6) && (tam <= 8)) {
                campo.value = vr.substr(0, tam - 5) + "." + vr.substr(tam - 5, 3) + "," + vr.substr(tam - dec, tam);
            }
            if ((tam >= 9) && (tam <= 11)) {
                campo.value = vr.substr(0, tam - 8) + "." + vr.substr(tam - 8, 3) + "." + vr.substr(tam - 5, 3) + "," + vr.substr(tam - dec, tam);
            }
            if ((tam >= 12) && (tam <= 14)) {
                campo.value = vr.substr(0, tam - 11) + "." + vr.substr(tam - 11, 3) + "." + vr.substr(tam - 8, 3) + "." + vr.substr(tam - 5, 3) + "," + vr.substr(tam - dec, tam);
            }
            if ((tam >= 15) && (tam <= 17)) {
                campo.value = vr.substr(0, tam - 14) + "." + vr.substr(tam - 14, 3) + "." + vr.substr(tam - 11, 3) + "." + vr.substr(tam - 8, 3) + "." + vr.substr(tam - 5, 3) + "," + vr.substr(tam - 2, tam);
            }
        }
        return true;
    }
}
/*Fim da função formatar*/

function numValido(codTecla) {
    if (codTecla == 16 /* End*/ || codTecla == 36 /*Home*/ || codTecla == 16 /* Shift */ || codTecla == 18 /* Alt */ || codTecla == 8 /* Backspace */ || codTecla == 13 /* Enter */ || codTecla == 09 /* Tab */ || codTecla == 46 /* Del */ || (codTecla >= 48 && codTecla <= 57) /* Numeros */ || (codTecla >= 96 && codTecla <= 105) /* Numeros NUM */ || codTecla == 188 /* , */ || codTecla == 190 /* . */ || codTecla == 110 /* , (NUM) */ || codTecla == 194 /* . (NUM)*/ || (codTecla >= 37 && codTecla <= 40) /* setas */) {
        return true
    }
    else {
        return false;
    }
}

function formatarCampo_load(obj, sMask) {
    var sValue = obj.value;
    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace("-", "");
    sValue = sValue.toString().replace("-", "");
    sValue = sValue.toString().replace(".", "");
    sValue = sValue.toString().replace(".", "");
    sValue = sValue.toString().replace("/", "");
    sValue = sValue.toString().replace("/", "");
    sValue = sValue.toString().replace("(", "");
    sValue = sValue.toString().replace("(", "");
    sValue = sValue.toString().replace(")", "");
    sValue = sValue.toString().replace(")", "");
    sValue = sValue.toString().replace(" ", "");
    sValue = sValue.toString().replace(" ", "");
    var fldLen = sValue.length;
    var mskLen = sMask.length;
    var i = 0;
    var nCount = 0;
    var sCod = "";
    mskLen = fldLen;
    var bolMask;
    while (i <= mskLen) {
        bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
        bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

        if (bolMask) {
            sCod += sMask.charAt(i);
            mskLen++;
        }
        else {
            sCod += sValue.charAt(nCount);
            nCount++;
        }

        i++;
    }
    obj.value = sCod;
}
/*Função que muda o endereço da imagem*/
function mudarImagem(obj, sSrc) {
    obj.src = sSrc;
}
/*Função que retorna o valor de uma queryString*/
//variavel = unescape(getQueryString("xField"));
function getQueryString(field) {
    var queryString = window.location.search.substring(1);
    var queryPairs = queryString.split("&");
    for (var i = 0; i < queryPairs.length; i++) {
        var thisPair = queryPairs[i].split("=");
        if (thisPair[0] == field) {
            return thisPair[1];
        }
    }
    return false;
}


function esconderCalendario(oCalendario) {
    oCalendario.hide();
    oCalendario.get_element().blur();
}


function openAjax() {
    var Ajax;
    try {
        Ajax = new XMLHttpRequest(); // XMLHttpRequest para browsers mais populares, como: Firefox, Safari, dentre outros.
    } catch (ee) {
        try {
            Ajax = new ActiveXObject("Msxml2.XMLHTTP"); // Para o IE da MS
        } catch (e) {
            try {
                Ajax = new ActiveXObject("Microsoft.XMLHTTP"); // Para o IE da MS  
            }
            catch (e) {
                Ajax = false;
            }
        }
    }
    return Ajax;
}

function carregaAjax(sUrl, sMetodo, idObjRetorno, sParamOpcional) {
    if (document.getElementById) { // Para os browsers complacentes com o DOM W3C.
        if (sMetodo == undefined) {
            sMetodo = "GET";
        }
        var exibeResultado = document.getElementById(idObjRetorno); // div que exibirá o resultado.
        var Ajax = openAjax(); // Inicia o Ajax.
        Ajax.open(sMetodo, sUrl, true); // fazendo a requisição
        Ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Ajax.onreadystatechange = function () {
            if (Ajax.readyState == 1) { // Quando estiver carregando, exibe: carregando...
                exibeResultado.innerHTML = "<strong>Carregando...</strong>";
            }
            if (Ajax.readyState == 4) { // Quando estiver tudo pronto.
                if (Ajax.status == 200) {
                    var resultado = Ajax.responseText; // Coloca o retornado pelo Ajax nessa variável
                    resultado = resultado.replace(/\+/g, " "); // Resolve o problema dos acentos (saiba mais aqui: http://www.plugsites.net/leandro/?p=4)
                    resultado = unescape(resultado); // Resolve o problema dos acentos
                    exibeResultado.innerHTML = resultado;
                } else {
                    alert(Ajax.responseText);
                    exibeResultado.innerHTML = "Erro: " + Ajax.responseText;
                }
            }
        }
        if (sMetodo == "GET" || sParamOpcional == undefined) {
            Ajax.send(null); // submete sem parâmetros
        }
        else {
            Ajax.send(sParamOpcional); // submete com parâmetros
        }
    }
}
function bloqueiaMouse() {
    var mensagem = "";
    function clickIE() {
        if (document.all) {
            (mensagem);
            return false;
        }
    }
    function clickNS(e) {
        if (document.layers || (document.getElementById && !document.all)) {
            if (e.which == 2 || e.which == 3) {
                (mensagem);
                return false;
            }
        }
    }
    if (document.layers) {
        document.captureEvents(Event.MOUSEDOWN);
        document.onmousedown = clickNS;
    }
    else {
        document.onmouseup = clickNS; document.oncontextmenu = clickIE;
    }
    bloqueiaSelecao();
}
function bloqueiaSelecao() {
    function disableselect(e) {
        return false;
    }
    function reEnable() {
        return true;
    }
    //if IE4+
    document.onselectstart = new Function("return false");
    //if NS6
    if (window.sidebar) {
        document.onmousedown = disableselect;
        document.onclick = reEnable;
    }
    document.oncontextmenu = new Function("return false;");
}


function retiraPontuacao(sValor) {
    while (sValor.indexOf(".") >= 0) {
        sValor = sValor.replace(".", "");
    }
    while (sValor.indexOf("-") >= 0) {
        sValor = sValor.replace("-", "");
    }
    while (sValor.indexOf("_") >= 0) {
        sValor = sValor.replace("_", "");
    }
    while (sValor.indexOf("/") >= 0) {
        sValor = sValor.replace("/", "");
    }
    return sValor;
}

function imprimirNovaJanela(idObj) {
    var prtContent = document.getElementById(strid);
    var WinPrint = window.open('', '', 'letf=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status=0');
    WinPrint.document.write(prtContent.innerHTML);
    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();
    prtContent.innerHTML = strOldOne;
}

function limitaCaracteres_keyUp(txtLimitado, iQtdCaracteres, idObjQtdCaracteresRestantes) {
    txtLimitado.value = txtLimitado.value.substring(0, iQtdCaracteres);
    if (idObjQtdCaracteresRestantes != undefined) {
        document.getElementById(idObjQtdCaracteresRestantes).innerHTML = iQtdCaracteres - txtLimitado.value.length;
    }
}