$(document).ready(function () {

    /* -------------------- pagination ajax nouvelle --------------------------*/
    $('body').on('click','.getresult_news',function(){
        var url=$(this).attr("paginate");
        getresult_news(url);
    });
    /* -------------------- pagination ajax repertoire membre --------------------------*/
    $('body').on('click','.getresult_list_membre',function(){
        var url=$(this).attr("paginate");
        getresult_list_membre(url);
    });
    /* -------------------- pagination ajax evenement --------------------------*/
    $('body').on('click','.go_to_page2',function(){
        var num_page=$(this).attr("paginate");
        go_to_page2(num_page);
    });
    $('body').on('click','.go_to_page2_prev',function(){
        previous2();
    });
    $('body').on('click','.go_to_page2_next',function(){
        next2();
    });
     // lien vers la carte du membre
    $('#lien_versCarte').on('click',function(){
        var width=(document.getElementById("lacarte"))?document.getElementById("lacarte").offsetWidth:0;
        var height=(document.getElementById("lacarte"))?document.getElementById("lacarte").offsetHeight:0;
        window.open(($('#lien_versCarte').attr('data-link'))+"width="+width+"&height="+height, '_blank');
    });
    // bouton retour history pour csp

    $('.RetourHistory').click(function() {
        history.back();
    });
    //afficher / caché un element par class ou par id
    $('.show_hide').click(function() {
        var elem=$(this).attr('show_hide_elem');
       	//$('#'+elem).toggle('fast');

        //fonctionnement avec les class bootstrap d-none / d-block
        var has_class=$('#'+elem).hasClass('d-none');
        if(has_class){
            $('#'+elem).removeClass('d-none');
            $('#'+elem).addClass('d-block');
        }else{
            $('#'+elem).addClass('d-none');
            $('#'+elem).removeClass('d-block');
        }

    });
    //affiche/cache un element par class
    $('.show_hide_by_class').click(function() {
        var elem=$(this).attr('show_hide_elem');
       	//$('.'+elem).toggle('fast');

        //fonctionnement avec les class bootstrap d-none / d-block
        var has_class=$('.'+elem).hasClass('d-none');
        if(has_class){
            $('.'+elem).removeClass('d-none');
            $('.'+elem).addClass('d-block');
        }else{
            $('.'+elem).addClass('d-none');
            $('.'+elem).removeClass('d-block');
        }
    });
    //cache un element
    $('.hide_by_class').click(function() {
        var elem=$(this).attr('show_hide_elem');

        var has_class=$('.'+elem).hasClass('d-none');
        if(!has_class){
            $('.'+elem).addClass('d-none');
            $('.'+elem).removeClass('d-block');
        }
    });

    $("#fast_login_form").submit(function (e) {
        if ($("#fast_login_ajax").val() == 0) {
            e.preventDefault(); // avoid to execute the actual submit of the form.
            var url = "/boutique/ajax_check_login.php"; // the script where you handle the form input.
            $.ajax({
                type: "POST",
                url: url,
                data: $("#fast_login_form").serialize(), // serializes the form's elements.
                success: function (data) {

                    if($.isNumeric(data))
                    {
                        if (data == 0)   //if(data.match(/1/g))
                        {
                            $("#fast_login_email_address").val("");
                            $("#fast_login_password").val("");
                            $("#msg_error_login").html("<br>Mot de passe ou identifiant invalide");
                        }
                        else if(data==3)
                        {
                            $("#code_email").val("");
                            $("#msg_error_login").html("<br>Le code entré est incorrect il vous reste 2 essaie avant d\'être bloqué");
                        }
                        else if(data==4)
                        {
                            $("#code_email").val("");
                            $("#msg_error_login").html("<br>Le code entré est incorrect il vous reste 1 essaie avant d\'être bloqué");
                        }
                        else if(data==5)
                        {
                            $("#code_email").val("");
                            $("#msg_error_login").html("<br>compte bloqué");
                        }
                        else
                        {
                            //2f
                            //affiche le champ reponse -> submit -> ajax -> en php check reponse -> log
                            $('.login-controls').hide();
                            $('#auth2F-wrapper').show();
                            $('#code_email').prop("disabled", false);
                        }

                    }
                    else
                    {
                        //on est loggé => redirect
                        //alert("[" + data + "]");
                       // if (data == "")

                        // voir VG-065880-0
                        var currentURL = window.location.href;

                        const urlParams = new URL(currentURL).searchParams;
                        const redirect = urlParams.get('redirect_secure_link');



                        if(redirect !='' && redirect!=null)
                        {

                            if (redirect.includes("offre-benevolat"))
                            {


                                var parts = redirect.split("?");
                                if (parts.length === 2)
                                {

                                    var prefix = parts[0];
                                    var queryString = parts[1];
                                    queryString = queryString.replace("id=", "");

                                    var modifiedUrl = prefix + "/postuler/" + queryString;


                                    data=modifiedUrl;
                                } else
                                {

                                }


                            }
                            else
                            {

                                 data=redirect;
                            }

                        }
                        else
                        {

                           data = "/boutique/account.php";

                        }
                       window.location.href = data;
                    }
                }
            });
        }
    });



    $("#echange_document_form").submit(function (e) {
        if ($("#fast_loginEchangeDoc_ajax").val() == 0) {
            e.preventDefault();
            var url = "/gi2-modules/custom/echange_document/ajax_check_login.php";
            $.ajax({
                type: "POST",
                url: url,
                data: $("#echange_document_form").serialize(),
                dataType: 'json',
                success: function (data) {
                    if (data.connexionOK == "0" || data.connexionOK == "-1") {
                        $("#echangeDocUser").val("");
                        $("#echangeDocPassword").val("");
                        if (data.connexionOK == "0") {
                            $("#msg_error_echangeDoc").html("<br>Mot de passe ou code d'utilisateur invalide");
                        } else {
                            $("#msg_error_echangeDoc").html("<br>Ce projet est inactif");
                        }
                    } else {
                        $("#fast_loginEchangeDoc_ajax").val("1");
                        $("#projetId").val(data.projetId);
                        $("#echange_document_form").submit();
                    }
                }
            });
        }
    });

    //sidebar account -----------------------------------------------------------------------------
    $('#sidebarCollapse').on('click', function () {
    	$('#sidebar').toggleClass('active');
        if ($("#sidebar").hasClass("active")) {
            //$('.container_content_all').removeClass('side_active');
            $('#master_all').removeClass('side_active');
        }else{
            //$('.container_content_all').addClass('side_active');
            $('#master_all').addClass('side_active');
        }
    });
    $("#sidebar_fixe").mCustomScrollbar({
    	theme: "minimal"
    });
    if ($(window).width() < 900) {
       $('#sidebar').addClass('active');
       //$('.container_content_all').removeClass('side_active');
       $('#master_all').removeClass('side_active');
    }else{
        //load
        /*if ($("#sidebar").hasClass("active")) {
            $('.container_content_all').removeClass('side_active');
        }else{
            $('.container_content_all').addClass('side_active2');
        }*/
    }


    // Formulaire de contact flottant
    $("#contactUs-tab").click(function () {
        $("#request-contactUs").toggleClass("visible");
    });

    $(".contactUs-close").click(function () {
        $("#request-contactUs").removeClass("visible");
    });

    //scrolling top
    $(window).scroll(function () {
        if ($(this).scrollTop() >= 150) {
            $('#return-to-top').fadeIn(200);
        } else {
            $('#return-to-top').fadeOut(200);
        }
    });
    $('#return-to-top').click(function () {
        $('body,html').animate({
            scrollTop: 0
        }, 500);
    });



    //---------------- menu sticky-----------------

    var body = document.body,
        html = document.documentElement;
    var total_height = Math.max(body.scrollHeight, body.offsetHeight,
        html.clientHeight, html.scrollHeight, html.offsetHeight);


    // Get the navbar
    var navbar = document.getElementById("menu_principal");
    var logo = document.getElementById("logo_sticky_nav");
    const logo2 = document.querySelector("#link_logo_nav");
    // var change_lang = document.getElementById("changeLang_sticky_nav");
    // Get the offset position of the navbar
    if (navbar)
    {
        //Sticky Nav
        // When the user scrolls the page, execute stickyNav
        window.onscroll = function ()
        {
            if(window.scrollY==0)
           {
                //user scrolled to the top of the page

                navbar.classList.remove("sticky");
                logo.classList.remove("sticky_nav_logo");
                if(logo2) {
                    //VG-066072-0
                    logo.classList.add("d-none");
                }
           }
           else
           {
               stickyNav(total_height);
               //VG-066072-0
               logo.classList.remove("d-none");
           }
        };
        var sticky = navbar.offsetTop;
    }


    // Add the sticky class to the navbar when you reach its scroll position.
    // Remove "sticky" when you leave the scroll position
    function stickyNav(total_height) {
        if (window.pageYOffset >= sticky && total_height > '1300') {
            navbar.classList.add("sticky");
            logo.classList.add("sticky_nav_logo");

            if (logo.style.display === "none") {
                logo.style.display = "table-cell";
            }

            /*if (change_lang.style.display === "none"){
                change_lang.style.display = "table-cell";
            } */
        } else {
            navbar.classList.remove("sticky");
            logo.classList.remove("sticky_nav_logo");

            if (logo.style.display === "table-cell") {
                logo.style.display = "none";
            }

            /* if (change_lang.style.display === "table-cell"){
                 change_lang.style.display = "none";
             } */
        }
    }

    $('.change_submit_url').change(function () {
        window.location = $(this).children('option:selected').val();
    });


    openAnchorAccordion();      //ouvrir un accordeon specific au load de la page  ex.: https://ville.lorraine.qc.ca/loisirs-et-culture/parcs-et-espaces-verts#collapse45  pour ouvrir l'accordeon #45

    $('[data-toggle="tooltip"]').tooltip({
            template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner large"></div></div>'
    });


    $(".modal_frame_btn").click(function () {
        //alert('test');
        var modal_target = $(this).attr("data-show-id");
        ;
        var src = $(this).attr("data-src");       //pour les images, ajouter 20px à la heuteur et largeur de l'image, pour éviter les scrollbar
        var width = $(this).attr("data-width");
        if (width == null) {
            width = '100%';
        }
        var height = $(this).attr("data-height");
        if (height == null) {
            height = '500';
        }                  // alert(src);
        var dataFrame = {
            'src': src,
            'height': height,
            'width': width
        };
        $('.' + modal_target).find(".iframe_modal").attr(dataFrame);
    });


    //duplicate admin /admin/jquerycode.js.php
    $("#ajouter_image_crop").click(function(){
        if(!$.trim($(this).attr("stringfieldvide"))){
            let numero=parseInt($(this).val());
            let maxLimit;
            if ($(this).attr('maxLimit')) {
                maxLimit=$(this).attr('maxLimit');
            }
            else{
                maxLimit=10;
            }
            if(!$("#image_crop"+numero).length && numero<maxLimit+1){
                $(this).val(numero+1);
                let txtAreaName;
                if($(this).attr("txtAreaName").includes("numberToChange")){
                    txtAreaName=$(this).attr("txtAreaName").replace("numberToChange", numero);

                }
                /*else{
                    txtAreaName="numberToChange", numero
                }*/

                $.ajax({
                    type: 'POST',
                    url: '/boutique/ajax/ajax_image_crop.php',
                    data: {'data_target': 'resize_custom_db_photo'+numero, 'imageId':$(this).attr("imageId"), 'field_id_img':$(this).attr("field_id_img"), 'field_img':$(this).attr("field_img")+numero, 'table_img':$(this).attr("table_img"), 'inputImgName':'image_crop'+numero, 'path':$(this).attr("path"), 'imgResizeThumb':'img_resize_image_crop'+numero, 'height':$(this).attr("height"), 'width':$(this).attr("width"), 'adminBack':$(this).attr("adminBack"), 'txtAreaName':txtAreaName, 'txtAreaContent':$(this).attr("txtAreaContent"), 'field_additional_text':$(this).attr("field_additional_text")+numero, name_additional_text:$(this).attr("name_additional_text")},
                    dataFilter: function(data,type) {
                        return data || "{}"
                    },
                    success: function (response) {
                        //$( "#result_photos" ).html( response );
                        //console.log("requete");
                    }
                }).done(function (data){$("#result_image_crop").html(data)});
            }
        }
        else{
            let options=$(this).attr("stringFieldVide").split(",");
            let numero=options[0].replace("photo", '');

            let txtAreaName;
            if($(this).attr("txtAreaName").includes("numberToChange")){
                txtAreaName=$(this).attr("txtAreaName").replace("numberToChange", numero);
                //console.log(txtAreaName);
            }
            /*else{
                txtAreaName="numberToChange", numero
            } */

            let stringRestantFieldVide='';
            let premier=0;
            for(let i=1;i<options.length; i++){
                if(premier==0){
                    stringRestantFieldVide+=options[i];
                    premier=1;
                }
                else{
                    stringRestantFieldVide+=','+options[i];
                }
            }

            $(this).attr("stringFieldVide", stringRestantFieldVide);

            $.ajax({
                type: 'POST',
                url: '/boutique/ajax/ajax_image_crop.php',
                data: {'data_target': 'resize_custom_db_photo'+numero, 'imageId':$(this).attr("imageId"), 'field_id_img':$(this).attr("field_id_img"), 'field_img':$(this).attr("field_img")+numero, 'table_img':$(this).attr("table_img"), 'inputImgName':'image_crop'+numero, 'path':$(this).attr("path"), 'imgResizeThumb':'img_resize_image_crop'+numero, 'height':$(this).attr("height"), 'width':$(this).attr("width"), 'adminBack':$(this).attr("adminBack"), 'txtAreaName':txtAreaName, 'txtAreaContent':$(this).attr("txtAreaContent"), 'field_additional_text':$(this).attr("field_additional_text")+numero, name_additional_text:$(this).attr("name_additional_text")},
                dataFilter: function(data,type) {
                    return data || "{}"
                },
                success: function (response) {
                    //$( "#result_photos" ).html( response );
                    //console.log("requete");
                }
            }).done(function (data){$("#result_image_crop").html(data)});
        }
    });


    //auto open accordeon si l'ancre est active
    if (window.location.hash) {
        var jQuerytarget = jQuery('body').find(window.location.hash);

        if (jQuerytarget.hasClass('collapse')) {
            var jQuerytargetAccordion = jQuerytarget.find('.collapse');
            jQuerytarget.collapse('show');
        }
    }

    $('.datepicker').datepicker({dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, yearRange: '-100:+10'});



    /*-----------------------PAGINATION - docready--------------------*/
    var show_per_page = 10;
    var number_of_items = $('#wrapper_list_paginate').children('.list_paginate').length;
    var number_of_pages = Math.ceil(number_of_items / show_per_page);

    $( "#nav_prev" ).click(function() {
        previous();
    });
    $( "#nav_next" ).click(function() {
        next();
    });

    if (number_of_pages > 1) {
        $('#current_page').val(0);
        $('#show_per_page').val(show_per_page);

        var navigation_html = '<a class="prev" id="nav_prev" ooonclick="previous()">Précedent</a>';
        var current_link = 0;
        while (number_of_pages > current_link) {
            navigation_html += '<a class="page" onclick="go_to_page(' + current_link + ')" longdesc="' + current_link + '">' + (current_link + 1) + '</a>';
            current_link++;
        }
        navigation_html += '<a class="next" id="nav_next" ooonclick="next()">Suivant</a>';

        $('.controls_pagination').html(navigation_html);
        $('.controls_pagination .page:first').addClass('active');

        //$('#wrapper_list_paginate').children().css('display', 'none');
        $('#wrapper_list_paginate').children().removeClass('d-block');   // d-flex
        $('#wrapper_list_paginate').children().addClass('d-none');
        //$('#wrapper_list_paginate').children().slice(0, show_per_page).css('display', 'flex');
        $('#wrapper_list_paginate').children().slice(0, show_per_page).removeClass('d-none');
        $('#wrapper_list_paginate').children().slice(0, show_per_page).addClass('d-block');   // d-flex
    }

    var mode = '';
    if (document.getElementById('spc_mod') != null) {
        mode = document.getElementById('spc_mod').value;
    }

    if (mode == 'table') {
        var number_of_items = $("#list_item").children('tbody').children(".oneItem_wrapper").length;
        var show_per_page = 10;
        if (document.getElementById('show_per_page_table') != null) {
            var show_per_page = document.getElementById('show_per_page_table').value;
        }
    } else {
        //alert(document.getElementById('default_show_per_page').value);
        var number_of_items = $('#list_item').children('.oneItem_wrapper').length;
             // alert(number_of_items);
        if (document.getElementById('default_show_per_page') != null) {
            var show_per_page = document.getElementById('default_show_per_page').value;
        } else {
            var show_per_page = 6;
        }
    }

    var number_of_pages = Math.ceil(number_of_items / show_per_page);
    if (number_of_pages > 1) {
        $('#current_page').val(0);
        $('#show_per_page').val(show_per_page);

        var navigation_html = '<a class="prev go_to_page2_prev" id="precedent_pagination_event" >Précédent</a>';
        var current_link = 0;
        while (number_of_pages > current_link) {
            navigation_html += '<a class="page go_to_page2" paginate="' + current_link + '"  longdesc="' + current_link + '">' + (current_link + 1) + '</a>';
            current_link++;
        }

        navigation_html += '<a class="next go_to_page2_next" id="suivant_pagination_event">Suivant</a>';

        $('.controls_pagination').html(navigation_html);
        //trigger_suivant();
        $('.controls_pagination .page:first').addClass('active');

        if (mode == 'table') {
            //removeClass
            $('#list_item').children('tbody').children(".oneItem_wrapper").removeClass('d-block');  // d-flex
            $('#list_item').children('tbody').children(".oneItem_wrapper").addClass('d-none');
            //$('#list_item').children('tbody').children(".oneItem_wrapper").slice(0, show_per_page).css('display', 'table-row');
            $('#list_item').children('tbody').children(".oneItem_wrapper").slice(0, show_per_page).removeClass('d-none');
            $('#list_item').children('tbody').children(".oneItem_wrapper").slice(0, show_per_page).addClass('d-block');  // d-flex
        } else {
            //$('#list_item').children().css('display', 'none');

            $('#list_item').children().removeClass('d-block'); // d-flex
            $('#list_item').children().addClass('d-none');
            //$('#list_item').children().slice(0, show_per_page).css('display', 'flex');
            $('#list_item').children().slice(0, show_per_page).removeClass('d-none');
            $('#list_item').children('.oneItem_wrapper').slice(0, show_per_page).addClass('d-block');   // d-flex



        }

        $("a.next").prev().css("display", "inline-block");
        $("a.next").prev().prev().css("display", "inline-block");
    }



   $(".interuupteur_toggle").click(function(e){

                switch_interrupteur($(e.target).next('input').val())
   });



});     //------------------------------- FIN   $(document).ready(function () ----------------------------------




