// JavaScript Document

function digitarCpf(c, e) { 
    
    var cpf = c.value;
    var tam = cpf.length;
    
    if (!isTeclaEspecial(e) ){
        if (tam > 13){
            e.stop();
        }
        if (inStr("1234567890.-", e.key, 0) == -1){
            e.stop();
        }
        cpf = cleanStr(cpf,"0123456789");
        tam = cpf.length;
        if (tam > 2) {
            if (e.key != ".") cpf = cpf.substr(0,3) + "." + cpf.substr(3, tam);
        }    
        if (tam > 5) {
            if (e.key != ".") cpf = cpf.substr(0,7) + "." + cpf.substr(7, tam);
        }     
        if (tam > 8) {
            if (e.key != "-") cpf = cpf.substr(0,11) + "-" + cpf.substr(11, tam);
        }     

        c.value = cpf;        
    }
}

function isTeclaEspecial(e){
    if ( (e.key == 'c' && e.control) || (e.key == 'x' && e.control) || 
         (e.key == 'v' && e.control) || (e.shift) || (e.key == "end") ||
         (e.key == "backspace") || (e.key == "delete") || (e.key == "left") ||
         (e.key == "right") || (e.key == "tab") ){                 
        return true;
    } else {
        return false;
    }
}

function inStr(texto,c,posInicial) {
    if (posInicial<0) posInicial=0;
    
    for(var i=posInicial; i<texto.length;i++) {
        if(texto.charAt(i)==c) return i;
    }
    return -1;
}

// retira caracteres invalidos da string
function cleanStr(str,validos) {
    var i,temp = "";
    for (i=0;i<str.length;i++){
        if (validos.indexOf(str.charAt(i)) != -1){
            temp += str.charAt(i);
        }
    }
    return temp;
}

function validarCpf(c){
    var numeros, digitos, soma, i, resultado, digitos_iguais;
    var cpf = cleanStr(c.value,"0123456789");
    digitos_iguais = 1;
    if (cpf.length < 11) return false;
    for (i = 0; i < cpf.length - 1; i++){
        if (cpf.charAt(i) != cpf.charAt(i + 1)){
            digitos_iguais = 0;
            break;
        }
    }
    if (!digitos_iguais){
        numeros = cpf.substring(0,9);
        digitos = cpf.substring(9);
        soma = 0;
        for (i = 10; i > 1; i--){
            soma += numeros.charAt(10 - i) * i;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(0)) return false;
        numeros = cpf.substring(0,10);
        soma = 0;
        for (i = 11; i > 1; i--){
            soma += numeros.charAt(11 - i) * i;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1)) return false;
        return true;
    }
    else
        return false;
}
