$.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
    prevText: '<Préc', prevStatus: 'Voir le mois précédent',
    nextText: 'Suiv>', nextStatus: 'Voir le mois suivant',
    currentText: 'Courant', currentStatus: 'Voir le mois courant',
    monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    'Jul','Aoû','Sep','Oct','Nov','Déc'],
    monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 0,
    initStatus: 'Choisir la date', isRTL: false};
$('.datepicker').datepicker({dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, yearRange: '-100:+10'});

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

function toggle_tuile(tuile_id) {
    $('.fix_tuile_height').removeClass('tuile_active');
    $('#tuile_' + tuile_id).addClass('tuile_active');

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

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

/*------------debut input masks---------------------*/
//VG-068725
$(".mask_phone").inputmask({"mask": "999 999-9999 ext: 9999"});
$(".mask_email").inputmask("email");

$( ".numeric_only" ).on( "keyup", function() {
    this.value = this.value.replace(/[^0-9\.]/g,'');
} );

$( ".alpha_only" ).on( "keyup", function() {
    this.value = this.value.replace(/[^a-z\. ^A-Z\.]/g,'');
} );

/*------------fin input masks---------------------*/

$(document).ready(function () {

    table = $('.basic_datatable').DataTable({
        columnDefs: [{targets: 0,
    	  width: "140px"
        },],
        'searching': false,
    	"aaSorting": [],	/*aucun tri par default à l'initialisation du tableau*/
        aLengthMenu: [
            [20, 50, 100, -1],
            [20, 50, 100, "Tous"]
        ]
    });

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


    /*-----------------------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-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-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 {
        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" >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" >Suivant</a>';

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

        if (mode == 'table') {
            //removeClass
            $('#list_item').children('tbody').children(".oneItem_wrapper").removeClass('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-flex');
        } else {
            //$('#list_item').children().css('display', 'none');
            $('#list_item').children().removeClass('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().slice(0, show_per_page).addClass('d-flex');
        }

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

    //cache un element
    $('.hide_by_class').click(function() {
        var elem=$(this).attr('hide_elem');

        var has_class=$('.'+elem).hasClass('d-none');
        //if(!has_class){
            $('.'+elem).removeClass('d-none');  //pas de d-none en double
            $('.'+elem).addClass('d-none');
            $('.'+elem).removeClass('d-block');
        //}
    });
    //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');
        }
    });


        //iframe dynamique dans une modal
    $('body').on('click','.modal_frame_btn',function(){ //  $('body').on('click' VS $('.modal_frame_btn').click => https://stackoverflow.com/questions/30560954/
    //$('.modal_frame_btn').click(function() {
        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='1200';}
        var height = $(this).attr("data-height");
        if(height == null){height='700';}
        var dataFrame = {
            'src': src,
            'height':height,
            'width':width
        };

        $('#'+modal_target).find(".iframe_modal").attr(dataFrame);
        $('#'+modal_target).modal('show');
    });


});     //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') {
        $('#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-flex');
        $('#list_item').children().removeClass('d-flex').slice(start_from, end_on).removeClass('d-none');
    }

    $('.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");
    }
}
/*----------------------- event - nav by cat ----------------------*/

/*event cat*/      /*--------------- OBSOLETTE  ?? ---------------*/
/*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) {   /*------- à voir si on conserve se system (csp) --------*/
    //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) {
    var data_cat = {"cat_id": cat_id, "aa": aa, "mm": mm, "jj": jj}
    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();             
        },
    });
    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
        },
    });
}

/*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
        },
    });
    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
        },
    });
}

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

/* ---------------------- <select> passe la valeur dans l'url on change ---------------------- */
$(".change_submit_url").on('change', function(){
    window.location = $(this).children('option:selected').val();
});
$(".change_submit_url_confirm").on('change', function(){
    if (confirm('Veuillez confirmez') == true) {window.location = $(this).children('option:selected').val(); }
});

/* -------------------- display modal bootstrap --------------------------*/
/*$('body').on('click','.show_modal_bs',function(){
    var num_page=$(this).attr("paginate");
    go_to_page2(num_page);
});*/

$(".interuupteur_toggle").click(function(e){
    switch_interrupteur($(e.target).next('input').val())
});
/**** 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;

    }
}

/**** interrupteur simple ***/
$(".toogle_switch_radio").click(function(e){
    var id_input = $(this).attr("id_input");
    if(this.checked) {
        $('#'+id_input).val('1').trigger('change');

    } else {
        $('#'+id_input).val('0').trigger('change');
    }
});
/**** interrupteur nouveau ***/
$(".toogle_switch_interrupteur").click(function(e){
    var id_input = $(this).attr("id_input");
    $('#'+id_input).trigger('change');
});
/*-------------------------------- CSP onclick confirm --------------------------------*/
$('.confirm').on('click', function () {
    var msg=$(this).attr("data_confirm");
    return confirm(msg);
});


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



function markRequired() {
    var control = $(this).children(".form-control");
    var label = $(this).children("label");
    if (control.attr("required") == "required") {
        label.addClass("required");
    }
}

function countCharacters() {
    var attr_max = $(this).attr('maxlength');
    if (typeof attr_max !== 'undefined' && attr_max !== false) {
    var max = $(this).attr("maxlength");
    }

    var attr_val = $(this).attr('value');
    if ((typeof attr_val !== 'undefined' && attr_val !== false) || $(this).is("textarea") ) {
        var length = $(this).val().length;
    }else{var length = 0;}

    var counter = max - length;
    var helper = $(this).prev(".input-counter");
    // Switch to the singular if there's exactly 1 character remaining
    var char_num=max-counter;
    if (counter !== 1) {
        helper.text(char_num + " / " + max);
    } else {
        helper.text(char_num + " / " + max);
    }
    // Make it red if there are 0 characters remaining
    if (counter === 0) {
        helper.removeClass("text-muted");
        helper.addClass("text-danger");
    } else {
        helper.removeClass("text-danger");
        helper.addClass("text-muted");
    }
}

$(document).ready(function () {
    $(".form-group").each(markRequired);
    $(".form-control").each(countCharacters);
    $(".form-control").keyup(countCharacters);
});