function go_to_page2(page_num) {

    var mode = '';
    if (document.getElementById('spc_mod') != null) {
        mode = document.getElementById('spc_mod').value;
    }
    var show_per_page = parseInt($('#show_per_page').val(), 0);
    start_from = page_num * show_per_page;
    end_on = start_from + show_per_page;
    if (mode == 'table') {
        //  VG-066035-0
        $('#list_item').children('tbody').children(".oneItem_wrapper").removeClass('d-block');
        $('#list_item').children('tbody').children(".oneItem_wrapper").removeClass('d-none');
        $('#list_item').children('tbody').children(".oneItem_wrapper").css('display', 'none').slice(start_from, end_on).css('display', 'table-row');
    } else {
        //$('#list_item').children().css('display', 'none').slice(start_from, end_on).css('display', 'flex');
        $('#list_item').children().addClass('d-none').slice(start_from, end_on).addClass('d-block');     // d-flex
        $('#list_item').children(".oneItem_wrapper").removeClass('d-block').slice(start_from, end_on).removeClass('d-none');   //d-flex
    }

    $('.page[longdesc=' + page_num + ']').addClass('active').siblings('.active').removeClass('active');
    $('#current_page').val(page_num);

    $("a.page").css("display", "none");
    $("a.page").removeClass("prev_nav");
    $("a.active").css("display", "inline-block");

    $("a.active").prev().css("display", "inline-block");
    $("a.active").prev().prev().css("display", "inline-block");

    $("a.active").next().css("display", "inline-block");
    $("a.active").next().next().css("display", "inline-block");

    $("a.prev").next().css("display", "inline-block");
    $("a.prev").next().next().css("display", "inline-block");

    $("a.next").prev().css("display", "inline-block");
    $("a.next").prev().prev().css("display", "inline-block");

    if (page_num >= 5) {
        $("a.active").prev().prev().addClass('prev_nav');
    }
    $('html,body').animate({
            scrollTop: $("#main_wrapper_interne").offset().top
        },
        'fast');
}

