﻿function SetUniqueRadioButton(nameregex, current)   
{
    for (i = 0; i < document.forms[0].elements.length; i++) 
    {
        elm = document.forms[0].elements[i];
        if (elm.type == 'radio')
            elm.checked = false;
    }
    current.checked = true;
}

function formatPhone(field, evt) {
    //(00) 0000-0000
    var xPos = positionCursor(field);
    evt = getEvent(evt);
    var key = getKeyCode(evt);
    if (!invalidKey(key))
        return;

    vr = field.value = filterNumber(filterField(field));
    tam = vr.length;

    if (tam == 1)
        field.value = '(' + vr;
    else if (tam >= 2 && tam < 6)
        field.value = '(' + vr.substr(0, 2) + ') ' + vr.substr(2);
    else if (tam >= 6)
        field.value = '(' + vr.substr(0, 2) + ') ' + vr.substr(2, 4) + '-' + vr.substr(6);

    movimentCursor(field, xPos);
}

function formatValue(field, evt) {
    var xPos = positionCursor(field);
    evt = getEvent(evt);
    var key = getKeyCode(evt);
    if (!invalidKey(key))
        return;

    vr = field.value = filterNumber(filterField(field));
    if (vr.length > 0) {
        vr = parseFloat(vr.toString()).toString();
        tam = vr.length;

        if (tam == 1)
            field.value = "0,0" + vr;
        if (tam == 2)
            field.value = "0," + vr;
        if ((tam > 2) && (tam <= 5))
            field.value = vr.substr(0, tam - 2) + ',' + vr.substr(tam - 2, tam);
        if ((tam >= 6) && (tam <= 8))
            field.value = vr.substr(0, tam - 5) + '.' + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam);
        if ((tam >= 9) && (tam <= 11))
            field.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))
            field.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))
            field.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);
    }
    movimentCursor(field, xPos);
}

//Função que mantem 4 digitos apos a vírgula.
function formatValueDig(field, evt) {
    var xPos = positionCursor(field);
    evt = getEvent(evt);
    var key = getKeyCode(evt);
    if (!invalidKey(key))
        return;

    vr = field.value = filterNumber(filterField(field));
    if (vr.length > 0) {
        vr = parseFloat(vr.toString()).toString();
        tam = vr.length;

        if (tam == 1)
            field.value = "0,000" + vr;
        if (tam == 2)
            field.value = "0,00" + vr;
        if (tam == 3)
            field.value = "0,0" + vr;
        if (tam == 4)
            field.value = "0," + vr;
        if ((tam > 4) && (tam <= 7))
            field.value = vr.substr(0, tam - 4) + ',' + vr.substr(tam - 4, tam);
        if ((tam >= 8) && (tam <= 10))
            field.value = vr.substr(0, tam - 7) + '.' + vr.substr(tam - 7, 3) + ',' + vr.substr(tam - 4, tam);
        if ((tam >= 11) && (tam <= 13))
            field.value = vr.substr(0, tam - 10) + '.' + vr.substr(tam - 10, 3) + '.' + vr.substr(tam - 7, 3) + ',' + vr.substr(tam - 4, tam);
    }
    movimentCursor(field, xPos);
}

// Formata data no padrão DD/MM/YYYY
function formatDate(field, evt) {
    var xPos = positionCursor(field);
    //dd/MM/yyyy
    evt = getEvent(evt);

    var key = getKeyCode(evt);
    if (!invalidKey(key))
        return;

    vr = field.value = filterNumber(filterField(field));
    tam = vr.length;

    if (tam >= 2 && tam < 4) 
        field.value = vr.substr(0, 2) + '/' + vr.substr(2);
    if (tam == 4)
        field.value = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/';
    if (tam > 4)
        field.value = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/' + vr.substr(4, 4);

    movimentCursor(field, xPos);
}

