jQuery(document).ready(function () {


    $('#custom_carousel').on('slide.bs.carousel', function (evt) {
        $('#custom_carousel .controls li.active').removeClass('active');
        $('#custom_carousel .controls li:eq(' + $(evt.relatedTarget).index() + ')').addClass('active');
    });

    $(document).on('click', '.show_more', function () {
        var time = Date.now();
        var ID = $(this).attr('id');
        $('.show_more').hide();
        $('.loding').show();
        $.ajax({
            type: 'POST',
            url: 'ajax/more_post.php?version=' + time,
            data: 'id=' + ID,
            success: function (html) {
                $('#show_more_main' + ID).remove();
                $('.postList').append(html);
            }
        });
    });

     //Load more data marques
     $(document).on('click', '.regenerate', function () {
        var time = Date.now();
        data = {
            action: 'regenerate_captcha'
        };
        $.ajax({
            type: 'POST',
            url: 'ajax/recaptcha.php?version=' + time,
            data: data,
            success: function () {
                $('.img-captcha').attr('src','ajax/recaptcha.php?' + new Date().getTime());
                $('#panel-recaptcha-error').hide();

            }
        });
    });


    $(document).on('click', '#go_option_vo', function () {
        $("html, body").animate({
            scrollTop: $(".tb_description_vo").offset().top
    }, 2000);
        $('.tab_onglet_0').removeClass('active');
        $('#onglet-0').removeClass('active fade in');
        $('.tab_onglet_2').removeClass('active');
        $('#onglet-2').removeClass('active fade in');
        $('.tab_onglet_1').addClass('active');
        $('#onglet-1').addClass('active fade in');
    });

    jQuery('.tp-banner').show().revolution(
            {
                dottedOverlay: "none",
                delay: 9000,
                startwidth: 1170,
                startheight: 550,
                hideThumbs: 200,
                thumbWidth: 100,
                thumbHeight: 50,
                thumbAmount: 5,
                navigationType: "none",
                navigationArrows: "solo",
                navigationStyle: "preview2",
                touchenabled: "on",
                onHoverStop: "on",
                swipe_velocity: 0.7,
                swipe_min_touches: 1,
                swipe_max_touches: 1,
                drag_block_vertical: false,
                keyboardNavigation: "on",
                navigationHAlign: "center",
                navigationVAlign: "bottom",
                navigationHOffset: 0,
                navigationVOffset: 20,
                soloArrowLeftHalign: "left",
                soloArrowLeftValign: "center",
                soloArrowLeftHOffset: 20,
                soloArrowLeftVOffset: 0,
                soloArrowRightHalign: "right",
                soloArrowRightValign: "center",
                soloArrowRightHOffset: 20,
                soloArrowRightVOffset: 0,
                shadow: 0,
                fullWidth: "on",
                fullScreen: "off",
                spinner: "spinner0",
                stopLoop: "off",
                stopAfterLoops: -1,
                stopAtSlide: -1,
                shuffle: "off",
                autoHeight: "off",
                forceFullWidth: "off",
                hideThumbsOnMobile: "off",
                hideNavDelayOnMobile: 1500,
                hideBulletsOnMobile: "off",
                hideArrowsOnMobile: "off",
                hideThumbsUnderResolution: 0,
                hideSliderAtLimit: 0,
                hideCaptionAtLimit: 0,
                hideAllCaptionAtLilmit: 0,
                startWithSlide: 0
            });





    //show login form
    $(document).on('click', '#btn-have-account', function () {
        $('html, body').animate({scrollTop: '130px'}, 500);
        have_account();
    });

    //Hide login form
    $(document).on('click', '#back-new-account', function () {
        $('html, body').animate({scrollTop: '130px'}, 500);
        create_new_account();
    });

    //Show form forget password
    $(document).on('click', '#link-forget-pass', function () {
        $('.brud_connect').hide();
        $('.brud_sign').hide();
        $('.brud_forget').show();
        $('#bloc-forget-password').fadeIn();
        $('#bloc-login-account').fadeOut();
        forget_password_form(null);
    });

    $(document).on('click', '#link-back-login', function () {
        $('.brud_sign').hide();
        $('.brud_forget').hide();
        $('.brud_connect').show();
        $('#bloc-forget-password').fadeOut();
        $('#bloc-login-account').fadeIn();
        login_form(null);
    });

    //Remember me
    $(document).on('click', '#remember_connect', function () {
        if ($('#remember_connect').is(':checked')) {
            // save username and password
            localStorage.email_connect = $('#email_login').val();
            localStorage.pass_connect = $('#password_login').val();
            localStorage.chkbx_connect = $('#remember_connect').val();
        } else {
            localStorage.email_connect = '';
            localStorage.pass_connect = '';
            localStorage.chkbx_connect = '';
        }
    });




    check_remember();
    create_account_espacepro();
    connect_espacepro();
    send_code_forgetpassword();

    if ($('.financement_vo').length > 0) {
        loadfinancementVo();
    }

    $(document).on('change', '#range_month', function () {
        $('#financement_year').val($(this).val() / 12);
        $('.nbr_mois').html($(this).val());
        $('.mensualite_final').html($('#finnocar_mensualite_' + $(this).val()).val() + ' ' + DeviseAppSociete());
    });

    $(document).on('change', '#range_apport', function () {
        $('#financement_apport').val($(this).val());
        loadfinancementVo();
    });

    $('.my-rating-4').starRating({
        totalStars: 5,
        starShape: 'rounded',
        starSize: 23,
        emptyColor: 'lightgray',
        activeColor: '#eab959',
        useGradient: false,
        readOnly: true
    });


    if (window.location.hash === '#success') {
        $.post("ajax/stripe.php", {idVehicule: $('#checkout-button').attr('data-id')}).done(function (response) {
            if (parseInt(response, 10) === 1) {
                $('#container-stripe').removeClass('hide-element').find('.alert').addClass('alert-success').append('<strong>Bravo, </strong> Votre paiement à été traité avec succès. <br/> Veuillez vous assurer que vous regardez bien la boîte de réception correspondant à l\'adresse e-mail que vous avez entré lors de votre paiement.');
            }
        });
    } else if (window.location.hash === '#cancel') {
        $('#container-stripe').removeClass('hide-element').find('.alert').addClass('alert-danger').append('<strong>Erreur est survenue, </strong> Votre paiement a été refusé merci de renouveler l\'opération.');
    }

});

