var value_progress = 1;
var add_progress = 1;
var step;
isWaiting = false;
var ttStep = $('.step').length;
var total_progress = 100/ttStep;
var id_imovel = $('#id_imovel').val();
var id_simulacao = $('#id_simulacao').val();
var w = $(this).width();

var tipo_pessoa;

var Campos_obrigatorios =
[
    [],//STEP 0
    //['tipo_pessoa','data_nascimento','renda_familiar','recaptcha'],
    ['tipo_pessoa','data_nascimento','renda_familiar'],//g-recaptcha-response -> no valida campos
    [],
    [],
    [],
];

$(window).on('load', function(){
    //id_imovel = $('#id_imovel').val();
    
    step = 1;
    
    iniciaStep();
    //console.log('step',step);
    if(step > 0){
		widgetId1 = grecaptcha.render('gcaptcha', {
            'sitekey' : sitekey,
            'theme' : 'light'
		});
    }
    if(w <=991){
        $("#gcaptcha").children("div").css("width","290px");
    }
    
    verificaTipopessoa();
    
});

/*$.fn.start_captcha = function()
{
	$('.captcha').fadeIn();
	widgetId1 = grecaptcha.render('gcaptcha', {
        'sitekey' : sitekey,
        'theme' : 'light'
	});
}*/

function getForm(){
    data = [];
    data.push({name: "id_imovel",value: id_imovel});
    data.push({name: "id_simulacao",value: id_simulacao});
    data.push({name: "step",value: step});
    $('#form-financ-etapas').find('input:not([type=radio]):input:not([type=checkbox]),textarea').each(function(key,value){
        if(this.name != "")data.push({"name": this.name, "value": this.value});});
        
    $('#form-financ-etapas').find('input[type=radio]:checked').each(function(key,value)    {
        if(this.name != "")data.push({"name": this.name, "value": this.value});});
        
    $('#form-financ-etapas').find('select option:selected').each(function(key,value)    {
        if(this.parentElement.localName == 'select')
            data.push({"name": this.parentElement.name, "value": this.value});
        if(this.parentElement.parentElement.localName == 'select')
            data.push({"name": this.parentElement.parentElement.name, "value": this.value});});
    
    $('#form-financ-etapas').find('input[type=checkbox]:checked').each(function(key,value)    {
        if(this.name != "")
            data.push({"name": this.name, "value": this.value});
    });
            
    $('#form-financ-etapas input[type=checkbox]:not(:checked)').each(function(key,value)    {
        if(this.name != "")data.push({"name": this.name, "value": ""});});
        
        
        
    /*$('#form-financ-etapas').find('input:not([type=radio]):input:not([type=checkbox]):input:not([type=file])').each(function(key,value){
        if(this.name != "")
            data.push({"name": this.name, "value": this.value});
    });
   
    $('#form-financ-etapas').find('input[type=radio]:checked').each(function(key,value)    {
        if(this.name != "")
            data.push({"name": this.name, "value": this.value});
    });
    $('#form-financ-etapas').find('select option:selected').each(function(key,value)    {
        if(this.parentElement.localName == 'select')
            data.push({"name": this.parentElement.name, "value": this.value});
            
        if(this.parentElement.parentElement.localName == 'select')
            data.push({"name": this.parentElement.parentElement.name, "value": this.value});
    });
    
    $('#form-financ-etapas').find('input[type=checkbox]:checked').each(function(key,value)    {
        if(this.name != "")
            data.push({"name": this.name, "value": this.value});
    });
    
    $('#form-financ-etapas').find('input[type=checkbox]:not(:checked)').each(function(key,value)    {
        if(this.name != "")
            data.push({"name": this.name, "value": ""});
    }); */   
    
    return data;
}

function iniciaStep(){
    
    var divStep = $(".step");
    $.each(divStep, function(key,div){
        $(this).addClass('step-'+(key+1));
    });
    
    $('.pro-etapa').addClass('bg-info').animate({width: total_progress +"%"}, 50 );
    step--;
    nextStep();
    $('body').on('click','.a-step', aStep);
}

