﻿//Inverte o valor da propriedade "visible" de um objeto
function InverteVisibilidade(obj) {
    if (obj != null)
        if (obj != "")
        document.getElementById(obj).style.display = (document.getElementById(obj).style.display != "none") ? "none" : "block";
}
//Mostra um determinado objeto e some com o outro
function AlternaVisibilidade(objMostra, objSome) {
    if (objMostra != null)
        if (objMostra != "")
        document.getElementById(objMostra).style.display = 'block';
    if (objSome != null)
        if (objSome != "")
        document.getElementById(objSome).style.display = 'none';
}

//Focaliza um campo
function Focaliza(objID) {
    if (document.getElementById(objID) != null)
        if (!document.getElementById(objID).disabled)
        document.getElementById(objID).focus();
}

//Abre uma Janela customizada por parametros
function OpenWin(
	url,
	name,
	width,
	height,
	left,
	top,
	scroll,
	resizable,
	status,
	menubar,
	toolbar,
	location) {
    try {
        if (top == null && left == null) {
            left = ((window.screen.availWidth / 2) - (width / 2));
            top = ((window.screen.availHeight / 2) - (height / 2));
        }
        var oWin = window.open(url, name, "width=" + width + ",height=" + height + ",left=" + left + ",top=" + top + ",scrollbars=" + scroll + ",resizable=" + resizable + ",status=" + status + ",menubar=" + menubar + ",toolbar=" + toolbar + ",location=" + location);
        oWin.focus();
    }
    catch (e) {
        alert(e);
    }
}

//Máscaras : Inicio
function ConsisteNumero_onKeyDown(e) {
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode != 13 && whichCode != 8 && whichCode != 9 && whichCode != 16 && whichCode != 17 && whichCode != 18 && whichCode != 20 && whichCode != 35 && whichCode != 36 && whichCode != 37 && whichCode != 38 && whichCode != 39 && whichCode != 40 && whichCode != 46 && whichCode != 91 && whichCode != 93 && whichCode != 116) {
        if (whichCode < 48 || (whichCode > 57 && (whichCode < 96 || whichCode > 105))) {
            if (e.returnValue) {
                e.returnValue = false;
                e.cancelBubble = true;
            }
            if (e.preventDefault) {
                e.preventDefault();
                e.stopPropagation();
            }
        }
    }
}

function ConsisteNumero_onKeyUp(obj) {
    str = obj.value;
    for (i = 0; i < str.length; i++) {
        ch = str.charCodeAt(i);
        if (ch <= 42 || ch == 60 || ch == 64 || ch >= 91)
            str = str.replace(str.charAt(i), "");
    }
    if (str != obj.value) obj.innerText = str;
}

function ConsisteCPF_onKeyUpDown(obj) {
    if (event.keyCode == 8)
        return false;

    var vr = obj.value;
    var tam = vr.length;
    if (tam == 3) obj.value += ".";
    if (tam == 7) obj.value += ".";
    if (tam == 11) obj.value += "-";
}

function ConsisteCNPJ_onKeyUpDown(obj) {
    if (event.keyCode == 8)
        return false;

    var vr = obj.value;
    var tam = vr.length;
    if (tam == 2) obj.value += ".";
    if (tam == 6) obj.value += ".";
    if (tam == 10) obj.value += "/";
    if (tam == 15) obj.value += "-";

}

function ConsisteMoney_onKeyPress(objTextBox, SeparadorMilesimo, SeparadorDecimal, e) {
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
    key = String.fromCharCode(whichCode);
    if (strCheck.indexOf(key) == -1) return false;
    len = objTextBox.value.length;
    for (i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for (; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i)) != -1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0' + SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0' + SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
            objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
}
function ConsisteMoneyAux_onKeyPress(obj) {
    if (obj.value.length >= obj.maxLength)
        obj.value = obj.value.substr(1, obj.maxLength);
}