function update_password_forget() {
    $('#forms-update-password-forget').formValidation({
        framework: 'bootstrap',
        icon: {
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            clientscol_token: {
                validators: {
                    notEmpty: {
                        message: 'Le code de réinitialisation est obligatoire'
                    }
                }
            },
            update_new_password: {
                validators: {
                    notEmpty: {
                        message: 'Le nouveau mot de passe est obligatoire'
                    },
                    stringLength: {
                        min: 6,
                        message: 'Le nouveau mot de passe doit être plus de 6 caractères'
                    },
                    identical: {
                        field: 'update_confirm_new_password',
                        message: 'Le nouveau mot de passe et sa confirmation ne sont pas identiques'
                    }
                }
            },
            update_confirm_new_password: {
                validators: {
                    notEmpty: {
                        message: 'Le mot de passe de confirmation est obligatoire'
                    },
                    identical: {
                        field: 'update_new_password',
                        message: 'Le nouveau mot de passe et sa confirmation ne sont pas identiques'
                    }
                }
            }
        }
    }).on('success.form.fv', function (e) {
        e.preventDefault();
        var time = Date.now();
        $.ajax({
            type: "POST",
            data: new FormData(this),
            url: "ajax/espace_pro.php?op=update_password_forget&version=" + time,
            contentType: false, // The content type used when sending data to the server.
            cache: false, // To unable request pages to be cached
            processData: false,
            async: true,
            headers: {
                "cache-control": "no-cache"
            },
            beforeSend: function () {
                setTimeout(function () {
                    $('#panel-succes-forget').hide();
                    $('#btn-update-new-pass').prop("disabled", true);
                    $('#btn-update-new-pass').html('<i class="fa fa-spinner fa-spin"></i>  Mettre à jour');
                }, 0);
            },
            success: function (data) {
                setTimeout(function () {
                    if (data == 'ERROR_TOKEN') {
                        $('#panel-error-token').slideDown();
                        $('#btn-update-new-pass').prop("disabled", false);
                        $('#btn-update-new-pass').html('<i class="fa fa-edit"></i>  Mettre à jour');
                    } else {

                    }
                }, 1500);
            }
        });
    });
}