function nextStep(){
    if(step < ttStep)
    {
        $('.step-'+step).hide();
        step++;
        
        //console.log('nextStep',step);
        
        $('.step-'+step).show('clip');
        $('.t-etapa').html('Etapa '+step);
        $('.pro-etapa').addClass('bg-info').animate({width: total_progress * step +"%"}, 50 );
        if(ttStep == step)//penultimo step
        {
            
            $('.a-step').hide();
            
            
            //$('.btn_proximo').addClass('concluirCadastro');
            $('.btn_proximo').addClass('btn-success');
            
            //$('.btn_proximo').removeClass('p-step');
            $('.btn_proximo').removeClass('btn-primary');
            $('.btn_proximo').html('Concluir');
            
            
            $('.pro-etapa').removeClass('bg-info').addClass('bg-success');
        }
        setTimeout(function(){ $('body').on('click','.p-step', pStep); }, 500);
        
        $('html, body').animate({
            scrollTop: $("main").offset().top
        }, 500);
    } 
    else
    {
        setTimeout(function(){ $('body').on('click','.p-step', pStep); }, 500);
    } 
} 

function backStep(){
    if(ttStep == step)
    {
        $('.btn_proximo').removeClass('concluirCadastro');
        $('.btn_proximo').removeClass('btn-success');
        
        $('.btn_proximo').addClass('p-step');
        $('.btn_proximo').addClass('btn-primary');
        $('.btn_proximo').html('Próximo');
    }
    
    if((step - 1) > 0)
    {
        $('.step-'+step).hide();
        step--;
        
        $('.step-'+step).show('clip');
        $('.t-etapa').html('Etapa '+step);
        $('.pro-etapa').addClass('bg-info').animate({width: total_progress * step +"%"}, 50 );
        $('.pro-etapa').addClass('bg-success').addClass('bg-info');
    }
    else
    {
        $.ajax({
    		url: base_url+"comdono/ajax/financiamento_ajax/atualiza_simulacao",
    		dataType: 'json',
    		type: 'POST',
    		data: {step: 0, id_simulacao: id_simulacao},
    		success: function(retorno)
    		{
    		        location.reload();
    		    
    		},
    		error: function(error)
    		{
    		    console.log(error);
    		}
    	});
    }
}

// btn proximo step
function pStep(){
    $('body').off('click','.p-step', pStep);
    
    loadButton($(this));
    
    //loadButton(null,false);
    //nextStep();
    
    form = getForm();
    if(validaStep())//Erros estao na function validaStep()
    {
    	$.ajax({
    		url: base_url+"comdono/ajax/financiamento_ajax/atualiza_simulacao",
    		dataType: 'json',
    		type: 'POST',
    		data: form,
    		success: function(retorno)
    		{
    		    if(step == ttStep){
    		        //document.location.href = base_url+'imovel/'+id_imovel;
    		        if(retorno.redirect !== null){
    		            document.location.href = base_url;
    		        }else{
    		            document.location.href = base_url+'minha_conta/minhas_compras/financiamento/'+id_imovel;
    		        }    		    
    		    }
    		    else
    		    {
    		        loadButton(null,false);
    			    nextStep();
    		    }
    		},
    		error: function(error)
    		{
    			loadButton(null,false);
                setTimeout(function(){ $('body').on('click','.p-step', pStep); }, 500);
    		}
    	});
    }
    else
    {
        setTimeout(function(){ $('body').on('click','.p-step', pStep); }, 500);
    }
};

//btn anterior step
function aStep(){
    $('body').off('click','.a-step', aStep);
    
    loadButton($(this));
    
    backStep();
    
	loadButton(null,false);
    
    setTimeout(function(){ $('body').on('click','.a-step', aStep); }, 500);
    
    $('html, body').animate({
        scrollTop: $("main").offset().top
    }, 500);
    
};

