﻿var NUM_DIGITOS_CNPJ = 14;
var NUM_DIGITOS_CPF = 11;


String.prototype.lpad = function(pSize, pCharPad) {
    var str = this;
    var dif = pSize - str.length;
    var ch = String(pCharPad).charAt(0);
    for (; dif > 0; dif--) str = ch + str;
    return (str);
}



String.prototype.trim = function() {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
function unformatNumber(pNum) {
    return String(pNum).replace(/\D/g, "").replace(/^0+/, "");
}

function formatCpfCnpj(pCpfCnpj, pUseSepar, pIsCnpj) {
    if (pIsCnpj == null) pIsCnpj = false;
    if (pUseSepar == null) pUseSepar = true;
    var maxDigitos = pIsCnpj ? NUM_DIGITOS_CNPJ : NUM_DIGITOS_CPF;
    var numero = unformatNumber(pCpfCnpj);

    numero = numero.lpad(maxDigitos, '0');
    if (!pUseSepar) return numero;

    if (pIsCnpj) {
        reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
        numero = numero.replace(reCnpj, "$1.$2.$3/$4-$5");
    }
    else {
        reCpf = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
        numero = numero.replace(reCpf, "$1.$2.$3-$4");
    }
    return numero;
}

function dvCpfCnpj(pBase, pIsCnpj) {
    if (pIsCnpj == null) pIsCnpj = false;
    var i, j, k, soma, dv;
    var cicloPeso = pIsCnpj ? 8 : NUM_DIGITOS_CPF;
    var maxDigitos = pIsCnpj ? NUM_DIGITOS_CNPJ : NUM_DIGITOS_CPF;
    var calculado = formatCpfCnpj(pBase, false, pIsCnpj);
    calculado = calculado.substring(2, maxDigitos);
    var result = "";

    for (j = 1; j <= 2; j++) {
        k = 2;
        soma = 0;
        for (i = calculado.length - 1; i >= 0; i--) {
            soma += (calculado.charAt(i) - '0') * k;
            k = (k - 1) % cicloPeso + 2;
        }
        dv = 11 - soma % 11;
        if (dv > 9) dv = 0;
        calculado += dv;
        result += dv
    }

    return result;
}

function isCpf(pCpf, alerta) {
    var numero = formatCpfCnpj(pCpf, false, false);
    var base = numero.substring(0, numero.length - 2);
    var digitos = dvCpfCnpj(base, false);
    var algUnico, i;


    if (numero != base + digitos) {
        exibeAlerta("Alerta", alerta);
        return false;
    }


    algUnico = true;
    for (i = 1; i < NUM_DIGITOS_CPF; i++) {
        algUnico = algUnico && (numero.charAt(i - 1) == numero.charAt(i));
    }

    return (!algUnico);

}


function isCnpj(pCnpj, alerta) {
    var numero = formatCpfCnpj(pCnpj, false, true);
    var base = numero.substring(0, 8);
    var ordem = numero.substring(8, 12);
    var digitos = dvCpfCnpj(base + ordem, true);
    var algUnico;

    if (numero != base + ordem + digitos) {
        exibeAlerta("Alerta", alerta);
        return false;
    }

    algUnico = numero.charAt(0) != '0';
    for (i = 1; i < 8; i++) {
        algUnico = algUnico && (numero.charAt(i - 1) == numero.charAt(i));
    }
    if (algUnico) return false;

    if (ordem == "0000") return false;
    return (base == "00000000"
		|| parseInt(ordem, 10) <= 300 || base.substring(0, 3) != "000");
}

function isCpfCnpj(pCpfCnpj) {
    var numero = pCpfCnpj.replace(/\D/g, "");
    if (numero.length > NUM_DIGITOS_CPF)
        return isCnpj(pCpfCnpj)
    else
        return isCpf(pCpfCnpj);
}

// FILTRO DE NÚMEROS
function valida_numeros(s) {
    var i;
    var dif = 0;
    for (i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (!((c >= "0") && (c <= "9") || (c == ".") || (c == ",") || (c == "-"))) {
            dif = 1;
        }
    }
    if (dif == 1) {
        return false;
    }
    return true;
}

function valida_numeros_moeda(s, alerta) {
    var i;
    var dif = 0;
    for (i = 0; i < s.value.length; i++) {
        var c = s.value.charAt(i);
        if (!((c >= "0") && (c <= "9") || (c == ","))) {
            dif = 1;
        }
    }
    if (dif == 1) {
        exibeAlerta("Alerta", alerta);
        s.focus();
        return true;
    }
    //alert(alerta);
    return false;

}

function formata_a_moeda(campo) {
    if (campo.indexOf(",", 0) == -1 && campo.indexOf(".", 0) == -1) {
        campo = campo + ",00";
        return campo;
    } else {
        if (campo.indexOf(".", 0) != -1) {
            decimal = campo.substring(campo.indexOf(".", 0) + 1, campo.length)
        }
        if (campo.indexOf(",", 0) != -1) {
            decimal = campo.substring(campo.indexOf(",", 0) + 1, campo.length)
        }
        if (decimal.length == 1 && decimal != 0) {
            campo = eval(campo) + "0";
        }
        if (decimal.length == 1 && decimal == 0) {
            campo = campo + "0";
        }
        if (decimal.length == 0 && decimal == 0) {
            campo = campo + "00";
        }
        return campo;
    }
}

function valida_numeros_cpf(s, alerta) {
    var i;
    var dif = 0;
    for (i = 0; i < s.value.length; i++) {
        var c = s.value.charAt(i);
        if (!((c >= "0") && (c <= "9") || (c == ".") || (c == "/") || (c == "-"))) {
            dif = 1;
        }
    }
    if (dif == 1) {
        exibeAlerta("Alerta", alerta);
        s.focus();
        return true;
    }
    //alert(alerta);
    return false;

}

function valida_numeros_apenas(s, alerta) {
    var i;
    var dif = 0;
    for (i = 0; i < s.value.length; i++) {
        var c = s.value.charAt(i);
        if (!((c >= "0") && (c <= "9"))) {
            dif = 1;
        }
    }
    if (dif == 1) {
        exibeAlerta("Alerta", alerta);
        s.focus();
        return true;
    }

    return false;

}

function valida_letra_apenas(s, alerta) {
    var i;
    var dif = 0;
    for (i = 0; i < s.value.length; i++) {
        var c = s.value.charAt(i);
        if (((c >= "0") && (c <= "9"))) {
            dif = 1;
        }
    }
    if (dif == 1) {
        exibeAlerta("Alerta", alerta);
        s.focus();
        return true;
    }

    return false;

}


// QUANTIDADE NO CAMPO
function conta_espaco(campo, num1, num2, alerta) {
    var dif_new = 0;
    var i;
    for (i = num1; i <= num2; i++) {
        if (campo.value.length == i)
        { dif_new = 1 }
    }
    if (dif_new != 1) {
        exibeAlerta("Alerta", alerta);
        campo.focus();
        return true;
    }
}

// LIMITA VALOES
function entre_numeros(campo, num1, num2, alerta) {
    if (campo.value < num1 || campo.value > num2) {
        exibeAlerta("Alerta", alerta);
        campo.focus();
        return true;
    }
}

// DATA DE SAIDA MAIOR QUE A DATA DE ENTRADA
function saida_menor(dia1, mes1, ano1, dia2, mes2, ano2, alerta) {
    if (ano2.value < ano1.value) {
        exibeAlerta("Alerta", alerta);
        ano2.focus();
        return true;
    }
    else {
        if (ano2.value == ano1.value) {
            if (mes2.value < mes1.value) {
                exibeAlerta("Alerta", alerta);
                mes2.focus();
                return true;
            }
            else {
                if (mes2.value == mes1.value) {
                    if (dia2.value < dia1.value) {
                        exibeAlerta("Alerta", alerta);
                        dia2.focus();
                        return true;
                    }
                }
            }
        }
    }
}

// PASSA CAMPO
function passa_campo(campo1, campo2, limite) {
    if (campo1.value.length >= limite) {
        campo2.focus();
        return true;
    }
}

// CONFERE INVALIDOS CARCTERES
function problema(campo) {
    invalidChars = "~'"
    for (i = 0; i < invalidChars.length; i++) {
        badChar = invalidChars.charAt(i)
        if (campo.value.indexOf(badChar) != -1) {
            //alert(mens2+badChar+mens2A)
            campo.select();
            return true;
        }
    }
}

// CONFERE FORMULÁRIOS MOEDA
function confere_moeda(campo) {
    if (campo.value.indexOf(".") != -1) {
        alert("Não é necessário inserir pontos.\nCaso esteja usando para separar os centavos, substitua o '.'(ponto) por ','(vírgula).");
        campo.focus();
        return true;
        return;
    }
    if (campo.value.indexOf(",") == -1) {
        alert("Ponha a vírgula e depois os centavos. Ex: ',00'.");
        campo.focus();
        return true;
        return;
    }
    pos01 = campo.value.indexOf(",") + 1
    str = campo.value.substring(pos01, campo.value.length)
    if (str.indexOf(",") != -1) {
        alert("Não é permitido mais que 01 vírgula no preço.");
        campo.focus();
        return true;
        return;
    }
}

// CONFERE FORMULÁRIOS
function confere(campo, alerta) {

    if (campo) {

        if (campo.value == "") {
            exibeAlerta("Alerta", alerta);
            campo.focus();
            return true;
        }
        if (problema(campo) == true) {
            exibeAlerta("Alerta", "Existem alguns caracteres que não são válidos");
            campo.focus();
            return true;
        }

    }
}

function confere_numerico(campo, alerta) {
    if (campo.value.length == 0) {
        exibeAlerta("Alerta", "Existem alguns caracteres que não são válidos");
        campo.focus();
        return true;
    }
}

// COMPARA CAMPOS
function compara(campo1, campo2, alerta) {
    if ((campo1) && (campo2)) {
        if (campo1.value != campo2.value) {
            exibeAlerta("Alerta", alerta);
            campo2.focus();
            return true;
            return;
        }
    }
}

// CONFERE E-MAIL
function confere_email(campo) {
    mens1 = "Por favor, coloque o seu e-mail. Você precisará dele para acessar o acesso restrito."
    mens2 = "Caracter "
    mens2A = " inválido no seu e-Mail."
    mens2c = "Carater inválido na sua senha."
    mens3 = "O e-mail digitado deve possuir @"
    mens4 = "Mais de uma @ no seu e-Mail"
    mens5 = "O '.' não pode estar logo após a @ "
    mens6 = "Por favor, confira o seu e-mail, deve haver pelo menos um '.' após a '@'."
    mens7 = "Por favor, confira o seu e-mail, deve haver algum complemento após o primeiro ponto (exemplo@uec.com)."
    mens10 = "e-Mails não podem ter espaços."
    if (campo.value == "") {
        alert(mens1);
        campo.select();
        return true;
    }
    invalidChars = "/:,;><^~{}]='%\"[¨&*|+()"
    for (i = 0; i < invalidChars.length; i++) {
        badChar = invalidChars.charAt(i)

        if (campo.value.indexOf(badChar) != -1) {
            alert(mens2 + badChar + mens2A)
            campo.select();
            return true;
        }
    }
    atPos = campo.value.indexOf("@")
    if (atPos == -1) {
        alert(mens3);
        campo.select();
        return true;
    }
    x = campo.value.indexOf("@");
    variavel = campo.value;
    aux_email = variavel.substring(x + 1, variavel.length);
    if (aux_email.indexOf("@") != -1) {
        alert(mens4);
        campo.select();
        return true;
    }

    x = campo.value.indexOf("@");
    variavel = campo.value;
    aux_email = variavel.substring(x + 1, x + 2);
    if (aux_email == ".") {
        alert(mens5);
        campo.select();
        return true;
    }

    x = campo.value.indexOf(" ");
    if (x != "-1") {
        alert(mens10);
        campo.select();
        return true;
    }

    periodPos = campo.value.indexOf(".", atPos)
    if (periodPos == -1) {
        alert(mens6);
        campo.select();
        return true;
    }
    if (periodPos + 3 > campo.value.length) {
        alert(mens7);
        campo.select();
        return true;
    }
}


// ABRE POP-UP
function abre_a_foto(pagina, nome, sb, larg, altu) {
    window.open(pagina, nome, "resizable=no,toolbar=no,status=no,menubar=no,scrollbars=" + sb + ",width=" + larg + ",height=" + altu)
}

// AUMENTAR / DIMINUIR - CAIXA DE TEXTO
function alter_box_height(boxid, pixelvalue) {
    var box = fetch_object(boxid);
    var boxheight = parseInt(box.style.height);
    var newheight = boxheight + pixelvalue;
    if (newheight > 0) {
        box.style.height = newheight + "px";
    }
    return false;
}