function create_account_espacepro() {
    $('#forms-create-account').formValidation({
        framework: 'bootstrap',
        icon: {
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            clientscol_naissance_nom: {
                validators: {
                    notEmpty: {
                        message: 'Le nom est obligatoire'
                    }
                }
            },
            clientscol_naissance_prenom: {
                validators: {
                    notEmpty: {
                        message: 'Le prénom est obligatoire'
                    }
                }
            },
            clientscol_raisonsociale: {
                validators: {
                    notEmpty: {
                        message: 'La société est obligatoire'
                    }
                }
            },
            clientscol_email: {
                validators: {
                    notEmpty: {
                        message: 'L\'adresse email est obligatoire'
                    },
                    regexp: {
                        regexp: '^[^@\\s]+@([^@\\s]+\\.)+[^@\\s]+$',
                        message: "Le format de l'adresse email est invalide"
                    }
                }
            },
            clientscol_pwd: {
                validators: {
                    notEmpty: {
                        message: 'Le mot de passe est obligatoire'
                    },
                    stringLength: {
                        min: 6,
                        message: 'Le mot de passe doit être plus de 6 caractères'
                    },
                    identical: {
                        field: 'clientscol_pwd_c',
                        message: 'Le mot de passe et sa confirmation ne sont pas identiques'
                    }
                }
            },
            clientscol_pwd_c: {
                validators: {
                    notEmpty: {
                        message: 'Le mot de passe de confirmation est obligatoire'
                    },
                    identical: {
                        field: 'clientscol_pwd',
                        message: 'Le mot de passe et sa confirmation ne sont pas identiques'
                    }
                }
            },
            captcha_input: {
                validators: {
                    notEmpty: {
                        message: 'Veuillez saisir le code reCAPTCHA'
                    }
                }
            }
        }
    }).on('success.form.fv', function (e) {
        e.preventDefault();
        var time = Date.now();
        $.ajax({
            type: "POST",
            data: new FormData(this),
            url: "ajax/espace_pro.php?op=create_account&version=" + time,
            contentType: false, // The content type used when sending data to the server.
            cache: false, // To unable request pages to be cached
            processData: false,
            async: true,
            headers: {
                "cache-control": "no-cache"
            },
            beforeSend: function () {
                setTimeout(function () {
                    $('#panel-create-account').hide();
                    $('.into-succes-inscription').html('');
                    $('#btn-validate-account').prop("disabled", true);
                    $('#btn-validate-account').html('<i class="fa fa-spinner fa-spin"></i> Créer un compte');
                }, 0);
            },
            success: function (data) {
                setTimeout(function () {
                    $('#btn-validate-account').prop("disabled", false);
                    $('#btn-validate-account').html('Créer un compte');
                    if (data == 'EMAIL_EXIST') {
                        $('html, body').animate({scrollTop: '150px'}, 500);

                        register_form('error_account_email');

                    } else if (data == 'recuptcha_invalid') {
                        $('#panel-recaptcha-error').show();
                    } else {
                        $('html, body').animate({scrollTop: '150px'}, 500);

                        register_form('succes_account');
                    }
                }, 1500);
            }
        });
    });
}

function connect_espacepro() {
    $('#forms-login-account').formValidation({
        framework: 'bootstrap',
        icon: {
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            email_login: {
                validators: {
                    notEmpty: {
                        message: 'L\'adresse email est obligatoire'
                    },
                    regexp: {
                        regexp: '^[^@\\s]+@([^@\\s]+\\.)+[^@\\s]+$',
                        message: "Le format de l'adresse email est invalide"
                    }
                }
            },
            password_login: {
                validators: {
                    notEmpty: {
                        message: 'Le mot de passe est obligatoire'
                    },
                    stringLength: {
                        min: 6,
                        message: 'Le mot de passe doit être plus de 6 caractères'
                    },
                }
            }
        }
    }).on('success.form.fv', function (e) {
        e.preventDefault();
        var time = Date.now();
        $.ajax({
            type: "POST",
            data: new FormData(this),
            url: "ajax/espace_pro.php?op=verif_login&version=" + time,
            contentType: false, // The content type used when sending data to the server.
            cache: false, // To unable request pages to be cached
            processData: false,
            async: true,
            headers: {
                "cache-control": "no-cache"
            },
            beforeSend: function () {
                setTimeout(function () {
                    $('#panel-error-connect').hide();
                    $('#msg_connect_login').html("");
                    $('#btn-verif-login').prop("disabled", true);
                    $('#btn-verif-login').html('<i class="fa fa-spinner fa-spin"></i> Se connecter');
                }, 0);
            },
            success: function (data) {
                setTimeout(function () {
                    if (data == 'FALSE_IDENT_USER') {
                        $('#panel-error-connect').slideDown();
                        $('#msg_connect_login').html("Connexion refusée, L'adresse email ou mot de passe incorrect");
                    } else if (data == 'VALIDATE_IDENT_USER') {
                        $('#panel-error-connect').slideDown();
                        $('#msg_connect_login').html("Connexion refusée, Compte en attente de validation");
                    } else if (data == 'TRUE_IDENT_USER') {
                        $(location).attr('href', "index.php?p=profil");
                    }
                    $('#btn-verif-login').html('Se connecter');
                    $('#btn-verif-login').prop("disabled", false);
                }, 1000);
            }
        });
    });
}