function SomenteNumero(e) {
    var tecla = (window.event) ? event.keyCode : e.which;
    if ((tecla > 47 && tecla < 58))
        return true;
    else {
        if (tecla == 8 || tecla == 0)
            return true;
        else
            return false;
    }
}

function onlyNumber(field) {
    field.value = filterNumber(filterField(field));
}

//descobre qual a posição do cursor no campo
function positionCursor(text) {
    var pos = 0;
    if (typeof (document.selection) != 'undefined') {   
        //IE
        var range = document.selection.createRange();
        var i = 0;
        for (i = text.value.length; i > 0; i--) {
            if (range.moveStart('character', 1) == 0)
                break;
        }
        pos = i;
    }
    if (typeof (text.selectionStart) != 'undefined') {
        //FireFox
        pos = text.selectionStart;
    }

    if (pos == text.value.length)
        return 0; //retorna 0 quando não precisa posicionar o elemento
    else
        return pos; //posição do cursor
}

//// move o cursor para a posição pos
function movimentCursor(text, pos) {
    if (pos <= 0)
        return; //se a posição for 0 não reposiciona

    if (typeof (document.selection) != 'undefined') {
        //IE
        var oRange = text.createTextRange();
        var LENGTH = 1;
        var STARTINDEX = pos;

        oRange.moveStart("character", -text.value.length);
        oRange.moveEnd("character", -text.value.length);
        oRange.moveStart("character", pos);
        //oRange.moveEnd("character", pos);
        oRange.select();
        text.focus();
    }
    if (typeof (text.selectionStart) != 'undefined') {
        //FireFox
        text.selectionStart = pos;
        text.selectionEnd = pos;
    }
}

//// limpa todos os caracteres especiais do campo solicitado
function filterField(field) {
    var s = "";
    var cp = "";
    vr = field.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) != ")"
            && 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 os caracteres especiais do campo solicitado
function filterFieldWithDot(field) {
    var s = "";
    var cp = "";
    vr = field.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 filterNumber(field) {
    var s = "";
    var cp = "";
    vr = field;
    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
function filterNumberWithDot(field) {
    var s = "";
    var cp = "";
    vr = field;
    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) == "," ||
            vr.substring(i, i + 1) == "." ||
            vr.substring(i, i + 1) == "9") {
            s = s + vr.substring(i, i + 1);
        }
    }
    return s;
    //return campo.value.replace("/", "").replace("-", "").replace(".", "").replace(",", "")
}

