// Formata o campo valor monetário 
function formataValor(campo, evt) {
    //1.000.000,00 
    evt = getEvent(evt);
    var tecla = getKeyCode(evt);
    if (!teclaValida(tecla))
        return;
    vr = campo.value = filtraNumeros(filtraCampo(campo));
    tam = vr.length;
    if (tam <= 2) {
        campo.value = vr;
    }
    if ((tam > 2) && (tam <= 5)) {
        campo.value = vr.substr(0, tam - 2) + ',' + vr.substr(tam - 2, tam);
    }
    if ((tam >= 6) && (tam <= 8)) {
        campo.value = vr.substr(0, tam - 5) + '.' + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, 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 - 2, 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 - 2, tam);
    }
    if ((tam >= 15) && (tam <= 18)) {
        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);
    }
}
// Formata data no padrão DD/MM/YYYY 
function formataData(campo, evt) {
    //dd/MM/yyyy 
    evt = getEvent(evt);
    var tecla = getKeyCode(evt);
    if (!teclaValida(tecla))
        return;
    vr = campo.value = filtraNumeros(filtraCampo(campo));
    tam = vr.length;
    if (tam >= 2 && tam < 4)
        campo.value = vr.substr(0, 2) + '/' + vr.substr(2);
    if (tam == 4)
        campo.value = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/';
    if (tam > 4)
        campo.value = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/' + vr.substr(4);
    //if (tam >= 5 && tam <= 10) 
    // campo.value = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/' + vr.substr(4, 4); 
}
// Formata só números 
function formataInteiro(campo, evt) {
    //1234567890 
    evt = getEvent(evt);
    var tecla = getKeyCode(evt);
    if (!teclaValida(tecla))
        return;
    campo.value = filtraNumeros(filtraCampo(campo));
}
// Formata hora no padrao HH:MM 
function formataHora(campo, evt) {
    //HH:mm 
    evt = getEvent(evt);
    var tecla = getKeyCode(evt);
    if (!teclaValida(tecla))
        return;
    vr = campo.value = filtraNumeros(filtraCampo(campo));
    if (tam == 2)
        campo.value = vr.substr(0, 2) + ':';
    if (tam > 2 && tam < 5)
        campo.value = vr.substr(0, 2) + ':' + vr.substr(2);
}
// Formata o campo quando é digitado somente o mês e o ano 
function formataMesAno(campo, evt) {
    //MM/yyyy 
    evt = getEvent(evt);
    var tecla = getKeyCode(evt);
    if (!teclaValida(tecla))
        return;
    vr = campo.value = filtraNumeros(filtraCampo(campo));
    tam = vr.length;
    if (tam > 2 && tam < 5)
        campo.value = vr.substr(0, tam - 2) + '/' + vr.substr(tam - 2, tam);
    if (tam >= 5 && tam <= 10)
        campo.value = vr.substr(0, 2) + '/' + vr.substr(2, 4);
}
// Formata o campo CNPJ 
function formataCNPJ(campo, evt) {
    //99.999.999/9999-99 
    evt = getEvent(evt);
    var tecla = getKeyCode(evt);
    if (!teclaValida(tecla))
        return;
    vr = campo.value = filtraNumeros(filtraCampo(campo));
    tam = vr.length;
    if (tam <= 2) {
        campo.value = vr;
    }
    if ((tam > 2) && (tam <= 6)) {
        campo.value = vr.substr(0, tam - 2) + '-' + vr.substr(tam - 2, tam);
    }
    if ((tam >= 7) && (tam <= 9)) {
        campo.value = vr.substr(0, tam - 6) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam);
    }
    if ((tam >= 10) && (tam <= 12)) {
        campo.value = vr.substr(0, tam - 9) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam);
    }
    if ((tam >= 13) && (tam <= 14)) {
        campo.value = vr.substr(0, tam - 12) + '.' + vr.substr(tam - 12, 3) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, 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);
    }
}
// Formata o campo CPF 
function formataCPF(campo, evt) {
    //999.999.999-99 
    evt = getEvent(evt);
    var tecla = getKeyCode(evt);
    if (!teclaValida(tecla))
        return;
    vr = campo.value = filtraNumeros(filtraCampo(campo));
    tam = vr.length;
    if (tam <= 2) {
        campo.value = vr;
    }
    if (tam > 2 && tam <= 5) {
        campo.value = vr.substr(0, tam - 2) + '-' + vr.substr(tam - 2, tam);
    }
    if (tam >= 6 && tam <= 8) {
        campo.value = vr.substr(0, tam - 5) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, 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 - 2, tam);
    }
}
// Formata campo flutuante, permite números e somente uma vírgula 
function formataDouble(campo, evt) {
    //18,53012 
    evt = getEvent(evt);
    var tecla = getKeyCode(evt);
    if (!teclaValida(tecla))
        return;
    campo.value = filtraNumerosComVirgula(campo.value);
}
// Formata campo telefone 
function formataTelefone(campo, evt) {
    //0000-0000 
    evt = getEvent(evt);
    var tecla = getKeyCode(evt);
    if (!teclaValida(tecla))
        return;
    vr = campo.value = filtraCampo(campo);
    tam = vr.length;
    if (tam <= 4)
        campo.value = vr;
    if (tam > 4)
        campo.value = vr.substr(0, tam - 4) + '-' + vr.substr(tam - 4, tam);
}
// Formata o campo CEP 
function formataCEP(campo, evt) {
    //312555-650 
    evt = getEvent(evt);
    var tecla = getKeyCode(evt);
    if (!teclaValida(tecla))
        return;
    vr = campo.value = filtraNumeros(filtraCampo(campo));
    tam = vr.length;
    if (tam <= 3)
        campo.value = vr;
    if (tam > 3)
        campo.value = vr.substr(0, tam - 3) + '-' + vr.substr(tam - 3, tam);
}
// Formata o campo Cartão de Crédito 
function formataCartaoCredito(campo, evt) {
    //0000.0000.0000.0000 
    evt = getEvent(evt);
    var tecla = getKeyCode(evt);
    if (!teclaValida(tecla))
        return;
    var vr = campo.value = filtraNumeros(filtraCampo(campo));
    var tammax = 16;
    var tam = vr.length;
    if (tam < tammax && tecla != 8)
    { tam = vr.length + 1; }
    if (tam < 5)
    { campo.value = vr; }
    if ((tam > 4) && (tam < 9))
    { campo.value = vr.substr(0, 4) + '.' + vr.substr(4, tam - 4); }
    if ((tam > 8) && (tam < 13))
    { campo.value = vr.substr(0, 4) + '.' + vr.substr(4, 4) + '.' + vr.substr(8, tam - 4); }
    if (tam > 12)
    { campo.value = vr.substr(0, 4) + '.' + vr.substr(4, 4) + '.' + vr.substr(8, 4) + '.' + vr.substr(12, tam - 4); }
}
// limpa todos os caracteres especiais do campo solicitado 
function filtraCampo(campo) {
    var s = "";
    var cp = "";
    vr = campo.value;
    tam = vr.length;
    for (i = 0; i < tam; i++) {
        if (vr.substring(i, i + 1) != "/"
&& vr.substring(i, i + 1) != "-"
&& vr.substring(i, i + 1) != "."
&& vr.substring(i, i + 1) != ":"
&& vr.substring(i, i + 1) != ",") {
            s = s + vr.substring(i, i + 1);
        }
    }
    return s;
    //return campo.value.replace("/", "").replace("-", "").replace(".", "").replace(",", "") 
}
// limpa todos caracteres que não são números 
function filtraNumeros(campo) {
    var s = "";
    var cp = "";
    vr = campo;
    tam = vr.length;
    for (i = 0; i < tam; i++) {
        if (vr.substring(i, i + 1) == "0" ||
vr.substring(i, i + 1) == "1" ||
vr.substring(i, i + 1) == "2" ||
vr.substring(i, i + 1) == "3" ||
vr.substring(i, i + 1) == "4" ||
vr.substring(i, i + 1) == "5" ||
vr.substring(i, i + 1) == "6" ||
vr.substring(i, i + 1) == "7" ||
vr.substring(i, i + 1) == "8" ||
vr.substring(i, i + 1) == "9") {
            s = s + vr.substring(i, i + 1);
        }
    }
    return s;
    //return campo.value.replace("/", "").replace("-", "").replace(".", "").replace(",", "") 
}
// limpa todos caracteres que não são números, menos a vírgula 
function filtraNumerosComVirgula(campo) {
    var s = "";
    var cp = "";
    vr = campo;
    tam = vr.length;
    var complemento = 0; //flag paga contar o número de virgulas 
    for (i = 0; i < tam; i++) {
        if ((vr.substring(i, i + 1) == "," && complemento == 0 && s != "") ||
vr.substring(i, i + 1) == "0" ||
vr.substring(i, i + 1) == "1" ||
vr.substring(i, i + 1) == "2" ||
vr.substring(i, i + 1) == "3" ||
vr.substring(i, i + 1) == "4" ||
vr.substring(i, i + 1) == "5" ||
vr.substring(i, i + 1) == "6" ||
vr.substring(i, i + 1) == "7" ||
vr.substring(i, i + 1) == "8" ||
vr.substring(i, i + 1) == "9") {
            if (vr.substring(i, i + 1) == ",")
                complemento = complemento + 1;
            s = s + vr.substring(i, i + 1);
        }
    }
    return s;
}
//recupera tecla 
//evita criar mascara quando as teclas são pressionadas 
function teclaValida(tecla) {
    if (tecla == 8 //backspace 
|| tecla == 45 //insert 
|| tecla == 46 //delete 
|| tecla == 36 //home 
|| tecla == 37 //esquerda 
|| tecla == 38 //cima 
|| tecla == 39 //direita 
|| tecla == 40)//baixo 
        return false;
    else
        return true;
}
// recupera o evento do form 
function getEvent(evt) {
    if (!evt) evt = window.event; //IE 
    return evt;
}
//Recupera o código da tecla que foi pressionado 
function getKeyCode(evt) {
    var code;
    if (typeof (evt.keyCode) == 'number')
        code = evt.keyCode;
    else if (typeof (evt.which) == 'number')
        code = evt.which;
    else if (typeof (evt.charCode) == 'number')
        code = evt.charCode;
    else
        return 0;
    return code;
}



