function send_code_forgetpassword() {
    $('#forms-forget-password').formValidation({
        framework: 'bootstrap',
        icon: {
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            email_forget: {
                validators: {
                    notEmpty: {
                        message: 'L\'adresse email est obligatoire'
                    },
                    regexp: {
                        regexp: '^[^@\\s]+@([^@\\s]+\\.)+[^@\\s]+$',
                        message: "Le format de l'adresse email est invalide"
                    }
                }
            }
        }
    }).on('success.form.fv', function (e) {
        e.preventDefault();
        var time = Date.now();
        $.ajax({
            type: "POST",
            data: new FormData(this),
            url: "ajax/espace_pro.php?op=send_confirmation_code&version=" + time,
            contentType: false, // The content type used when sending data to the server.
            cache: false, // To unable request pages to be cached
            processData: false,
            async: true,
            headers: {
                "cache-control": "no-cache"
            },
            beforeSend: function () {
                setTimeout(function () {
                    $('#btn-send-code').prop("disabled", true);
                    $('#btn-send-code').html('<i class="fa fa-spinner fa-spin"></i> Générer un nouveau mot de passe');
                }, 0);
            },
            success: function (data) {
                setTimeout(function () {
                    if (data == 'FALSE_MEAIL') {
                        $('#panel-error-forget').slideDown();
                        forget_password_form('msg_sc');
                    } else if (data == 'NEW_PASSWORD') {
                        $('#bloc-forget-password').fadeOut();
                        $('#bloc-login-account').fadeIn();
                        login_form('new_pass');
                    }
                }, 1500);
            }
        });
    });
}

function register_form(action) {
    var time = Date.now();
    data = {
        action: 'get_form_register'
    };
    $.ajax({
        type: "POST",
        url: "ajax/espace_pro.php?version=" + time,
        data: data,
        success: function (data) {
            $('#bloc-create-account').html(data);
            if (action == 'error_account_email') {
                $('#panel-create-account-error').show();
                $('.into-succes-inscription-error').html("Cette adresse email est déjà utilisée, merci de renseigner une autre.");
            } else if (action == 'succes_account') {
                $('#panel-create-account').show();
                $('.into-succes-inscription').html('Votre inscription a bien été enregistrée, vous recevrez un email pour vous informer, une fois que votre demande a été acceptée.');
            }
            //FORM VALIDATION AND SUBMIT DATA
            create_account_espacepro();
        }
    });
}

function login_form(action) {
    var time = Date.now();
    data = {
        action: 'get_form_login'
    };
    $.ajax({
        type: "POST",
        url: "ajax/espace_pro.php?version=" + time,
        data: data,
        success: function (data) {
            $('#bloc-login-account').html(data);
            if (action == 'new_pass') {
                $('#panel-new-password-forget').show();
            }
            //FORM VALIDATION AND SUBMIT DATA
            check_remember();
            connect_espacepro();
        }
    });
}

function forget_password_form(action) {
    var time = Date.now();
    data = {
        action: 'get_form_forget'
    };
    $.ajax({
        type: "POST",
        url: "ajax/espace_pro.php?version=" + time,
        data: data,
        success: function (data) {
            $('#bloc-forget-password').html(data);
            if (action == 'msg_sc') {
                $('#panel-error-forget').show();
            }
            //FORM VALIDATION AND SUBMIT DATA
            send_code_forgetpassword();
        }
    });
}

function check_remember() {
    if (localStorage.chkbx_connect && localStorage.chkbx_connect != '') {
        $('#remember_connect').attr('checked', 'checked');
        $('#email_login').val(localStorage.email_connect);
        $('#password_login').val(localStorage.pass_connect);
    } else {
        $('#remember_connect').removeAttr('checked');
        $('#email_login').val('');
        $('#password_login').val('');
    }
}

function have_account() {
    $('#bloc-create-account').fadeOut();
    $('#bloc-login-account').fadeIn();
    $('#btn-have-account').hide();
    $('#back-new-account').show();
    $('.brud_sign').hide();
    $('.brud_forget').hide();
    $('.brud_connect').show();
    $('#bloc-forget-password').hide();
}

function create_new_account() {
    $('#bloc-create-account').fadeIn();
    $('#bloc-login-account').fadeOut();
    $('#btn-have-account').show();
    $('#back-new-account').hide();
    $('#bloc-forget-password').hide();
    $('.brud_connect').hide();
    $('.brud_forget').hide();
    $('.brud_sign').show();
    $('#bloc-forget-password').hide();
    register_form(null);
    login_form(null);
    forget_password_form(null);
}

const loadfinancementVo = () => {
    data = {
        financement_montant: $('#financement_montant').val(),
        financement_modele: $('#financement_modele').val(),
        financement_year: $('#financement_year').val(),
        financement_apport: $('#financement_apport').val(),
        financement_type: $('#financement_type').val(),
    };
    $.ajax({
        type: "POST",
        url: "/sadmin/ajax/vo/financement.php",
        data: data,
        success: function (data) {
            $('.financement_vo').html(data);
        }
    });
};