function previous2() {
    new_page = parseInt($('#current_page').val(), 0) - 1;
    //if there is an item before the current active link run the function
    if ($('.active').prev('.page').length == true) {
        go_to_page2(new_page);
    }
}


function next2() {

    new_page = parseInt($('#current_page').val(), 0) + 1;
    //if there is an item after the current active link run the function
    if ($('.active').next('.page').length == true) {
        go_to_page2(new_page);
    }
}

/* ------ pagination module nouvelle ----------*/

function getresult_news(url) {
    $.ajax({
        url: url,
        type: "GET",
        data:  {rowcount:$("#rowcount").val(),"pagination_setting":$("#pagination-setting").val()},
        //beforeSend: function(){$("#overlay").show();},
        success: function(data){
            $("#pagination-result").html(data);
            //setInterval(function() {$("#overlay").hide(); },500);
        },
        error: function()
        {}
    });
}
function changePagination(option) {
    if(option!= "") {
        getresult_news("/gi2-modules/standard/news/client/fe_list_news.php");
    }
}

//---------------------------------------------------------------------------------------------------------------------------
//-------------- probleme quand le menu sticky embarque par dessus un input required ----------------------------------------
//Offset should be the height of your header and delay is how long you want it to take to scroll to the element.
var delay = 0;
var offset = 150;