//Função para formatar
function formatar(src, mask) {
    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);
    }
}



//Função para qualquer formatação de um textbox(input)
function txtBoxFormat(objForm, strField, 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;
}

sValue = objForm[strField].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( ":", "" );
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) == " "))
bolMask = bolMask || (sMask.charAt(i) == ":")

if (bolMask) {
sCod += sMask.charAt(i);
mskLen++; }
else {
sCod += sValue.charAt(nCount);
nCount++;
}

i++;
}

objForm[strField].value = sCod;

if (nTecla != 8) { // backspace
if (sMask.charAt(i-1) == "9") { // apenas números...
return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
else { // qualquer caracter...
return true;
} }
else {
return true;
}
} 

//Função para validar email
function validar_email(objForm, strField) {
	var campo_email = objForm[strField].value;
	//Checando se o endereço e-mail não esta vazio
	if(campo_email=="") {
		alert("É necessário o preenchimento deste campo.");
		objForm[strField].focus();
		return false;
	}
	//Checando se o endereço de e-mail é válido
	if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(objForm[strField].value))) {
		alert("É necessário o preenchimento de um endereço de e-mail válido.");
		objForm[strField].focus();
		return false;
	}
}





function rdoDestino_onClick(obj) {

    var cboEntidade = document.form.getElementById("sel_Entidade");

    if (obj.value == "fundo") {
        cboEntidade.disabled = true;
    }
    else {
        cboEntidade.disabled = false;
    }

    return true;
}
function Somente_Numeros() {
    if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
}

