var formatoData = 'd/m/Y';
var mensagemErro = '<div class="msg_erro"><h4>Campos em destaque contém valores inválidos ou sem preenchimento (*)</h4>';
var mensagemErroEmail = '<div class="msg_erro"><h4>E-mail inválido</h4>';
var exp = 0;
var htmlExp = "";
var edu = 0;
var htmlEdu = "";
var idi = 0;
var htmlIdi = "";

/* Validacao de formulario */
(function($) {
    $.fn.validate = function(args) {
        var options = $.extend({}, $.fn.validate.defaults, args);
        var jQ = $;
        return this.each(function() {
            jQ(this).submit(function() {
                var valid=true;
                var msg;
                var label;
                var qtdCar;
                var campo1;
                var campo2;
                jQ(this).find(".validate").each(function() {
                    el = jQ(this);
                    var filtro = false;
                    if('filtro_' == el[0].name.substr(0, 7)) {
                        filtro = true;
                    }
                    qtdCar = $('#'+el[0].name).prev("span").prev("label").text().length;
                    label = $('#'+el[0].name).prev("span").prev("label").text().substr(0, qtdCar-6);
                    el[0].setAttribute("style", "color: #000000");
                    if(el.hasClass("required")) {
                        if(!valid_required(el.val())) {
                            msg = '"' + label + '" obrigatório';
                            add_error(el,filtro,msg);
                            valid=false;
                        }else{
                            sub_error(el);
                            if(el.hasClass("required") && el.hasClass("email")) {
                                if(!valid_email(el.val())) {
                                    msg = '"' + label + '" é invalido';
                                    add_error(el,filtro,msg);
                                    valid=false;
                                }else{
                                    sub_error(el);
                                }
                            }
                            if(el.hasClass("required") && el.hasClass("date")) {
                                if(!valid_date(el.val(), formatoData)) {
                                    msg = '"' + label + '" é invalido';
                                    add_error(el,filtro,msg);
                                    valid=false;
                                }else if(el.hasClass("birthday")){
                                    if(!valid_date_birthday(el.val())){
                                        msg = '"' + label + '" é invalido';
                                        add_error(el,filtro,msg);
                                        valid=false;
                                    }
                                }else{
                                    sub_error(el);
                                }
                            }
                            if(el.hasClass("required") &&  el.hasClass("number")) {
                                if(!valid_number(el.val())) {
                                    msg = '"' + label + '" é invalido';
                                    add_error(el,filtro,msg);
                                    valid=false;
                                }else{
                                    sub_error(el);
                                }
                            }
                            if(el.hasClass("required") &&  el.hasClass("cpf")) {
                                if(!valid_cpf(el.val())){
                                    msg = '"' + label + '" é invalido';
                                    add_error(el,filtro,msg);
                                    valid=false;
                                }else{
                                    sub_error(el);
                                }
                            }
                            if(el.hasClass("required") &&  el.hasClass("cnpj")) {
                                if(!valid_cnpj(el.val())){
                                    msg = '"' + label + '" é invalido';
                                    add_error(el,filtro,msg);
                                    valid=false;
                                }else{
                                    sub_error(el);
                                }
                            }
                            if(el.hasClass("required") &&  el.hasClass("aceite")) {
                                if(!valid_checked(el[0].name)) {
                                    msg = 'Você não concordou com os termos apresentados';
                                    add_error(el,filtro,msg);
                                    valid=false;
                                }
                            }
                            if(el.hasClass("required") &&  el.hasClass("primary")) {
                                campo1 = el.val();
                            }
                            if(el.hasClass("required") &&  el.hasClass("second")) {
                                campo2 = el.val();
                                if(!valid_senha(campo1, campo2)){
                                    msg = 'Senhas se diferem';
                                    add_error(el,filtro,msg);
                                    valid=false;
                                }else{
                                    sub_error(el);
                                }
                            }
                        }
                    }
                });
                if(valid == false) {
                    $("#mensagem_erro").html(mensagemErro);
                    $("#mensagem_erro").attr("style", "color:#FF0000; font-weight:bold; font-size:16px; display: block");
                    $('html, body').animate({
                        scrollTop: $(".error").offset().top
                    }, 1500);
                }
                return valid;
            });
        });
    };
    function sub_error(el) {
        $('#erro-'+el[0].name).html('');
    }
    function add_error(el,filtro,msg) {
        if(!filtro) {
            $('#erro-'+el[0].name).html(msg);
            el[0].setAttribute("style", "border: 1px solid red !important; color: #FF0000 !important; -moz-border-radius: 3px 3px 3px 3px !important");
        }
    }
    function valid_email(email) {
        var email_pattern  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if(email.match(email_pattern)) return true;
        if(email == '') {
            return false;
        }
        return false;
    }
    function valid_number(number) {
        var number_pattern = /^([0-9\s])+$/;
        if(number.match(number_pattern)) {
            return true;
        }
        if(number == '') {
            return true;
        }
        return false;
    }
    function valid_required(val) {
        val = $.trim(val);
        if(val.length>0) {
            return true;
        }else{
            return false;
        }
    }
    function valid_checked(id) {
        if( $('#'+id).is(":checked") == true ){
            return true;
        }else{
            return false;
        }
    }
    function valid_date(date_passed, date_format, birthday) {
        var date_pattern;
        if(date_format == "m/d/Y") date_pattern  = /(0[1-9]|1[012])+\/(0[1-9]|[12][0-9]|3[01])+\/(19|20)\d\d/;
        if(date_format == "m-d-Y") date_pattern  = /(0[1-9]|1[012])+\/(0[1-9]|[12][0-9]|3[01])+\/(19|20)\d\d/;
        if(date_format == "d/m/Y") date_pattern  = /(0[1-9]|[12][0-9]|3[01])+\/(0[1-9]|1[012])+\/(19|20)\d\d/;
        if(date_format == "d-m-Y") date_pattern  = /(0[1-9]|[12][0-9]|3[01])+\/(0[1-9]|1[012])+\/(19|20)\d\d/;
        if(date_passed.match(date_pattern)) return true;
        if(date_passed == '') {
            return true;
        }
        return false;
    }
    function valid_date_birthday(date_passed) {
        var data = new Date();
        var txtData = date_passed;
        if(Date.parse(data)>Date.parse(txtData.split("/").reverse().join("/"))){
            return true;
        }else{
            return false;
        }
    }
    function valid_senha(campo1,campo2) {
        if(campo1 == campo2){
            return true;
        }else{
            return false;
        }
    }
    function valid_cpf(cpf) {
        if ( cpf != '' ) {
            var soma;
            var multiplicador;
            var dig1 = 0;
            var dig2 = 0;
            var verifica;
            var ExpReg = /^(\d{3}).(\d{3}).(\d{3})-(\d{2})$/;
            if ( cpf.search(ExpReg) == -1 ) {
                return false;
            }
            cpf = cpf.replace("\.","");
            cpf = cpf.replace("\.","");
            cpf = cpf.replace("-","");
            if(cpf.match("11111111111")!=null) {
                return false
            } else if(cpf.match("22222222222")!=null) {
                return false
            } else if(cpf.match("33333333333")!=null) {
                return false
            } else if(cpf.match("44444444444")!=null) {
                return false;
            } else if(cpf.match("55555555555")!=null) {
                return false;
            } else if(cpf.match("66666666666")!=null) {
                return false;
            } else if(cpf.match("77777777777")!=null) {
                return false;
            } else if(cpf.match("88888888888")!=null) {
                return false;
            } else if(cpf.match("99999999999")!=null) {
                return false;
            }
            verifica = cpf.match("00000000000");
            if ( verifica == null ) {
                soma = 0;
                multiplicador = 10;
                for ( i = 0; i < 9; i++ ) {
                    soma += parseInt(cpf.substr(i,1) * multiplicador);
                    multiplicador--;
                }
                dig1 = parseInt(11 - (soma % 11));
                if ( dig1 == 11 || dig1 == 10 )
                    dig1 = 0;
                soma = 0;
                multiplicador = 11;
                for ( i = 0; i < 10; i++ ) {
                    soma += parseInt(cpf.substr(i,1) * multiplicador);
                    multiplicador--;
                }
                dig2 = parseInt(11 - (soma % 11));
                if ( dig2 == 11 || dig2 == 10 )
                    dig2 = 0;
                if ( !( ( dig1 == parseInt(cpf.substr(9,1)) ) && ( dig2 == parseInt(cpf.substr(10,1)) ) ) ) {
                    return false;
                }
            }
            else {
                return false;
            }
            return true;
        }
    }
    function valid_cnpj(valor) {
        valor = valor.replace("\.","");
        valor = valor.replace("\.","");
        valor = valor.replace(".","");
        valor = valor.replace("/","");
        valor = valor.replace("-","");
        var erro = false;
        if ( valor != '' ) {
            if ( valor.length != 14 )
                erro = true;
            var numeros = valor.split('');
            var igual = true;
            for ( j = 1; j < 14; j++ ) {
                if ( numeros[j] != numeros[0] ) {
                    igual = false;
                    break;
                }
            }
            if ( igual )
                erro = true;
            var soma = 0;
            var fator = 5;
            for ( j = 0; j < 12 ; j++ ) {
                soma += fator * numeros[j];
                fator--;
                if ( fator == 1 )
                    fator = 9;
            }
            var resultado = soma % 11;
            if ( resultado == 1 || resultado == 0 ) {
                if ( numeros[12] != 0 )
                    erro = true;
            }
            else {
                if ( numeros[12] != 11 - resultado )
                    erro = true;
            }
            soma = 0;
            fator = 6;
            for ( j = 0; j < 13 ; j++ ) {
                soma += fator * numeros[j];
                fator--;
                if ( fator == 1 )
                    fator=9;
            }
            resultado = soma%11;
            if ( resultado == 1 || resultado == 0 ) {
                if ( numeros[13] != 0 )
                    erro = true;
            }
            else {
                if ( numeros[13] != 11 - resultado )
                    erro = true;
            }
            if ( erro == true ) {
                return false;
            }
            return true;
        }
    }
})($);

