var $vars = {
    'siret': $("#app_bundle_subscribe_form_siret"),
    'identifiant': $("#app_bundle_subscribe_form_identifiant"),
    'nom': $("#app_bundle_subscribe_form_nom"),
    'prenom': $("#app_bundle_subscribe_form_prenom"),
    'email': $("#app_bundle_subscribe_form_email"),
    'emailCheck': $("#app_bundle_subscribe_form_emailCheck"),
    'telephone': $("#app_bundle_subscribe_form_telephone"),
    'password': $("#app_bundle_subscribe_form_password"),
    'passwordCheck': $("#app_bundle_subscribe_form_passwordCheck"),
    'themBox': $("#thematique-box"),
    'error': $("#js-error")
}, errors = null;

function displayThematiques() {
    $.getJSON(Routing.generate("ajax_interloc_thematique", { 'siret': $vars.siret.val() }), function(data) {
        $vars.themBox.html('');
        $.each(data, function (e, i) {
            $vars.themBox.append('<div class="form-group mb-16">'+
                '<input id="app_bundle_subscribe_form_'+i.code+'" name="app_bundle_subscribe_form[thematique][]" type="checkbox" class="mr-8" value="'+i.code+'">'+
                '<label for="app_bundle_subscribe_form_'+i.code+'" class="control-label form-check-label">'+i.intitule+'</label>'+
            '</div>')
        })
    })
}

$(".FormCheck").on('click', function(e) {
    e.preventDefault();

    var $this = $(this),
        step = $this.data('step')
    ;

    $this.button('loading');
    console.log('click');

    switch (step) {
        case 1 :
            errors = { 'fields': {} };
            if($vars.siret.val().length !== 14) errors.fields.siret = "Le format du sirect est incorrect";
            if($.isEmptyObject(errors.fields)) {
                $.ajax({
                    'type': 'POST',
                    'url': Routing.generate('security_subCheck1'),
                    'data': {
                        'siret': $vars.siret.val(),
                        'identifiant': $vars.identifiant.val()
                    },
                    'success': function () {
                        clearErrors();
                        $this.button('reset');
                        nextStep(1);
                        displayThematiques();
                    },
                    'error': function (data) {
                        displayErrors(data.responseJSON);
                        $this.button('reset');
                    }
                });
            } else {
                $this.button('reset');
                displayErrors(errors);
            }
            break;
        case 2 :
            errors = { 'fields': {} };
            if($vars.nom.val()==="") errors.fields.nom = "Veuillez renseigner votre nom";
            if($vars.prenom.val()==="") errors.fields.prenom = "Veuillez renseigner votre prénom";
            if($vars.email.val()==="") errors.fields.email = "Veuillez renseigner votre email";
            if($vars.emailCheck.val()==="") errors.fields.emailCheck = "Veuillez confirmer votre email";
            if($vars.telephone.val().length !== 10) errors.fields.telephone = "Le format du téléphone est incorrect";
            if($vars.email.val() !== $vars.emailCheck.val()) errors.fields.emailCheck = "Les emails sont différents";
            if($.isEmptyObject(errors.fields)) {
                $.ajax({
                    'type': 'POST',
                    'url': Routing.generate('security_subCheck2'),
                    'data': {
                        'nom': $vars.nom.val(),
                        'prenom': $vars.prenom.val(),
                        'email': $vars.email.val(),
                        'emailCheck': $vars.emailCheck.val(),
                        'telephone': $vars.telephone.val()
                    },
                    'success': function () {
                        clearErrors();
                        $this.button('reset');
                        nextStep(2);
                    },
                    'error': function (data) {
                        displayErrors(data.responseJSON);
                        $this.button('reset');
                    }
                });
            } else {
                $this.button('reset');
                displayErrors(errors);
            }
            break;
        case 3 :
            $.ajax({
                'type': 'POST',
                'url': Routing.generate('security_subCheck3'),
                'data': {
                    'password': $vars.password.val(),
                    'passwordCheck': $vars.passwordCheck.val()
                },
                'success': function() {
                    clearErrors();
                    $this.button('reset');
                    nextStep(3);
                },
                'error': function(data) {
                    displayErrors(data.responseJSON);
                    $this.button('reset');
                }
            });
            break;
        case 4 :
            console.log('step 4');
            var checked = 0;
            $('#thematique-box input:checked').each(function(e,i){
                checked = 1;
                console.log(e,i,checked)
            });
            console.log(checked);
            if(checked === 0){
                displayErrors({
                    'fields': {
                        'step4main': 'Veuillez choisir au moins une thématique'
                    }
                });
            } else {
                clearErrors();
                nextStep(4);
            }
            $this.button('reset');
            break;
        case 5 :
            var cgu = 0, cookies = 0; errors = { 'fields': {} };
            if($("#app_bundle_subscribe_form_cgu:checked").val()){
                cgu = 1;
            } else {
                cgu = 0;
                errors.fields.cgu = 'Vous devez accepter les CGU pour vous inscrire'
            }
            if($("#app_bundle_subscribe_form_cookies:checked").val()){
                cookies = 1;
            } else {
                cookies = 0;
                errors.fields.cookies = "Vous devez accepter l'utilisation des cookies pour vous inscrire"
            }
            $this.button('reset');

            if(cgu && cookies){
                $("form").submit();
            } else {
                displayErrors(errors);
            }

    }
});

function displayErrors(errors) {
    clearErrors();
    console.log(errors);
    if(errors.global) {
        $vars.error.html('').html('Erreur : '+errors.global).show();
    }
    console.log(errors.fields);
    $.each(errors.fields, function(i, v){
        console.log(i, v);
        $("#"+i).addClass("has-error").find('.help-block').html(v).show();
    })
}

function clearErrors() {
    $vars.error.hide();
    $('.form-group').removeClass("has-error");
    $('.help-block').html('').hide();
}