function AlteraDisp(Tipo, Controle1, Controle2, Controle3) {
    if (Tipo == 1) {
        document.getElementById(Controle1).style.display = 'none';
        document.getElementById(Controle2).style.display = 'none';
        document.getElementById(Controle3).style.display = 'none';
    }
    else {
        document.getElementById(Controle1).style.display = 'block';
        document.getElementById(Controle2).style.display = 'block';
        document.getElementById(Controle3).style.display = 'block';
    }
}

// JavaScript Document

function soNumeroDecimal(objeto) {
    var keypress = event.keyCode;
    if (event.keyCode == 17) {
        event.keyCode = 0;
    }
    if (event.keyCode == 46 && (objeto.value.indexOf(String.fromCharCode(46)) != -1)) {
        event.keyCode = 0;
    }
    var campo = eval(objeto);
    var caracteres = '01234567890.';
    if ((caracteres.indexOf(String.fromCharCode(keypress)) != -1)) {
        event.returnValue = true;
    }
    else
        event.returnValue = false;
}

function validaCasasDecimal(objeto, maxlength, casas, valor) {
    if ((objeto.value.indexOf('.') != -1)) {
        if ((objeto.value.length - objeto.value.indexOf('.')) > casas + 1)
            objeto.value = objeto.value.substr(0, objeto.value.length - 1);
    }
    else {
        if ((objeto.value.length) >= maxlength - (casas + valor))
            objeto.value = objeto.value.substr(0, (maxlength - (casas + valor)));
    }
}