function ConsisteData_onKeyUp(obj, e) {
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 193 || (whichCode >= 48 && whichCode <= 57) || (whichCode >= 96 && whichCode <= 105) || whichCode == 8 || whichCode == 9 || whichCode == 13 || whichCode == 16 || whichCode == 17 || whichCode == 18 || whichCode == 20 || whichCode == 32 || whichCode == 35 || whichCode == 36 || whichCode == 37 || whichCode == 38 || whichCode == 39 || whichCode == 40 || whichCode == 46 || whichCode == 91 || whichCode == 93 || whichCode == 116) {
        vr = obj.value;
        if (vr.length == 1) {
            if (!((whichCode >= 48 && whichCode <= 51) || (whichCode >= 96 && whichCode <= 99)))
            { obj.value = obj.value.substring(0, obj.value.length - 1); }
        }
        else {
            if (vr.length == 2) {
                if (!((whichCode >= 48 && whichCode <= 105) || (whichCode >= 96 && whichCode <= 105)))
                { obj.value += vr.substr(0, vr.length - 1); }
                else
                { obj.value += vr + "/"; }
            }
            if (vr.length == 5) {
                if (!((whichCode >= 48 && whichCode <= 105) || (whichCode >= 96 && whichCode <= 105)))
                { obj.value += vr.substr(0, vr.length - 1); }
                else
                { obj.value += vr + "/"; }
            }
        }

        if ((vr.substr(0, 2) > 31) || (vr.substr(0, 2) == "00"))
        { obj.value = obj.value.substring(0, obj.value.length - 1); obj.focus(); }

        if ((vr.substr(3, 2) > 12) || (vr.substr(3, 2) == "00") || (vr.substr(3, 1) == " ") || (vr.substr(3, 2) == "  "))
        { obj.value = obj.value.substring(0, obj.value.length - 1); obj.focus(); }

        if (((vr.substr(3, 2) == 04) || (vr.substr(3, 2) == 06) || (vr.substr(3, 2) == 09) || (vr.substr(3, 2) == 11)) & (vr.substr(0, 2) == 31))
        { obj.value = obj.value.substring(0, obj.value.length - 2); obj.focus(); }

        if ((vr.substr(3, 2) == 02) && (vr.substr(0, 2) > 29))
        { obj.value = obj.value.substring(0, obj.value.length - 2); obj.focus(); }

        if (vr.length >= 8)
            if (vr.substr(6, 2) < 19)
            obj.value = obj.value.substring(0, obj.value.length - 1);

        if (vr.length > 10)
        { obj.value = vr.substr(0, 10); }
    }
    else {
        obj.value = obj.value.substring(0, obj.value.length - 1);
    }
}

function ConsisteData_onBlur(obj) {
    var vr = obj.value;

    if (vr.length > 10)
    { obj.innerText = vr.substr(0, 10); }

    if ((vr.length < 10) && (vr.length > 1))
    { obj.focus(); }

    if (vr.length == 1)
    { obj.innerText = ""; }
}

function ConsisteHora_onKeyUpDown(obj) {
    var tecla = event.keyCode;

    if ((tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) || tecla == 46 || tecla == 8 || tecla == 35 || tecla == 36 || tecla == 17 || tecla == 18 || tecla == 9)
        event.returnValue = true;
    else
        event.returnValue = false;

    if (obj.value.length == 2 && (tecla != 46 && tecla != 8 && tecla != 35 && tecla != 36 && tecla != 17 && tecla != 18 && tecla != 9))
        obj.value += ":";

    if (obj.value.length > 2) {
        var hrs = obj.value.substring(0, 2);
        if ((hrs < 00) || (hrs > 23))
            obj.value = "";
    }
    if (obj.value.length > 4) {
        var min = obj.value.substring(3, 5);
        if (min < "00" || min > "59")
            obj.value = "";
    }
}

function MM_formtCep(e, src, mask) {
    if (window.event) {
        _TXT = e.keyCode;
    }
    else if (e.which) {
        _TXT = e.which;
    }
    if (_TXT > 47 && _TXT < 58) {
        var i = src.value.length; var saida = mask.substring(0, 1); var texto = mask.substring(i)
        if (texto.substring(0, 1) != saida) {
            src.value += texto.substring(0, 1);
        }
        return true;
    }
    else {
        if (_TXT != 8) {
            return false;
        }
        else {
            return true;
        }
    }
}

function MascaraFone(keypress, objeto) {
    campo = eval(objeto);
    // telefone
    separador1 = '(';
    separador2 = ')';
    separador3 = '-';
    conjunto1 = 0;
    conjunto2 = 3;
    conjunto3 = 8;
    if (campo.value.length == conjunto1) {
        campo.value = campo.value + separador1;
    }
    if (campo.value.length == conjunto2) {
        campo.value = campo.value + separador2;
    }
    if (campo.value.length == conjunto3) {
        campo.value = campo.value + separador3;
    }
}


