$(document).ready(function(){
    const _msg_error_inconnue='Une erreur inconnue est survenue.';
    $('.toggle-extra').on('click',function() {
        $(this).parent('p').find('.extra-text').slideToggle(300);
        if ($(this).hasClass('icon-chevron-down-circle'))
                $(this).removeClass('icon-chevron-down-circle').addClass('icon-chevron-up-circle');
        else
                $(this).removeClass('icon-chevron-up-circle').addClass('icon-chevron-down-circle');
    });
    $(document).on('keypress','form input', function (e) {//Avoid submitting form with ENTER key
        if (e.which == 13 || e.code=='Enter' || e.key=='Enter' ) {
              e.preventDefault();e.stopPropagation();
        }
    });
    $('.numbered').on('input', function() {
        $(this).val($(this).val().replace(/[^0-9]/g, ''));
    });
    $('.numbered').on('paste', function(e) {
        if (!/^\d+$/.test(e.originalEvent.clipboardData.getData('Text')))
            e.preventDefault();
    });
   new Swiper('.swiper-container', {
        loop: true,
        autoplay: {
            delay: 5000,
        },
        pagination: {
            el: '.swiper-pagination',
            clickable: true,  // Permet à l'utilisateur de cliquer sur les indicateurs de pagination
        },
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
        effect: 'slide',  //slide fade cube coverflow flip creative
        on: {
            slideChange: function () {
                // This ensures that elements animate only when the slide is active
                const activeSlide = this.slides[this.activeIndex];
                const slideTitle = activeSlide.querySelector('.slide-item h6');
                const slideHeading = activeSlide.querySelector('.slide-item h1');
                const slideLinks = activeSlide.querySelectorAll('.slide-item a');
    
                // Reset animations for all slides
                document.querySelectorAll('.slide-item h6, .slide-item h1, .slide-item a').forEach(el => {
                    el.style.opacity = 0;
                    el.style.transform = 'translateY(20px)';
                });
    
                // Trigger animation on the active slide
                slideTitle.style.opacity = 1;
                slideTitle.style.transform = 'translateY(0)';
                slideHeading.style.opacity = 1;
                slideHeading.style.transform = 'translateY(0)';
                slideLinks.forEach(link => {
                    link.style.opacity = 1;
                    link.style.transform = 'translateY(0)';
                });
            },
        }
    });

    $(document).on('submit','form', function (e) {
          e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();
          $('.error,input[type=submit]+span').removeClass('text-success').empty();
          const o=$(this);
          
          if(FormValidity()!==true) return ;
          else{
                  const f=new FormData(this);
                  $.get("/communs/c-loading.html", function(r){ 
                            $('input[type=submit]+span').html(r);
                            $('input[type=submit]').prop('disabled',true);
                            
                            if(o.hasClass('candidature')){
                                $.ajax({ type: "POST", url: "/ajax/candidature.php", contentType: false, processData:false, data:f,
                                    success: function (r) {
                                        $('input[type=submit]').prop('disabled',false);
                                        try {
                                            const rJson=JSON.parse(r);
                                            if(rJson.hasOwnProperty('data')){
                                                window.location.href ='/candidature-spontanee-success';
                                            } 
                                            else{
                                                $('.error').html(rJson.msg?rJson.msg:_msg_error_inconnue);
                                                $('input[type=submit]+span').html(`<span class='error'>${rJson.msg?rJson.msg:_msg_error_inconnue}</span>`);
                                            } 
                                        }
                                        catch(e) {
                                        $('.error').html(e.responseText);
                                        $('input[type=submit]+span').html(`<span class='error'>${e.responseText}</span>`);
                                        }
                                    },
                                    error: function(e) {
                                            $('input[type=submit]').prop('disabled',false);
                                            $('.error').html(e.responseText);
                                            $('input[type=submit]+span').html(`<span class='error'>${e.responseText}</span>`);
                                    },
                            });
                            }
                            else if(o.hasClass('cotation-sante')){
                                $.ajax({ type: "POST", url: "/ajax/cotation-gestion-sante.php", contentType: false, processData:false, data:f,
                                    success: function (r) {
                                        console.log(r);
                                        
                                        $('input[type=submit]').prop('disabled',false);
                                        try {
                                            const rJson=JSON.parse(r);
                                            if(rJson.hasOwnProperty('data')){
                                                window.location.href ='/demande-cotation-success';
                                            } 
                                            else{
                                                $('.error').html(rJson.msg?rJson.msg:_msg_error_inconnue);
                                                $('input[type=submit]+span').html(`<span class='error'>${rJson.msg?rJson.msg:_msg_error_inconnue}</span>`);
                                            } 
                                        }
                                        catch(e) {
                                        $('.error').html(e.responseText);
                                        $('input[type=submit]+span').html(`<span class='error'>${e.responseText}</span>`);
                                        }
                                    },
                                    error: function(e) {
                                            $('input[type=submit]').prop('disabled',false);
                                            $('.error').html(e.responseText);
                                            $('input[type=submit]+span').html(`<span class='error'>${e.responseText}</span>`);
                                    },
                            });
                            }
                            else if(o.hasClass('cotation-voyage')){
                                f.append('type',$(document).find('.cotation-form-container-sejour-destination .cotation-voyage-choix.active').text().trim());
                                f.append('duree',$(document).find('.cotation-form-container-sejour-duree .cotation-voyage-choix.active').text().trim());
                                $.ajax({ type: "POST", url: "/ajax/cotation-assurance-voyage.php", contentType: false, processData:false, data:f,
                                    success: function (r) {
                                        $('input[type=submit]').prop('disabled',false);
                                        try {
                                            const rJson=JSON.parse(r);
                                            if(rJson.hasOwnProperty('data')){
                                                window.location.href ='/demande-cotation-success';
                                            } 
                                            else{
                                                $('.error').html(rJson.msg?rJson.msg:_msg_error_inconnue);
                                                $('input[type=submit]+span').html(`<span class='error'>${rJson.msg?rJson.msg:_msg_error_inconnue}</span>`);
                                            } 
                                        }
                                        catch(e) {
                                        $('.error').html(e.responseText);
                                        $('input[type=submit]+span').html(`<span class='error'>${e.responseText}</span>`);
                                        }
                                    },
                                    error: function(e) {
                                            $('input[type=submit]').prop('disabled',false);
                                            $('.error').html(e.responseText);
                                            $('input[type=submit]+span').html(`<span class='error'>${e.responseText}</span>`);
                                    },
                            });
                            }
                            else if(o.hasClass('contact')){
                                    $.post('/ajax/mail.php',{form_mail:f.get('form_mail'), nom:f.get('nom'), email:f.get('email'),obj:f.get('obj'),tel:f.get('tel'),msg:f.get('msg')}, function (r) {
                                        $('input[type=submit]').prop('disabled',false);
                                        if(r.hasOwnProperty('data')) {
                                            window.location.href ='/contact-success';
                                        }
                                        else {
                                            $('.error').html(r.msg?r.msg:_msg_error_inconnue);
                                            $('input[type=submit]+span').html(`<span class='error'>${r.msg?r.msg:_msg_error_inconnue}</span>`);
                                        }
                                    },'json')
                                    .fail(function(e) {
                                            $('input[type=submit]').prop('disabled',false);
                                            $('.error').html(e.responseText);
                                            $('input[type=submit]+span').html(`<span class='error'>${e.responseText}</span>`);
                                    });
                            }
                 });
          }
    });
    const FormValidity=()=>{
            let _valid=true;
            $(document).find("form .form-error").removeClass('form-error');
            $(document).find("form [required]").each(function() {
                const o=$(this);
                if(!o.get(0).checkValidity()){
                     o.addClass('form-error');
                     if(o.parents('.file-container').length>0)
                        o.parents('.file-container').addClass('form-error');
                     _valid=false;
                }
            });
        return _valid;
    }
    $(document).on('keyup change','.form-error', function (e) {
          const o=$(this);
          if(o.get(0).checkValidity()){ 
            o.removeClass('form-error');
            if(o.parents('.file-container').length>0)
                o.parents('.file-container').removeClass('form-error');
        }
    });
    $('.section-faq-accordion-item h2').on('click',function() {
        $(this).toggleClass('active');
        const icon = $(this).find('i');
        icon.toggleClass('icon-chevron-down-circle-outline icon-chevron-up-circle-outline');
        $('.section-faq-accordion-content').not($(this).next()).slideUp();
        $(this).next().slideToggle();
    });
    // Small screen navigation
    $('.navbar-toggler').click(function() {
        $('.navbar-nav').slideToggle();
    });
});