document.addEventListener('invalid', function(e){
    $(e.target).addClass("invalid");
    $('html, body').animate({scrollTop: $($(".invalid")[0]).offset().top - offset }, delay);
}, true);
document.addEventListener('change', function(e){
    $(e.target).removeClass("invalid")
}, true);


$(document).on( 'click', '.trigger_tuile', function(){
    var tuile_id=$(this).attr("tuile_id");
    toggle_tuile(tuile_id);
    $(this).addClass('tuile_active');
} );

function toggle_tuile(tuile_id) {
    $('.fix_tuile_height').removeClass('tuile_active');

    $('.tuile_detail.d-block').toggleClass('d-block d-none');
    $('#tuile_detail_' + tuile_id).toggleClass('d-none d-block');
}

function openAnchorAccordion() {
    if (window.location.hash) {
        var $target = $('body').find(window.location.hash);
        if ($target.hasClass('collapse')) {
            //console.log('hasClass collapse');
            $('.in').removeClass('in');
            $target.removeClass('collapse');
            //$('a[href*="' + window.location.hash + '"]').click();
        }
    }
}

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}


//----------------------- event - nav by cat ---------------
/*event cat*/
function changeSrcImage(image, id) {
    var element = document.getElementById(id);
    element.src = "/client_file/themes/default/interface/st_lin/" + image + "";
}

