jQuery(document).ready(function(){
    InitMaskCampos();

    $('.cep').blur(function(){
        getEndereco($(this).val());
    });

    InitAllowSubmit();

    checaCPF();
});

function InitMaskCampos(){
    // ADICIONANDO MASCARAS AO CAMPOS
    jQuery(function($){
//        $("#CadastroIe").           mask("?888888888888888888888888888888888888888888888888",{placeholder:""});
//   	$("#cpf").                  mask("999.999.999-99");
//        $("#CadastroCpfBanco").     mask("999.999.999-99");
//        $("#cnpj").                 mask("99.999.999/9999-99");
//        $("#CadastroRg").           mask("888888?888888888888", {placeholder:""});
//        $("#CadastroFone").         mask("(99) 9999-9999");
//        $("#CadastroFax").          mask("(99) 9999-9999");
//        $("#CadastroRefTelefone2"). mask("(99) 9999-9999");
//        $("#CadastroRefTelefone").  mask("(99) 9999-9999");
//        $("#CadastroRefEmpTel2").   mask("(99) 9999-9999");
//        $("#CadastroRefEmpTel1").   mask("(99) 9999-9999");
//        $("#CadastroCelular").      mask("(99) 9999-9999");
//
//        $("#CadastroComplemento").  mask("?++++++++++++++++++++++++++++++++++++++++++++++",{placeholder:""});
//        $("#CadastroEstado").       mask("?++++++++++++++++++++++++++++++++++++++++++++++",{placeholder:""});
//        $("#CadastroPais").         mask("?++++++++++++++++++++++++++++++++++++++++++++++",{placeholder:""});
//        $("#CadastroCep").          mask("99999-999");
//        $("#CadastroNumero").       mask("9?99999", {placeholder:""});
    });

    $("#ContatoTel").focus(function(){
        $(this).mask("(99) 9999-9999");
    });
     $("#TrabalhoTel").focus(function(){
        $(this).mask("(99) 9999-9999");
    });
}

function InitAllowSubmit(){
    checaAccept();

    $("#CadastroContratoLido").click(function(){
        checaAccept();
    })
}
function checaAccept(){
    var accept = $("#CadastroContratoLido:checked").attr('name');
    if(accept){
        $("#CadastroNovoForm :button").removeAttr('disabled');
    }
    else{
        $("#CadastroNovoForm :button").attr("disabled", "disabled");
    }
}

// Funço Única que fará a transação
function getEndereco(cep) {
    // Se o campo CEP n�o estiver vazio
    if($.trim($(".cep").val()) != ""){
        var valor = cep;
        $(".cep").attr('value',valor)
        /*
                        Para conectar no servi�o e executar o json, precisamos usar a fun��o
                        getScript do jQuery, o getScript e o dataType:"jsonp" conseguem fazer o cross-domain, os outros
                        dataTypes n�o possibilitam esta intera��o entre dom�nios diferentes
                        Estou chamando a url do servi�o passando o par�metro "formato=javascript" e o CEP digitado no formul�rio
                        http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val()
                */
        $.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$(".cep").val(), function(){
            // o getScript d� um eval no script, ent�o � s� ler!
            //Se o resultado for igual a 1
            if(resultadoCEP["resultado"]){
                // troca o valor dos elementos

                $("#CadastroLogradouro").val(unescape(resultadoCEP["tipo_logradouro"])+": "+unescape(resultadoCEP["logradouro"]));
                $("#CadastroBairro").val(unescape(resultadoCEP["bairro"]));
                $("#CadastroEstado").val(unescape(resultadoCEP["uf"]));
                $("#CadastroCidade").val(unescape(resultadoCEP["cidade"]));

            }
            else{
                alert("Endereço não encontrado");
            }
        });
    }
}

function checaCPF(){
    $('#CadastroCpf').blur(function(){
        if(validaCPF($(this).val(), $(this))){
            $(this).removeClass('form-error');
            $('div').remove('.error-message');
        }
        else{
            $(this).addClass('form-error');
            var errorCpf = $(this).parent().find('div.error-message');
                if($(errorCpf).attr('class') == 'error-message'){
                    $(errorCpf).html('CPF Invalido');
                }
                else{
                    $(this).parent().append('<div class="error-message">CPF Invalido</div>');
                }
        }
    });
}

function validaCPF(value, element){
    value = value.replace('.','');
    value = value.replace('.','');
    cpf = value.replace('-','');
    while(cpf.length < 11) cpf = "0"+ cpf;
    var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
    var a = [];
    var b = new Number;
    var c = 11;
    for (i=0; i<11; i++){
        a[i] = cpf.charAt(i);
        if (i < 9) b += (a[i] * --c);
    }
    if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
    b = 0;
    c = 11;
    for (y=0; y<10; y++) b += (a[y] * c--);
    if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
    if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg))
    return false;
    return true;
}