////evita criar mascara quando as teclas são pressionadas
function invalidKey(key) {
    if (key == 8 //backspace
    //Esta evitando o post, quando são pressionadas estas teclas.
    //Foi comentado pois, se for utilizado o evento texchange, é necessario o post.
        || key == 9 //TAB
        || key == 27 //ESC
        || key == 16 //Shif TAB 
        || key == 45 //insert
        || key == 46 //delete
        || key == 35 //home
        || key == 36 //end
        || key == 37 //esquerda
        || key == 38 //cima
        || key == 39 //direita
        || key == 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;
}

function Validar(theCPF) {

    if (theCPF.value == "")
        return (false);

    var text = theCPF.value.toString();

    text = remove(text, ".");
    text = remove(text, "/");
    text = remove(text, "-");

    if (((text.length == 11) && ((text == 11111111111) || (text == 22222222222) || (text == 33333333333) || (text == 44444444444) || (text == 55555555555) || (text == 66666666666) || (text == 77777777777) || (text == 88888888888) || (text == 99999999999) || (text == 00000000000)))) {
        alert("CPF/CNPJ inválido.");
        theCPF.value = "";
        return (false);
    }


    if (!((text.length == 11) || (text.length == 14))) {
        alert("CPF/CNPJ inválido.");
        theCPF.value = "";
        return (false);
    }

    var checkOK = "0123456789";
    var checkStr = text;
    var allValid = true;
    var allNum = "";
    for (i = 0; i < checkStr.length; i++) {
        ch = checkStr.charAt(i);
        for (j = 0; j < checkOK.length; j++)
            if (ch == checkOK.charAt(j))
                break;
        if (j == checkOK.length) {
            allValid = false;
            break;
        }
        allNum += ch;
    }
    if (!allValid) {
        alert("Favor preencher somente com dígitos o campo CPF/CNPJ.");
        return (false);
    }

    var chkVal = allNum;
    var prsVal = parseFloat(allNum);
    if (chkVal != "" && !(prsVal > "0")) {
        alert("CPF zerado !");
        return (false);
    }

    if (text.length == 11) {
        var tot = 0;

        for (i = 2; i <= 10; i++)
            tot += i * parseInt(checkStr.charAt(10 - i));

        if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(9))) {
            alert("CPF/CNPJ inválido.");
            theCPF.value = "";
            return (false);
        }

        tot = 0;

        for (i = 2; i <= 11; i++)
            tot += i * parseInt(checkStr.charAt(11 - i));

        if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(10))) {
            alert("CPF/CNPJ inválido.");
            theCPF.value = "";
            return (false);
        }
    }
    else {
        var tot = 0;
        var peso = 2;

        for (i = 0; i <= 11; i++) {
            tot += peso * parseInt(checkStr.charAt(11 - i));
            peso++;
            if (peso == 10) {
                peso = 2;
            }
        }

        if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(12))) {
            alert("CPF/CNPJ inválido.");
            theCPF.value = "";
            return (false);
        }

        tot = 0;
        peso = 2;

        for (i = 0; i <= 12; i++) {
            tot += peso * parseInt(checkStr.charAt(12 - i));
            peso++;
            if (peso == 10) {
                peso = 2;
            }
        }

        if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(13))) {
            alert("CPF/CNPJ inválido.");
            theCPF.value = "";
            return (false);
        }
    }
    return (true);
}




function cpfcnpj(theCPF) {

    //testo o tamanho do campo e quando atingir três caracteres coloco o ponto.

    if (theCPF.value.length == 3) {
        //para exemplo dei nome para o form de a e pro campo de b, o que pode ser mudado.
        theCPF.value = theCPF.value + '.';
        return false;
    }

    //agora testo ao sétimo digito que é onde vai o segundo ponto na mascara para o cpf.

    if (theCPF.value.length == 7) {
        theCPF.value = theCPF.value + '.';
        return false;
    }

    //e final mente o traço do digito verificador

    if (theCPF.value.length == 11) {
        theCPF.value = theCPF.value + '-';
        return false;
    }

    //agora é que fico sabendo se o campo é um cnpj, se tiver 15 caracteres pego todos eles pra dentro
    //de variáveis, sei que da pra fazer com um array mas assim fica fácil da galera entender.

    if (theCPF.value.length == 15) {
        //aqui uso charAt(0) que me retorna um caracter especifico, assim posso pegar apenas os números
        //do cpf e não os pontos e o traço.
        p0 = theCPF.value.charAt(0);
        p1 = theCPF.value.charAt(1);
        p2 = theCPF.value.charAt(2);
        p3 = theCPF.value.charAt(4);
        p4 = theCPF.value.charAt(5);
        p5 = theCPF.value.charAt(6);
        p6 = theCPF.value.charAt(8);
        p7 = theCPF.value.charAt(9);
        p8 = theCPF.value.charAt(10);
        p9 = theCPF.value.charAt(12);
        p10 = theCPF.value.charAt(13);
        p11 = theCPF.value.charAt(14);
        //limpo o campo pra depois colocar o cnpj.
        theCPF.value = '';

        //e faço uma concatenação das variáveis

        theCPF.value = p0 + p1 + '.' + p2 + p3 + p4 + '.' + p5 + p6 + p7 + '/' + p8 + p9 + p10 + p11 + '-';

        return false;
    }
}

function remove(str, sub) {

    i = str.indexOf(sub);

    r = "";

    if (i == -1) return str;

    r += str.substring(0, i) + remove(str.substring(i + sub.length), sub);

    return r;

}