//Máscaras : Fim

//Utilizado para controlar o maxlenth de campos como textarea
function ConsisteMaxLength_onKeyUp(obj, maxlength) {
    if (obj.value.length >= maxlength)
        obj.value = obj.value.substring(0, maxlength);
}

//Auxiliares : Inicio
function SetCookie(sName, sValue) {
    var today = new Date();
    var expires = new Date(today.getTime() + (1 * 86400000));
    document.cookie = sName + "=" + escape(sValue) + ";expires=" + expires + ";";
}

function GetCookie(sName) {
    var aCookie = document.cookie.split("; ");
    for (var i = 0; i < aCookie.length; i++) {
        var aCrumb = aCookie[i].split("=");
        if (sName == aCrumb[0])
            return unescape(aCrumb[1]);
    }

    return null;
}

function Trim(s) {
    while (s.search(" ") != -1)
        s = s.replace(" ", "");

    return (s);
}

function IsEmpty(vr) {
    return (Trim(vr) == "") ? false : true;
}

function IsNumeric(vr) {
    var ValidChars = "0123456789.-+/*,";
    var IsNumber = true;

    if (vr == "")
        return false;

    for (i = 0; i < vr.length && IsNumber == true; i++)
        if (ValidChars.indexOf(vr.charAt(i)) == -1)
        IsNumber = false;

    return IsNumber;
}

function IsDate(vr) {
    var sArrDate = vr.split("/");
    var sDateVal = new Date(sArrDate[1] + "/" + sArrDate[0] + "/" + sArrDate[2]);
    return (isNaN(sDateVal)) ? false : true;
}

// Exclusão em lote
function checarTodos(sender, e) {
    var sel = window.document.getElementsByTagName('input');
    var i = 0;
    for (i = 0; i < ((sel != null) ? sel.length : 0); i++)
        if (sel[i].type == 'checkbox' && sel[i].id.indexOf(e.container) == 0 && sel[i].id != sender.id)
        sel[i].checked = sender.checked;
}

function confirmarExclusaoLote(sender, e) {
    var sel = window.document.getElementsByTagName('input');
    var i = 0, existeSelecionado = false;
    for (i = 0; i < ((sel != null) ? sel.length : 0); i++)
        if (existeSelecionado = (sel[i].type == 'checkbox' && sel[i].id.indexOf(e.container) == 0 && sel[i].checked))
        break;

    return (existeSelecionado && window.confirm(e.message));
}

// Modal/Popup
function showModal(painel) {
    if (painel && painel.Show && typeof (painel.Show) == 'function')
        painel.Show();
    return (!painel);
}

//Auxiliares : Fim

//Funções adicionadas por usuários
//Wilberson - 14/08/2008

function mascara(src, mask) {
    var i = src.value.length;
    var saida = mask.substring(i, i + 1);
    var ascii = event.keyCode;

    if (saida == "B") //Não aceita número como entrada no teclado
    {
        if ((ascii < 48) && (ascii > 57)) {
            event.keyCode -= 32;
        }
        else {
            event.keyCode = 0;
        }
    } else
        if (saida == "A") //Aceita somente letras do alfabeto e maiúsculas como entrada no teclado
    {
        if ((ascii >= 97) && (ascii <= 122)) {
            event.keyCode -= 32;
        }
        else {
            event.keyCode = 0;
        }
    } else
        if (saida == "0") //Aceita somente números como entrada no teclado
    {
        if ((ascii >= 48) && (ascii <= 57)) {
            return
        }
        else {
            event.keyCode = 0
        }
    }
    else //Aceita qualquer entrada no teclado
        if (saida == "#") {
        return;
    }
    else {
        src.value += saida;
        i += 1
        saida = mask.substring(i, i + 1);
        if (saida == "A") {
            if ((ascii >= 97) && (ascii <= 122)) {
                event.keyCode -= 32;
            } else {
                event.keyCode = 0;
            }
        } else
            if (saida == "0") {
            if ((ascii >= 48) && (ascii <= 57)) {
                return
            } else {
                event.keyCode = 0
            }
        } else {
            return;
        }
    }
}