/*event cat*/
function changeBg(color, id) {
    var element = document.getElementById(id);
    element.style.background = "#" + color + "";
}

/*event cat*/
function detail_cat(cat_id, link_id, aa = '', mm = '', jj = '') {

    $('.secondary_cat_wrapper').empty();
    var data_cat = {"cat_id": cat_id, "aa": aa, "mm": mm, "jj": jj}
    var url = "/gi2-modules/custom/cust_fiq_evenement/ajax_cat.php";
    $.ajax({
        type: "POST",
        url: url,
        data: data_cat,
        success: function (result) {
            jQuery("#detail_cat_" + cat_id).html(result); // result is the HTML text
            jQuery("#detail_cat_" + cat_id).show("slow");
            //jQuery("#detail_cat").show("slow");
        },
    });
    $('.event_primary_cat').removeClass('picto_cat_active');
    if(link_id){
        $('#' + link_id).toggleClass('picto_cat_active');
    }
}

/*maj list event*/
function maj_event(cat_id, aa, mm, jj,typeC='') {
    // typec VG-067212-0
    var data_cat = {"cat_id": cat_id, "aa": aa, "mm": mm, "jj": jj,type:typeC}
    var url = "/gi2-modules/custom/cust_fiq_evenement/ajax_cal.php";
    $.ajax({
        type: "POST",
        url: url,
        data: data_cat,
        success: function (result) {
            jQuery("#wrapper_calendar").html(result); // result is the HTML text
            //jQuery("#wrapper_calendar").show("slow");
        },
    });

    var url = "/gi2-modules/custom/cust_fiq_evenement/ajax_event.php";
    $.ajax({
        type: "POST",
        url: url,
        data: data_cat,
        success: function (result) {
            jQuery("#wrapper_list_event").html(result); // result is the HTML text
            listevent();



        },
    });
    if(typeC=='region'){

          jQuery('.row_region_event').removeClass('active');
          jQuery('#region_evnt'+cat_id).addClass('active')
    }
    jQuery(".controls_pagination").html('');
    if(typeC!='region'){  // typec VG-067212-0
        //texte de la catégorie
        data_cat = {"cat_id": cat_id, "mod": "cat_desc"}
        $.ajax({
            type: "POST",
            url: url,
            data: data_cat,
            success: function (result) {
                jQuery("#cat_desc").html(result); // result is the HTML text
            },
        });
    }

}