function tiposcaracteristicas(descricao) {
    if (descricao == "Checkbox")
        return 1;
    else if (descricao == "Quantitativa")
        return 2;
    else if (descricao == "Valor")
        return 3;
    else if (descricao == "Filtro")
        return 4;
}

function tratarcampo(param, tratar) {
    if (tratar == true)
        var tipocaract = parseInt(tiposcaracteristicas(param));
    else
        var tipocaract = param;
    if (tipocaract == 1) { //checkbox
        document.form1.valorcaract.onkeypress = function() { };
        document.form1.valorcaract.onKeyUp = function() { };
        document.form1.valorcaract.value = "1"
        document.getElementById("linhacaract").style.visibility = "hidden";
    }
    else if (tipocaract == 2) { //quantitativa
        document.form1.valorcaract.onkeypress = function() { mascara(this, soNumeros) };
        document.form1.valorcaract.onKeyUp = function() { };
        document.form1.valorcaract.value = "";
        document.getElementById("linhacaract").style.visibility = "visible";
    }
    else if (tipocaract == 3) { //valor 	
        document.form1.valorcaract.onkeypress = function() { return (formatarvalor(this, '.', ',', event)); };
        document.form1.valorcaract.value = "";
        document.getElementById("linhacaract").style.visibility = "visible";
    }
}

function selecionarnocombo(obj, valor) {
    for (var i = 0; i < obj.options.length; i++) {
        if (obj.options[i].text == valor)
            obj.options[i].selected = true;
    }
}

function TextInner(obj) {
    if (document.all)
        return obj.innerText;  // pra IE
    else
        return obj.textContent; // pra Firefox
}

function atualizatamanhoIF(param) {
    //alert(param+" "+document.form1.offsetHeight)
    if (parent.document.getElementById(param)) {
        parent.document.getElementById(param).height = document.form1.offsetHeight;
        parent.document.getElementById(param).width = document.form1.offsetWidth;
    }
}

function addEvent(node, evtType, func) {
    if (node.addEventListener) {
        node.addEventListener(evtType, func, false);
        return true;
    }
    else if (node.attachEvent)
        return node.attachEvent("on" + evtType, func);
    else
        return false;
}

function emularenter() {
    if (document.all) {
        if (document.getElementById("executar"))
            addEvent(document, "keypress", function() { if (event.keyCode == 13) document.getElementById("executar").click(); });
        else if (document.form1.executar)
            addEvent(document, "keypress", function() { if (event.keyCode == 13) document.form1.executar.click(); });
    }
}

function limparcampos(param) {
    var campos = param.split(',')
    for (var i = 0; i < campos.length; i++) {
        if (document.getElementById(campos[i]))
            document.getElementById(campos[i]).value = "";
    }
}


function camposvazios(param) {
    var campos = param.split(",")
    for (var i = 0; i < campos.length; i++) {
        if (document.getElementById(campos[i]).value == "") {
            document.getElementById(campos[i]).style.backgroundColor = "red"
        }
    }
    alert('Preencha os Campos Obrigatórios!!')
    for (var i = 0; i < campos.length; i++) {
        document.getElementById(campos[i]).style.backgroundColor = "white"
    }
}