/* ---------- SCRIPTS PADRÕES DO SITE ---------- */

$(document).ready(function(){
    
    $('#add_experiencia').click(function(){
        var url = LINK_BASE+"/curriculo/ajax.experiencia";
        jQuery.post(url, {
            add: exp++
        },
        function(data) {
            if(data){
                htmlExp += data;
                $("#add_exp_view").html(htmlExp);
            }
        });
    });
    
    $('#add_curso').click(function(){
        var url = LINK_BASE+"/curriculo/ajax.educacao";
        jQuery.post(url, {
            add: edu++
        },
        function(data) {
            if(data){
                htmlEdu += data;
                $("#add_curso_view").html(htmlEdu);
            }
        });
    });

    $('#add_idioma').click(function(){
        var url = LINK_BASE+"/curriculo/ajax.idioma";
        jQuery.post(url, {
            add: idi++
        },
        function(data) {
            if(data){
                htmlIdi += data;
                $("#add_idi_view").html(htmlIdi);
            }
        });
    });

    $("#estado_fk").change(function(){
        $("#cidade_fk").html('<option value="" selected="selected">Aguarde...</option>');
        var url = LINK_BASE+"/curriculo/ajax.cidades";
        jQuery.post(url, {
            estado_fk: $("#estado_fk option:selected").val()
        },
        function(data) {
            if(data){
                $("#cidade_fk").html(data);
            }
        });
    });
    
    $("#form-cad-news").submit(function(){
        //faço o ajax do newsletter
        
        doNewsAjax();
        
        return false;
    });
    
    $("#form-cad-news a.link").click(function(evento){
        evento.preventDefault();
        doNewsUndoAjax();
        return false;
    });
    
    $("#button").click(function(){
        
        });
    
});