//----------------------------- news - nav by cat ---------------------
/*news cat*/
function detail_cat_news(cat_id, link_id) {
    //$('.secondary_cat_wrapper').empty();
    var data_cat = {"cat_id": cat_id}
    var url = "/gi2-modules/standard/news/ajax_cat.php";
    $.ajax({
        type: "POST",
        url: url,
        data: data_cat,
        success: function (result) {
            jQuery("#detail_cat_" + cat_id).html(result); // result is the HTML text
            jQuery("#detail_cat_" + cat_id).show("slow");
            //jQuery("#detail_cat").show("slow");
        },
    });
    //$('.event_primary_cat').removeClass('picto_cat_active');
    //$('#'+link_id).toggleClass('picto_cat_active');
}

/*maj list news*/
function maj_news(cat_id) {
    var data_cat = {"cat_id": cat_id}
    var url = "/gi2-modules/standard/news/ajax_news.php";   //rebuild $_SESSION['news_query']
    $.ajax({
        type: "POST",
        url: url,
        data: data_cat,
        success: function (result) {
            //jQuery("#wrapper_calendar").show("slow");
            getresult_news("/gi2-modules/standard/news/client/fe_list_news.php");   //reload les news avec la nouvelle query $_SESSION['news_query']
        },
    });
    jQuery(".controls_pagination").html('');

    //texte de la catégorie
    data_cat = {"cat_id": cat_id, "mod": "cat_desc"}
    $.ajax({
        type: "POST",
        url: url,
        data: data_cat,
        success: function (result) {
            jQuery("#cat_desc").html(result); // result is the HTML text
        },
    });
}