function salvar(param, func) {
    var campos = param.split(',')
    for (var i = 0; i < campos.length; i++) {
        if (document.getElementById(campos[i]).value == "") {
            document.getElementById(campos[i]).focus();
            camposvazios(param)
            return false;
            break;
        }
    }
    return enviar('operacoes/cadastrar.php', '', '', '' + func + '');
}

function popup(param, largura, altura) {
    window.open(param, '', 'location=no,scrollbars=yes,width=' + largura + ',height=' + altura + 'px')
}

function validardata(f, fld, msg, vazio) {
    var frm = f
    var e = document.getElementById(fld)
    dataStr = e.value;
    if (vazio == "sim") {
        return true;
    } else {
        if (dataStr == "") {
            return false;
        }
        var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
        var matchArray = dataStr.match(datePat); // formato da data ok? 
        if (matchArray == null) {
            alert("Data Inválida com formato inválido.");
            e.value = "";
            return false;
        }
        dia = matchArray[1];
        mes = matchArray[3];
        ano = matchArray[4];

        if (dia < 1 || dia > 31) {
            alert("Favor digitar um Dia Válido.");
            e.value = "";
            return false;
        }

        if ((mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia == 31) {
            alert("O Mês " + mes + " não possue 31 dias!");
            e.value = "";
            return false;
        }

        if (mes == 2) {
            // checando Fevereiro para dia 29  
            var isleap = (ano % 4 == 0 && (ano % 100 != 0 || ano % 400 == 0));
            if (dia > 29 || (dia == 29 && !isleap)) {
                alert("Fevereiro de " + ano + " não tem " + dia + " dias!");
                e.value = "";
                e.select();
                return false;
            }
        }

        if (mes < 1 || mes > 12) {
            alert("Favor digitar um Mês Válido."); e.value = ""; e.select();
            return false;
        }

        return true; // Data válida

    }
}

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
}


function filtrarnumero(param) {
    var result = "";

    for (var i = 0; i < param.length; i++) {
        if (!isNaN(parseInt(param.charAt(i))))
            result += (param.charAt(i))
    }

    return result;
}

//--------------------------------------------------------------

function Verifica_campo_CPF(campo) {
    var CPF = filtrarnumero(campo.value); // Recebe o valor digitado no campo

    // Aqui começa a checagem do CPF
    var POSICAO, I, SOMA, DV, DV_INFORMADO;
    var DIGITO = new Array(10);
    DV_INFORMADO = CPF.substr(9, 2); // Retira os dois últimos dígitos do número informado

    // Desemembra o número do CPF na array DIGITO
    for (I = 0; I <= 8; I++) {
        DIGITO[I] = CPF.substr(I, 1);
    }

    // Calcula o valor do 10º dígito da verificação
    POSICAO = 10;
    SOMA = 0;
    for (I = 0; I <= 8; I++) {
        SOMA = SOMA + DIGITO[I] * POSICAO;
        POSICAO = POSICAO - 1;
    }
    DIGITO[9] = SOMA % 11;
    if (DIGITO[9] < 2) {
        DIGITO[9] = 0;
    }
    else {
        DIGITO[9] = 11 - DIGITO[9];
    }

    // Calcula o valor do 11º dígito da verificação
    POSICAO = 11;
    SOMA = 0;
    for (I = 0; I <= 9; I++) {
        SOMA = SOMA + DIGITO[I] * POSICAO;
        POSICAO = POSICAO - 1;
    }
    DIGITO[10] = SOMA % 11;
    if (DIGITO[10] < 2) {
        DIGITO[10] = 0;
    }
    else {
        DIGITO[10] = 11 - DIGITO[10];
    }

    // Verifica se os valores dos dígitos verificadores conferem
    DV = DIGITO[9] * 10 + DIGITO[10];
    if (DV != DV_INFORMADO) {
        alert('Cpf informado é inválido!');
        campo.value = '';
        campo.focus();
        return false;
    }
}

//---