function validaStep(){
    erros = true;
    
    $('#content-error').hide();
    
   
    dataForm = [];
    $.each(form, function(key,dt)    {
        dataForm[dt.name] = dt.value;
    }); 
    
    
    $.each(Campos_obrigatorios[step], function(key,campo)    {
        removeBorderRed(campo);
        if(dataForm[campo] == undefined || dataForm[campo] == ''){
            erros = false;
            addBorderRed(campo);
        }
    });
    
    
    if(!erros)
    {
        text = "Ops! Preencha os campos obrigatórios.";
        notifyErros(text)
        
        loadButton(null,false);
        
    }
    
    cpf = $('input[name=cpf]').val();
    
    if(step == 1 && tipo_pessoa == "cpf" && !validaCPF(cpf))
    {
        addBorderRed('cpf');
        text = "Ops! CPF inválido";
        notifyErros(text)
        loadButton(null,false);
        return false;
    }
    
    if(step == 1 && dataForm['g-recaptcha-response'] == '')
    {
        text = "Ops! Preencha o Não sou um robô.";
        notifyErros(text)
        loadButton(null,false);
        return false;
    }
    
    
    
        
    
    /*if(step == 3)
    {
        $r = false;
        $.each($('.banco'), function(key,imput)    {
            
            if($(this).attr('checked') == 'checked'){
                $r = true;
            }
        });
        if(!$r)
        {
            text = "Ops! Selecione ao menos um banco.";
            notifyErros(text)
            loadButton(null,false);
            return false;
        }
    }*/
    
    
    return erros;

}

function addBorderRed(campo){
    //console.log('borderRed ',campo);
    $('input[name='+campo+']').attr('style', 'border: 1px solid #ff5650 !important');
    $('select[name='+campo+']').attr('style', 'border: 1px solid #ff5650 !important');
}

function removeBorderRed(campo){
    $('input[name='+campo+']').removeAttr('style', 'border: 1px solid #ff5650 !important');
    $('select[name='+campo+']').removeAttr('style', 'border: 1px solid #ff5650 !important');
}

function addCampoObrigatorio(step, campo){
    key = Campos_obrigatorios[step].indexOf(campo);
    if(key == -1)
        Campos_obrigatorios[step].push(campo);
}

function removeCampoObrigatorio(step, campo){
    key = Campos_obrigatorios[step].indexOf(campo);
    if(key > -1)
        Campos_obrigatorios[step].splice(key, 1);
}


//submit
$('#form-financ').submit(function(event){	
    event.preventDefault();
    event.stopPropagation();
    
	loadButton($('.enviarProposta'));
	
	var valor = $("input[name=valor]").val();
	//var meses = $("input[name=meses] ").val();
	var meses = $('#change-meses option:selected').val();
	//var id_imovel = $("input[name=id_imovel]").val();
	
	//console.log("meses "+meses);
	
	var target = $(this).attr('action');
	//var data = $(this).serializeArray();
	
	data = {
	    valor: valor,
	    meses: meses,
	    id_imovel: id_imovel,
	    taxa: $rPorcentagem,
        val_parcelas: $rParcela,
        val_total: $rTotal,
	    bancos_aprovados: $bancosAprovados
 	}
	    
	$.ajax({
		url: base_url+'comdono/ajax/financiamento_ajax/iniciaSimulacao',
		dataType: 'json',
		type: 'POST',
		data: data,
		success: function(retorno)
		{	
		    //console.log("retorno: ",retorno.valid)
		    
			if (retorno.valid === true)
			{
			    document.location.href = retorno.redirect;
			}
			else
			{
			    loadButton(null,false);
		        ico = '<img src="'+base_url+'assets/img/comdono/icons/error.png'+'">';
                $('#content-error').show();
                $('#content-error').html('<label class="error-login"><span>'+ico+'</span>'+retorno.msg+'</label>');
			}
		},
		error: function(error)
		{
		    loadButton(null,false);
			ico = '<img src="'+base_url+'assets/img/comdono/icons/error.png'+'">';
            $('#content-error').show();
            $('#content-error').html('<label class="error-login"><span>'+ico+'</span>Não foi possível realizar o acesso! Falha na Comunicação.</label>');
			
		}
	});
	return false;
});