function option_conditionelle(traitement, bloc, titre, opt_id, origin_radio_value=0) {
    if(traitement == 'block')
    {
        var list_option = document.getElementsByName(bloc);
        list_option.forEach(element => {
            if(element.checked)
            {
                element.checked = false;
            }
            element.disabled = true;
        });
        //if($('#msg_alert_opt_'+opt_id).length==0){
            $('#alert_opt_'+opt_id).html('<br><span id="msg_alert_opt_'+opt_id+'"><small>(Aucune sélection à faire pour ce bloc, vous êtes inscrit(e) à : '+titre+') <a href="javascript:void(0)" onclick="option_conditionelle(\'unblock\',\''+ bloc +'\',\''+ titre +'\',\''+ opt_id +'\',\''+ origin_radio_value +'\');">(annuler)</a></span></small>');       //"annuler" remet les checkbox à 0
        //}
    }
    else if(traitement == 'unblock')
    {
        var list_option = document.getElementsByName(bloc);
        list_option.forEach(element => {
            element.disabled = false;
            element.checked = false;
        });
        $('#msg_alert_opt_'+opt_id).remove();
        if(origin_radio_value>0){
            $("input[type=radio][value=" + origin_radio_value + "]").prop('checked', false);
        }

    }
}

function input_numeric_only(evt, allow_negatif) {
    var theEvent = evt || window.event;

    // Handle paste
    if (theEvent.type === 'paste') {
        key = event.clipboardData.getData('text/plain');
    } else {
        // Handle key press
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode(key);
    }
    if (allow_negatif == '1') {
        var regex = /[0-9]|\.|\-/;
    } else {
        var regex = /[0-9]|\./;
    }
    if (!regex.test(key)) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) theEvent.preventDefault();
    }
}