function mascara(o, f) {
    v_obj = o
    v_fun = f
    setTimeout("execmascara()", 1)
}

function execmascara() {
    v_obj.value = v_fun(v_obj.value)
}

function leech(v) {
    v = v.replace(/o/gi, "0")
    v = v.replace(/i/gi, "1")
    v = v.replace(/z/gi, "2")
    v = v.replace(/e/gi, "3")
    v = v.replace(/a/gi, "4")
    v = v.replace(/s/gi, "5")
    v = v.replace(/t/gi, "7")
    return v
}

function soNumeros(v) {
    v.value = v.value.replace(/\D/g, "")
    return v
}

function telefone(v) {
    v.value = v.value.replace(/\D/g, "")                 //Remove tudo o que não é dígito
    v.value = v.value.replace(/^(\d\d)(\d)/g, "($1)$2")  //Coloca parênteses em volta dos dois primeiros dígitos
    v.value = v.value.replace(/(\d{4})(\d)/, "$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function cpfcnpj(v) {
    if (v.value.length <= 12) {
        return (cpf(v));
    } else {
        return (cnpj(v));
    }
}
function cpf(v) {

    v.value = v.value.replace(/\D/g, "");                    //Remove tudo o que não é dígito
    v.value = v.value.replace(/(\d{3})(\d)/, "$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
    v.value = v.value.replace(/(\d{3})(\d)/, "$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos

    v.value = v.value.replace(/(\d{3})(\d{1,2})$/, "$1-$2"); //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function cep(v) {
    v.value = v.value.replace(/D/g, "")                //Remove tudo o que não é dígito
    v.value = v.value.replace(/^(\d{5})(\d)/, "$1-$2") //Esse é tão fácil que não merece explicações
    return v
}


function data(v) {
    v.value = v.value.replace(/[a-z]/g, "");
    v.value = v.value.replace(/^(\d+)$/g, "$1");
    v.value = v.value.replace(/^(\d{2})\/?(\d+)$/g, "$1/$2");
    v.value = v.value.replace(/^(\d{2})\/?(\d{2})\/?(\d{1,4})$/g, "$1/$2/$3");
    return v;
}


function hora(v) {
    v.replace(/[^d]/g, '').replace(/^(\d{2})(\d{2}).*$/, '$1: $2');
    return v;
}



function cnpj(v) {
    v.value = v.value.replace(/\D/g, "")                           //Remove tudo o que não é dígito
    v.value = v.value.replace(/^(\d{2})(\d)/, "$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v.value = v.value.replace(/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v.value = v.value.replace(/\.(\d{3})(\d)/, ".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v.value = v.value.replace(/(\d{4})(\d)/, "$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}
//-->

function formatarpercentual(fld, decSep, 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;  // Enter

    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key

    len = fld.value.length;

    for (i = 0; i < len; i++)
        if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;

    aux = '';

    for (; i < len; i++)
        if (strCheck.indexOf(fld.value.charAt(i)) != -1) aux += fld.value.charAt(i);

    aux += key;
    len = aux.length;

    if (len == 0) fld.value = '';
    if (len == 1) fld.value = '0' + decSep + '0' + aux; // Alterei coloquei + '0' , decSep = , (vírgula)
    if (len == 2) fld.value = '0' + decSep + aux; // Alterei coloquei + '0'
    if (len > 2) { // Alterei de 2 para 3

        aux2 = '';

        for (j = 0, i = len - 3; i >= 0; i--) {
            aux2 += aux.charAt(i);
            j++;
        }

        fld.value = '';
        len2 = aux2.length;

        for (i = len2 - 1; i >= 0; i--) // Alterei de i >= 0 para i > 0
            fld.value += aux2.charAt(i);

        fld.value += decSep + aux.substr(len - 2, len); // O número dois é o valor chave (número de casas que vem depois da vírgula)
    }
    return false;
}

function formatarvalor(fld, milSep, decSep, 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;  // Enter
    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
    len = fld.value.length;
    for (i = 0; i < len; i++)
        if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
    aux = '';
    for (; i < len; i++)
        if (strCheck.indexOf(fld.value.charAt(i)) != -1) aux += fld.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) fld.value = '';

    // Aqui tem que testar: se $Column->{decimals} for 3 coloca + '0' + '0' + senão, apenas + '0' +
    if (len == 1) fld.value = '0' + decSep + '0' + aux; // Alterei coloquei + '0' , decSep = , (vírgula)

    // Aqui tem que testar: se $Column->{decimals} for 3 coloca + '0' + senão, não coloca
    if (len == 2) fld.value = '0' + decSep + aux; // Alterei coloquei + '0'

    // Aqui tem que testar: se $Column->{decimals} for 3 coloca essa linha senão não coloca
    //if (len == 3) fld.value = '0' + decSep + aux + aux2; // Adicionei esta linha

    // Aqui tem que colocar a variável $decimal
    if (len > 2) { // Alterei de 2 para 3
        aux2 = '';

        // A cada três caracteres adiciona um milSep (ponto ".")
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += milSep;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }

        fld.value = '';
        len2 = aux2.length;

        // Aqui tem que testar: se $Column->{decimals} for 3 coloca i > 0 senão coloca i >= 0
        for (i = len2 - 1; i >= 0; i--) // Alterei de i >= 0 para i > 0
            fld.value += aux2.charAt(i);

        // Aqui tem que coloca a variável mo lugar do 3
        fld.value += decSep + aux.substr(len - 2, len); // O número dois é o valor chave (número de casas que vem depois da vírgula)
    }
    return false;
}
//-------------

function formatarcamposdata(param) {
    var campos = param.split(',')
    for (var i = 0; i < campos.length; i++) {
        if (document.getElementById(campos[i]).value == "00/00/0000") {
            document.getElementById(campos[i]).value = ""
        }
    }
}

function formatarcamposvlr(param) {
    var campos = param.split(',')
    for (var i = 0; i < campos.length; i++) {
        if (document.getElementById(campos[i]).value != "") {
            var valor = parseFloat(document.getElementById(campos[i]).value);
            document.getElementById(campos[i]).value = valor.format(2, ",", ".");
        } else {
            //document.getElementById(campos[i]).value="0,00";

        }
    }
}

String.PAD_LEFT = 0;
String.PAD_RIGHT = 1;
String.PAD_BOTH = 2;

String.prototype.pad = function(size, pad, side) {
    var str = this, append = "", size = (size - str.length);
    var pad = ((pad != null) ? pad : " ");
    if ((typeof size != "number") || ((typeof pad != "string") || (pad == ""))) {
        throw new Error("Wrong parameters for String.pad() method.");
    }
    if (side == String.PAD_BOTH) {
        str = str.pad((Math.floor(size / 2) + str.length), pad, String.PAD_LEFT);
        return str.pad((Math.ceil(size / 2) + str.length), pad, String.PAD_RIGHT);
    }
    while ((size -= pad.length) > 0) {
        append += pad;
    }
    append += pad.substr(0, (size + pad.length));
    return ((side == String.PAD_LEFT) ? append.concat(str) : str.concat(append));
}

Number.prototype.format = function(d_len, d_pt, t_pt) {
    var d_len = d_len || 0;
    var d_pt = d_pt || ".";
    var t_pt = t_pt || ",";
    if ((typeof d_len != "number")
    || (typeof d_pt != "string")
    || (typeof t_pt != "string")) {
        throw new Error("wrong parameters for method 'String.pad()'.");
    }
    var integer = "", decimal = "";
    var n = new String(this).split(/\./), i_len = n[0].length, i = 0;
    if (d_len > 0) {
        n[1] = (typeof n[1] != "undefined") ? n[1].substr(0, d_len) : "";
        decimal = d_pt.concat(n[1].pad(d_len, "0", String.PAD_RIGHT));
    }
    while (i_len > 0) {
        if ((++i % 3 == 1) && (i_len != n[0].length)) {
            integer = t_pt.concat(integer);
        }
        integer = n[0].substr(--i_len, 1).concat(integer);
    }
    return (integer + decimal);
}

function convertemoedamysql(param) {
    param = param.replace(".", "")
    param = param.replace(",", ".")
    return param;
}