//Abre uma Janela customizada por parametros
function OpenWin(
	url,
	name,
	width,
	height,
	left,
	top,
	scroll,
	resizable,
	status,
	menubar,
	toolbar,
	location) {
    if (top == null && left == null) {
        left = ((window.screen.availWidth / 2) - (width / 2));
        top = ((window.screen.availHeight / 2) - (height / 2));
    }
    var oWin = window.open(url, name, "width=" + width + ",height=" + height + ",left=" + left + ",top=" + top + ",scrollbars=" + scroll + ",resizable=" + resizable + ",status=" + status + ",menubar=" + menubar + ",toolbar=" + toolbar + ",location=" + location);
    oWin.focus();
}

function formatar(objeto, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen, bolMask, sCod, nTecla;
    if (document.all) { // Internet Explorer
        nTecla = evtKeyPress.keyCode;
    }
    else if (document.layers) { // Nestcape
        nTecla = evtKeyPress.which;
    }
    else {
        nTecla = evtKeyPress.which;
        if (nTecla == 8) {
            return true;
        }
    }

    sValue = objeto.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(")", "");
    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) == "/") || (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++;
    }

    objeto.value = sCod;

    if (nTecla != 8) { // backspace
        if (sMask.charAt(i - 1) == "9") { // apenas números...
            return ((nTecla > 47) && (nTecla < 58));
        }
        else { // qualquer caracter...
            return true;
        }
    }
    else {
        return true;
    }
}

function ChecarCPF(sender, args) {
    var bValida = true;
    // captura o valor para validação e remove os caracteres não numéricos
    var cpf = args.Value.replace(/\D/gi, '');

    // verifica a quantidade de dígitos
    if (bValida && cpf.length < 9)
        bValida = false;

    // verifica se todos os dígitos são iguais
    var i = 0;
    var digitosIguais = true;
    for (i = 0; i < ((bValida) ? cpf.length - 1 : 0); i++)
        if (!(digitosIguais = (cpf.charAt(i) == cpf.charAt(i + 1))))
        break;

    if (digitosIguais)
        bValida = false;

    // executa algoritmo de validação de cpf, fase 1
    var add = 0, rev = 0;
    if (bValida) {
        for (i = 0; i < 9; i++)
            add += parseInt(cpf.charAt(i), 10) * (10 - i);
        rev = 11 - (add % 11);

        if (rev == 10 || rev == 11)
            rev = 0;

        if (rev != parseInt(cpf.charAt(9), 10))
            bValida = false;
    }

    // executa algoritmo de validação de cpf, fase 2
    if (bValida) {
        add = 0;
        for (i = 0; i < 10; i++)
            add += parseInt(cpf.charAt(i), 10) * (11 - i);
        rev = 11 - (add % 11);
        if (rev == 10 || rev == 11)
            rev = 0;
        if (rev != parseInt(cpf.charAt(10), 10))
            bValida = false;
    }

    args.IsValid = bValida;
}

function Mascara(o, f) {
    v_obj = o
    v_fun = f
    setTimeout("execmascara()", 1)
}

function execmascara() {
    v_obj.value = v_fun(v_obj.value)
}

function soNumeros(v) {
    return v.replace(/\D/g, "")
}

function Moeda(v) {
    v = v.replace(/\D/g, "") //Remove tudo o que não é dígito
    v = v.replace(/^([0-9]{3}\.?){3}-[0-9]{2}$/, "$1,$2");
    //v=v.replace(/(\d{3})(\d)/g,"$1,$2")
    v = v.replace(/(\d)(\d{2})$/, "$1,$2") //Coloca virgula antes dos 2 últimos digitos
    return v
}

function telefone(v) {
    v = v.replace(/\D/g, "")                 //Remove tudo o que não é dígito
    v = v.replace(/^(\d\d)(\d)/g, "($1)$2") //Coloca parênteses em volta dos dois primeiros dígitos
    v = v.replace(/(\d{4})(\d)/, "$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function horario(v) {
    v = v.replace(/\D/g, "") //Remove tudo o que não é dígito
    v = v.replace(/(\d)(\d{2})$/, "$1:$2") //Coloca  dois pontos antes dos 2 últimos digitos
    return v
}