$('body').on('click','.enviarProposta', function(){
//http://dev.comdono.com/comdono/ajax/financiamento_ajax/index

    
});
$('body').on('click','.sairSimulacao', function(){
    
    window.location.href = base_url+'imovel/'+id_imovel;
    
});




$('body').on('change','input[name=tipo_pessoa]', function(){
    verificaTipopessoa();
});

function verificaTipopessoa(){
    tipo_pessoa = $("input[name='tipo_pessoa']:checked").val();
    

    if(tipo_pessoa == "cpf"){
        removeCampoObrigatorio(1, 'cnpj');
        addCampoObrigatorio(1, 'cpf');
        $('.container-cpf').removeClass('d-none');
        $('.container-cpf').show('clip');
        $('.container-cnpj').hide();
        
        //console.log('aqui');
        $.ajax(
        {
            url: base_url+'comdono/ajax/cad_ajax/get_cadastro_para_imovel',
            type: 'GET',
            dataType: 'json',
            success: function(result){
                
                console.log(result);
                
                ($('#cpf').val() == '')? $('#cpf').val(result.cad.cpf): '';
                 ($('#data_nascimento').val() == '')? $('#data_nascimento').val(result.cad.data_nascimento): '';
                //$('input[name=dn_nome_nomefantasia]').val(result.cad.nome);
                //$('input[name=dn_email]').val(result.cad.email);
                //$('input[name=dn_telefone]').val(result.cad.telefone);
                //$('input[name=dn_cpf_cnpj]').val(result.cad.cpf);
                //$('.box-razao-social').hide('clip');
                //$('#dn_razao_social').val("");
                
            
            },
            error: function(error)
    		{
    			console.log(error);
    		}
        });
        
        
    }
    else{
        removeCampoObrigatorio(1, 'cpf');
        addCampoObrigatorio(1, 'cnpj')
        $('.container-cpf').hide();
        $('.container-cnpj').removeClass('d-none');
        $('.container-cnpj').show('clip');
    }
}

/*
//Valor FGTS
$('body').on('change','input[name=possui_fgts]', function(){
   
    var possui_fgts = $("input[name='possui_fgts']:checked").val();
    
    if(possui_fgts == "on"){
        $('.container-valor-fgts').removeClass('d-none');
        $('.container-valor-fgts').show('clip');
    }
    else{
        $('.container-valor-fgts').hide('clip');
        $("input[name='valor_fgts']").val("");
    }
});*/

//bancos
$(".banco").change(function(){
    var banco = $(this).attr('checked');
    if(banco !== 'checked'){
        
        //console.log('false',$(this));
        
        $(this).attr('checked',true);
        $(this).parents('.container-item').find('.containerAgCt').show('clip');
    }
    else{
        //console.log('true',$(this));
        $(this).attr('checked',false);
        $(this).parents('.container-item').find('.containerAgCt').hide('clip');
        $(this).parents('.container-item').find('.agencia').val("");
        $(this).parents('.container-item').find('.conta').val("");
    }
});

//atualiza_banco_rel

//autoSave
$('body').on('change','.autoSave', function(){
   
    var idI = $(this).data('id_bc_rel');
    var name = $(this).data("name");
    var val = $(this).val();
    
    var form = [];
    
    form.push({"name": 'id_bc_rel', "value": idI});
    if(name == 'banco_chec' && $(this).attr('checked') != 'checked')
        form.push({"name": name, "value": ''});
    else
        form.push({"name": name, "value": val});
    
    $.ajax({
    		url: base_url+"comdono/ajax/financiamento_ajax/atualiza_banco_rel",
    		dataType: 'json',
    		type: 'POST',
    		data: form,
    		success: function(retorno)
    		{
    		    
    		},
    		error: function(error)
    		{
    		    console.log(error);
    		}
    	});
    
    
});