function changeBgNews(color, id) {
    var element = document.getElementById(id);
    element.style.background = "" + color + "";
}



//modal img
$(function () {
    $('.image_fullsize').on('click', function () {
        if($(this).attr('src')){
            var src=$(this).attr('src');
        }else{
            var src=$(this).find('img').attr('src')
        }

        $('#text_img_fullsize').html(''); 
        $('.imagepreview').attr('src', src);
        var desc = $(this).attr('alt');
        if (!desc) {
            desc = $(this).attr('title');
        }
        $('#text_img_fullsize').html(desc);
        $('#imagemodal').modal('show');
    });
});

function isValidDate(dateString) {
    var regEx = /^\d{4}-\d{2}-\d{2}$/;
    if (!dateString.match(regEx)) return false;  // Invalid format
    var d = new Date(dateString);
    var dNum = d.getTime();
    if (!dNum && dNum !== 0) return false; // NaN value, Invalid date
    return d.toISOString().slice(0, 10) === dateString;
}

function check_double_submit(id, form, txt) {
    btn_sbm = document.getElementById(id);
    btn_sbm.disabled = true;
    btn_sbm.value = txt;
    // btn_sbm.style.display ='none';
    return true;

}

function home_event_tab(evt, tabName) {
    var i, tabcontent, tablinks;

    // Get all elements with class="tabcontent" and hide them
    tabcontent = document.getElementsByClassName("home_event_tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    // Get all elements with class="tablinks" and remove the class "active"
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    // Show the current tab, and add an "active" class to the button that opened the tab
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";
}

function cart_login()
{
       $('.login-box').slideToggle();
       $('html, body').animate({ scrollTop: 0 }, 'slow');
}


function show_password(id_input_pass) {
    var x = document.getElementById(id_input_pass);
    if (x.type === "password") {
        x.type = "text";
    } else {
        x.type = "password";
    }
}

/* 68619 */
 jQuery(function ($) {
   $(".mask_phone_full").inputmask("(999) 999-9999 #9999");
   $(".mask_phone").inputmask("(999) 999-9999");
   $(".mask_postcode").inputmask("a9a 9a9");

 });

function trigger_album(id,idparent){

    if(eval('jb_'+id)!== undefined){
        width=1300
        if(eval(idparent)!== undefined){
            width=eval(idparent).offsetWidth
        }
    eval('jb_'+id).setGallerySize(width-30,700)
    }

}


/**** interrugpteur ***/
function   switch_interrupteur(id){
                             choix1=document.getElementById('choix1_interrupteur_'+id).value;
                             choix2=document.getElementById('choix2_interrupteur_'+id).value;
                             choix1_label=document.getElementById('label1_interrupteur_'+id).value;
                             choix2_label=document.getElementById('label2_interrupteur_'+id).value;
                             interrupt=document.getElementById('interrupteur_value_'+id).value;
                             if(interrupt==choix2){
                                document.getElementById('interrupteur_value_'+id).value=choix1;
                                document.getElementById('label_interrupteur_'+id).innerHTML=choix1_label;
                                document.getElementById('field_'+id).value=choix1;
                             }else{
                               document.getElementById('interrupteur_value_'+id).value=choix2;
                               document.getElementById('label_interrupteur_'+id).innerHTML=choix2_label;
                               document.getElementById('field_'+id).value=choix2;
                             }

}

/*********** statistique ************/
/*$(document).ready(function () {

if($('#counter_section')){
    observer = new MutationObserver(function(mutationsList, observer){

                                                document.querySelector("#pourc_"+mutationsList[0].target.getAttribute("cat-id")).setAttribute("stroke-dasharray", mutationsList[0].target.innerHTML+", 100");
    });
var div_top = $('#counter_section').offset().top;

    $(window).scroll(function(){
        if(($(window).scrollTop() + $(window).height()) > div_top){
            $('.counter').each(function() {
                var this_wind = $(this),
                    countTo = this_wind.attr('data-count');
                $({ countNum: this_wind.text()}).animate({
                        countNum: countTo
                },
                {
                    duration: 3000,
                    easing:'swing',
                    step: function() {
                        this_wind.text(Math.floor(this.countNum));
                    },
                    complete: function() {
                        this_wind.text(this.countNum);
                        //alert('finished');
                    }
                });
            });
        }
    });

}

}) */