function doNewsUndoAjax(){
    $.ajax({
        url : LINK_BASE + 'index/ajax.descadastranews/',
        data : 'email='+$("#form-cad-news .form-email").val(),
        dataType : 'html',
        type : 'POST',
        success : function(ret){
            alert(ret);
        }
    });
}

function doNewsAjax(){
    $.ajax({
        url : LINK_BASE + 'index/ajax.cadastranews/',
        data : 'nome='+$("#form-cad-news .form-nome").val()+'&email='+$(".form-email").val(),
        dataType : 'html',
        type : 'POST',
        success : function(ret){
            alert(ret);
        }
    });
}

function mycarousel_initCallback(carousel){
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });
		 
    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });
		 
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
}
		 
jQuery(document).ready(function() {
    jQuery('#mycarousel2').jcarousel();
});

function mycarousel_initCallback(carousel){
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });
		 
    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });
		 
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
}
		 
jQuery(document).ready(function() {
    jQuery('#mycarousel').jcarousel({
        scroll: 1,
        auto: 5,
        wrap: 'last',
        initCallback: mycarousel_initCallback
    });
});
/* ---------- SCRIPTS PADRÕES DO SITE FIM ---------- */

function validaEmail(email) {
    if(email == '') {
        return false;
    }else{
        var email_pattern  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if(email.match(email_pattern)) return true;
        return false;
    }
}

function limparPadrao(campo) {
    if (campo.value == campo.defaultValue) {
        campo.value = "";
    }
}

function escreverPadrao(campo) {
    if (campo.value == "") {
        campo.value = campo.defaultValue;
    }
}

function somente_numero(campo){
    var digits="0123456789"
    var campo_temp
    for (var i=0;i<campo.value.length;i++){
        campo_temp=campo.value.substring(i,i+1)
        if (digits.indexOf(campo_temp)==-1){
            campo.value = campo.value.substring(0,i);
        }
    }
}

$(document).ready(function(){
    $("ul.thumb li").hover(function() {
        $(this).css({
            'z-index' : '200'
        }); /*Add a higher z-index value so this image stays on top*/ 
        $(this).find('img').addClass("hover").stop() /* Add class of "hover", then stop animation queue buildup*/
        .animate({
            marginTop: '0px', /* The next 4 lines will vertically align this image */ 
            marginLeft: '-11px',
            width: '168px',
            height: '126px'
        }, 100); /* this value of "200" is the speed of how fast/slow this hover animates */

    } , function() {
        $(this).css({
            'z-index' : '0'
        }); /* Set z-index back to 0 */
        $(this).find('img').removeClass("hover").stop()  /* Remove the "hover" class , then stop animation queue buildup*/
        .animate({
            marginTop: '0',
            marginLeft: '0',
            width: '140px',
            height: '105px'
        }, 100);
    });
});
