var $vars = {
    'nom': $("#user_update_nom"),
    'prenom': $("#user_update_prenom"),
    'telephone': $("#user_update_telephone"),
    'email': $("#user_update_email"),
    'current': $("#password_update_current"),
    'new': $("#password_update_new"),
    'siret': $("#app_bundle_add_user_interloc_siret"),
    'identifiant': $("#app_bundle_add_user_interloc_identifiant"),
    'confirmation': $("#password_update_confirmation"),
    'userFormBtn': $("#userFormSubmit"),
    'pwFormBtn': $("#pwFormSubmit"),
    'interlocFormBtn': $("#interlocFormSubmit"),
    'error': $('#js-error'),
    'loading': $('.js-loading')
}, errors = null;

$vars.userFormBtn.on('click', function(){
    errors = {'fields': {}};
    $vars.userFormBtn.button('loading');

    $.ajax({
        'type': 'POST',
        'url': Routing.generate('user_update'),
        'data': {
            'nom': $vars.nom.val(),
            'prenom': $vars.prenom.val(),
            'telephone': $vars.telephone.val(),
            'email': $vars.email.val()
        },
        'success': function () {
            clearErrors();
            $vars.userFormBtn.button('reset');
            swal({
                title: "Succès !",
                text: "Informations sauvegardées",
                icon: "success",
                button: {
                    text: "OK",
                    className: "bg-orange hoverOpacity"
                }
            }).then(
                $(".modal").modal('hide')
            );
        },
        'error': function (data) {
            displayErrors(data.responseJSON);
            $vars.userFormBtn.button('reset');
        }
    });
});

$vars.interlocFormBtn.on('click', function(){
    console.log('interloc');
    errors = {'fields': {}};
    $vars.interlocFormBtn.button('loading');

    $.ajax({
        'type': 'POST',
        'url': Routing.generate('add_user_interlocuteur'),
        'data': {
            'siret': $vars.siret.val(),
            'identifiant': $vars.identifiant.val()
        },
        'success': function () {
            clearErrors();
            $vars.interlocFormBtn.button('reset');
            swal({
                title: "Succès !",
                text: "Interlocuteur ajouté",
                icon: "success",
                button: {
                    text: "OK",
                    className: "bg-orange hoverOpacity"
                }
            }).then(
                window.location.reload()
            );
        },
        'error': function (data) {
            swal({
                title: "Erreur !",
                text: data.responseJSON,
                icon: "error",
                button: {
                    text: "OK",
                    className: "bg-error hoverOpacity"
                }
            });
            $vars.interlocFormBtn.button('reset');
        }
    });
});

$vars.pwFormBtn.on('click', function(){
    console.log('pw');
    errors = {'fields': {}};
    $vars.pwFormBtn.button('loading');

    $.ajax({
        'type': 'POST',
        'url': Routing.generate('password_update'),
        'data': {
            'current': $vars.current.val(),
            'new': $vars.new.val(),
            'confirmation': $vars.confirmation.val()
        },
        'success': function () {
            clearErrors();
            $vars.pwFormBtn.button('reset');
            swal({
                title: "Succès !",
                text: "Informations sauvegardées",
                icon: "success",
                button: {
                    text: "OK",
                    className: "bg-orange hoverOpacity"
                }
            }).then(
                $(".modal").modal('hide')
            );
        },
        'error': function (data) {
            displayErrors(data.responseJSON);
            $vars.pwFormBtn.button('reset');
        }
    });
});

$(".js-them").on("change", function(){
    stopTimeOut();
    beginTimeOut();
});

var timeOut;

function beginTimeOut() {
    timeOut = setTimeout(updateThematiques, 1500);
}

function stopTimeOut() {
    clearTimeout(timeOut);
}

function updateThematiques(){
    $vars.loading.show();
    var thems = [];

    $(".js-them:checked").each(function(e, i){
        thems.push($(this).val());
    });

    if(thems.length === 0) {
        $vars.loading.hide();
        swal({
            title: "Attention !",
            text: "Vous devez sélectionner au moins une thématique",
            icon: "warning",
            button: {
                text: "OK",
                className: "bg-orange hoverOpacity"
            }
        })
    } else {
        $.ajax({
            'type': 'POST',
            'url': Routing.generate("thematique_update"),
            'data': {
                'thems': thems
            },
            'success': function () {
                $vars.loading.hide();
                swal({
                    title: "Succès !",
                    text: "Thématiques sauvegardées",
                    icon: "success",
                    button: {
                        text: "OK",
                        className: "bg-orange hoverOpacity"
                    }
                });
            },
            'error': function () {
                $vars.loading.hide();
                swal({
                    title: "Erreur !",
                    text: "Une erreur s'est produite, veuillez contactez le service technique",
                    icon: "error",
                    button: {
                        text: "OK",
                        className: "bg-error-swal hoverOpacity"
                    }
                })
            }
        })
    }
}

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();
}