function googleTranslateElementInit() {
    new google.translate.TranslateElement({
        pageLanguage: 'fr',
        includedLanguages: 'en,fr,es,de',
        layout: google.translate.TranslateElement.InlineLayout.SIMPLE
    }, 'google_translate_element');
}
function buttonUp(){
    var valux = $('.header-search input[type=text]').val();
    valux = $.trim(valux).length;
    if(valux !== 0){
        $('.header-search .loupe').css('z-index','999');
        $(".click-form-search").css("z-index","-100");
    } else{
        $('.header-search input[type=text]').val('');
        $('.header-search .loupe').css('z-index','-999');
        $(".click-form-search").css("z-index","100");
        //$(".header-top .formulaire-recherche").css("z-index","-999");
    }
}


/***** Réglage des hauteurs égales et dynamiques pour plusieurs blocs *****/

function equalizeHeights(selector) {
    var heights = new Array();

    // Loop to get all element heights
    $(selector).each(function() {

        // Need to let sizes be whatever they want so no overflow on resize
        $(this).css('min-height', '0');
        $(this).css('max-height', 'none');
        $(this).css('height', 'auto');

        // Then add size (no units) to array
        heights.push($(this).height());
    });

    // Find max height of all elements
    var max = Math.max.apply( Math, heights );

    // Set all heights to max height
    $(selector).each(function() {
        $(this).css('height', max + 'px');
    });
}

var swapElements = function(siblings, subjectIndex, objectIndex) {
    // Get subject jQuery
    var subject = $(siblings.get(subjectIndex));
    // Get object element
    var object = siblings.get(objectIndex);
    // Insert subject after object
    subject.insertAfter(object);
}
var swapElementsRWD = function() {
    var afterAdded = false;
    if (window.matchMedia("(min-width: 1201px)").matches && afterAdded == false ) {
        swapElements($('.services-container .item-service'), 0, 3);
        afterAdded = true;
    }
    if (window.matchMedia("(min-width: 992px)").matches && afterAdded == false) {
        swapElements($('.services-container .item-service'), 0, 3);
        afterAdded = true;

    }
    if (window.matchMedia("(min-width: 651px)").matches && afterAdded == false) {
        swapElements($('.services-container .item-service'), 0, 2);
        afterAdded = true;

    }
    if (window.matchMedia("(min-width: 481px)").matches && afterAdded == false) {
        swapElements($('.services-container .item-service'), 0, 1);
        afterAdded = true;
    }
    if (window.matchMedia("(max-width: 480px)").matches && afterAdded == false) {
        swapElements($('.services-container .item-service'), 0, 0);
        afterAdded = true;
    }
}

$(document).ready(function() {
    //Bloc acces
    $('.access a').click(function() {
        $('.access').removeClass('active');
        $(this).parent('.access').addClass('active');
    });

    //Bloc focus
    if($("#bloc-agenda-2").length){
        $("#bloc-agenda-2").css("opacity",'1');
    }
    if($("#bloc-focus").length){
        $("#bloc-agenda-2").addClass("with_focus");
    }

    //pretty photo
    if($("a[data-rel^='prettyPhoto']").length){
        $("a[data-rel^='prettyPhoto']").prettyPhoto({
            facebookLikeButton: false,
            tweetButton : false,
            default_width: 560,
            default_height: 315,
            allow_resize: true
        });
    }
    //Activation du menu niveau1 courant
 /*   $("header .navbar-default .navbar-left > li >a").each(function(){
        var pgurl = location.pathname.split("/")[1];
        var href = $(this).attr('href').split("/")[0];
        if(href === pgurl){
            $(this).parent("li").addClass("current-menu");
        }
    });*/

    swapElementsRWD();
    /****langue****/
    $(".langue>a").click(function() {
        $(".translate").toggleClass("show-translate");
        return true;
    });

    /****search****/


    var submitIcon = $('#search-menu');
    var submitInput = $('.header-search .loupe');
    var searchBox = $('.search');
    var isOpen = false;
    $(document).click(function(event) {
        if (event.target.id != '#search-menu' && $(event.target).parents('.search').length == 0) {
            searchBox.removeClass('search-open');
            isOpen = false;
            $('.header-search input[type=text]').val('');
            $('.header-search .loupe').css('z-index','-999');
            $(".click-form-search").css("z-index","100");
        }
        if (event.target.id != '#google_translate_element' && $(event.target).parents('.langue a').length == 0) {
            $('.langue a').removeClass("show-lang");
            //$("#google_translate_element").hide("slide",{ direction: "right" }, 250);
        }
    });
    $(document).keyup(function(){
        if(isOpen == true){
            submitInput.val('');
            //$(".header-top .formulaire-recherche").css("z-index","100");
        }
    });

    submitIcon.mouseup(function(){
        return false;
    });

    searchBox.mouseup(function(){
        return false;
    });

    submitIcon.click(function(){
        if(isOpen == false){
            searchBox.addClass('search-open');
            $('#SearchText').focus();
            isOpen = true;
            $('.langue a').removeClass("show-lang");
            //$("#google_translate_element").hide("slide",{ direction: "right" }, 250);
        } else {
            searchBox.removeClass('search-open');
            isOpen = false;
        }
    });

    /////////////

    $(".profil-menu").on('click focus', function(e) {
        if ( !$(this).data('fired') ) {
            var $this_menu = $(this).parent().find('.sub-menu-profil');
            $(".sub-menu-profil").not($this_menu).slideUp();
            $(this).toggleClass("profil-menu-open");
            // here is what I want to do
            $this_menu.slideToggle();
            e.preventDefault();

        }

        $(this).data('fired', true);

        setTimeout(function(self) {
            $(self).data('fired', false);
        }, 200, this);
        e.preventDefault();
    });

    //
    var mySwiper = new Swiper('.swiper-container', {
        scrollbar: '.swiper-scrollbar',
        scrollbarHide: false,
        scrollbarDraggable: true,
        slidesPerView: 'auto',
        centeredSlides: false,
        grabCursor: true
    });

    $(".swiper-container .swiper-slide a").bind("click", function() {
        window.location.href=$(this).attr('href');
    });

    //$(".nicescroll").niceScroll({autohidemode: false,railpadding:{top:0,right:0,left:0,bottom:0}, cursorwidth:11, background:'#69B8BE', cursorcolor:"#FFF", cursorborderradius: "5px", cursorborder: 'none'});
    $('.message-error ul li').each(function(){
        $(this).find('a').click(function(){
            $('html, body').animate({
                scrollTop: $( $.attr(this, 'href') ).offset().top
            }, 500);
            return false;
        });
    });

    var mainVideoHeight=$(".main-video .img-wrap a img").height();
    $("#bloc-medias .photos ul > li").css("height",(mainVideoHeight/2)-5);
    $("#bloc-medias.bloc-media-style2 .publications").css("height",mainVideoHeight);
    /**** toggle bloc commission *****/
    $(".conseil-level").not( ".active" ).find(".toggle-content").hide();

    $(".conseil-level h3 .toggle-arrow").on('click focus', function(e) {
        if ( !$(this).data('fired') ) {
            $(this).closest(".conseil-level").find(".toggle-content").slideToggle( "slow" ).siblings(".toggle-content:visible").slideUp("slow");
            $(this).closest(".conseil-level").toggleClass( "active" );
            e.preventDefault();
        }

        $(this).data('fired', true);

        setTimeout(function(self) {
            $(self).data('fired', false);
        }, 200, this);
        e.preventDefault();
    });

    $(".person .picto-plus").on('focus blur', function(e) {
        $(this).parents(".person").find(".mask-wrap").toggleClass("focused");
    });

    /**** barre cookies ****/
    $('#cookie-barre').animate({
        'height': "auto"
    }, 500);
    $("#fermer").mousedown(function(){
        $('#cookie-barre').animate({
            'padding': '0',
            'height': "0",
            'opacity':'0'
        }, 500);
    });

    $( ".btn-toggle" ).on( "click", function(event) {
        event.preventDefault();

        $(this).parent(".checkbox").children('.sous-thematiques').slideToggle();
        $(this).toggleClass("icon-down-open-1 icon-up-open-1", 1000, "easeOutSine" );
    });
    $(".mobile-toggle").click(function(event){
        event.preventDefault();
        $(this).toggleClass("icon-down-open-1 icon-up-open-1", 1000, "easeOutSine" );
        $(this).parent("li").toggleClass("open",300);
    });
//added
    $('.sous-thematiques input:checkbox').each(function(){
        if($(this).is(':checked')) {
            $(this).parents(".checkbox").children('.sous-thematiques').slideDown();
            $(this).toggleClass("icon-down-open-1 icon-up-open-1", 1000, "easeOutSine" );
        }
    });
    $(".tags").each(function(){
        if($(this).is(':checked')) {
            $(this).parent(".checkbox").find('.sous-thematiques input:checkbox').each(function() {
                $(this).attr('checked', true);
            });
        }
    });
    $( ".tags" ).on( "change", function() {
        if($(this).is(':checked')) {
            $(this).parent(".checkbox").find('.sous-thematiques input:checkbox').each(function() {
                $(this).prop('checked', true);
            });
        }
        else {
            $(this).parent(".checkbox").find('.sous-thematiques input:checkbox').each(function() {
                $(this).prop('checked', false);
            });
        }
    });


    $('#slideFocus').flexslider({
        animation: "slide",
        controlNav: false,
        itemWidth: 300,
        maxItems: 1,
        prevText: "",
        nextText: "",
        start: function(slider) {
            $('.current-slide').text(slider.currentSlide+1);
            $('.total-slides').text(slider.count);
        },
        after: function(slider) {
            $('.current-slide').text(slider.currentSlide+1);
        }
    });
    $('#slideshowId').flexslider({
        animation: "fade",
        directionNav: true,
        prevText: "",
        nextText: "",
        start: function(slider) {
            $('#slideshowId .flex-control-paging li').each(function(){
                $(this).find('a').attr('tabindex', 0);
            });
        }
    });
    $('#actu2Slider').flexslider({
        animation: "fade",
        directionNav: false,
        controlNav: true
    });
    $('#eventSlider').flexslider({
        slideshow: true,
        animation: "fade",
        directionNav: false,
        // manualControls: ".flex-control-paging li.pager",
        useCSS: false, /* Chrome fix*/
        start: function(){
            // On ajuste la hauteur de la liste en fonction de la hauteur du div et de l'accroche
            divheight = $('#eventSlider .flex-active-slide').height();
            listheight = $('#eventSlider .flex-active-slide .flex-caption').height();
            //$('#eventSlider .flexslider-controls ol.flex-control-paging').height( divheight - listheight);
        },
        after: function(){
            // On ajuste la hauteur de la liste en fonction de la hauteur du div et de l'accroche
            divheight = $('#eventSlider .flex-active-slide').height();
            listheight = $('#eventSlider .flex-active-slide .flex-caption').height();
            //$('#eventSlider .flexslider-controls ol.flex-control-paging').height( divheight - listheight);
        }
    });

    /** SLIDE DATES À RETENIR **/
    var $window = $(window),
        flexslider;

    function getGridSize() {
        // return  (window.innerWidth < 570) ? 2 : 3;
        return  (window.innerWidth < 480) ? 1 :
            (window.innerWidth < 767) ? 2 :3;
    }

    $('#slideDates').flexslider({
        animation: "slide",
        controlNav: false,
        animationLoop: false,
        itemWidth: 318,
        itemMargin: 27,
        prevText: "",
        nextText: "",
        minItems: getGridSize(), // use function to pull in initial value
        maxItems: getGridSize(), // use function to pull in initial value
        before: function(slider) {
            $('#slideDates .flex-direction-nav li').each(function(){
                $(this).find('a').attr('tabindex', "");
            });
        },
        after: function(slider) {
            $('#slideDates .flex-direction-nav li').each(function(){
                $(this).find('a').attr('tabindex', "");
            });
        }
    });

    /*Slider actualité version3*/
    function getGridSize3() {
        return  (window.innerWidth < 480) ? 1 :
            (window.innerWidth < 767) ? 2 :
                (window.innerWidth < 992) ? 3 :4;
    }
    $('#eventSlider3').flexslider({
        animation: "slide",
        controlNav: false,
        animationLoop: false,
        itemWidth: 318,
        itemMargin: 46,
        prevText: "",
        nextText: "",
        minItems: getGridSize3(), // use function to pull in initial value
        maxItems: getGridSize3(), // use function to pull in initial value
        before: function(slider) {
            $('#eventSlider3 .flex-direction-nav li').each(function(){
                $(this).find('a').attr('tabindex', "");
            });
        },
        after: function(slider) {
            $('#eventSlider3 .flex-direction-nav li').each(function(){
                $(this).find('a').attr('tabindex', "");
            });
        }
    });

    // check grid size on resize event
    $window.resize(function() {
        var gridSize1 = getGridSize();
        if($('#slideDates').length){
            $('#slideDates').data('flexslider').vars.minItems = gridSize1;
        }
        var gridSize3 = getGridSize3();
        if($('#eventSlider3').length){
            $('#eventSlider3').data('flexslider').vars.minItems = gridSize3;
        }
    });

    /** SLIDES PAGE AGENDA **/

    function getEventGridSize() {
        if(window.innerWidth < 400){return 1;}
        if(window.innerWidth < 700){return 2;}
        else{return 3;}
    }

    $window.load(function() {
        $('.permanent-events-slider').flexslider({
            animation: "slide",
            controlNav: false,
            animationLoop: false,
            itemWidth: 186,
            itemMargin: 25,
            prevText: "prev",
            nextText: "next",
            slideshow: false,
            touch: true,
            minItems: getEventGridSize(), // use function to pull in initial value
            maxItems: getEventGridSize() // use function to pull in initial value
        });
    });

    $window.load(function() {
        $('.events-slider').flexslider({
            animation: "slide",
            controlNav: false,
            animationLoop: false,
            itemWidth: 100,
            itemMargin: 23,
            prevText: "",
            nextText: "",
            slideshow: false,
            touch: true,
            minItems: getEventGridSize(), // use function to pull in initial value
            maxItems: getEventGridSize() // use function to pull in initial value
        });
    });

    // check grid size on resize event
    $window.resize(function() {
        var gridSize = getEventGridSize();
        $( '.events-slider' ).each(function() {
            $(this).data('flexslider').vars.minItems = gridSize;
            $(this).data('flexslider').vars.maxItems = gridSize;
        });
        if($('.permanent-events-slider').length){
            $('.permanent-events-slider').data('flexslider').vars.minItems = gridSize;
            $('.permanent-events-slider').data('flexslider').vars.maxItems = gridSize;
        }
    });


    /**** datepicker ****/

   /* $('#date-agenda').datetimepicker({ locale: 'fr',format: 'DD/MM/YYYY' });


    $('#datetimepicker1').datetimepicker({ locale: 'fr',format: 'DD/MM/YYYY' });
    $('#datetimepicker2').datetimepicker({ locale: 'fr',format: 'DD/MM/YYYY' });
    $("#datetimepicker2").on("dp.change",function (e) {
        $('#datetimepicker1').data("DateTimePicker").maxDate(e.date);
    });
    $("#datetimepicker1").on("dp.change",function (e) {
        $('#datetimepicker2').data("DateTimePicker").minDate(e.date);
    });

    if($("#datetimepicker").length) {
        $.datepicker.regional['fr'] = {
            closeText: 'Fermer',
            currentText: 'Courant',
            prevText: 'Mois précédent',
            nextText: 'Mois suivant',
            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'],
            dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
            dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
            dayNamesMin: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
            weekHeader: 'Sm',
            //dateFormat: 'dd/mm/yy',
            dateFormat: 'dd/mm/yy',

            todayHighlight: true
        };
        $.datepicker.setDefaults($.datepicker.regional['fr']);
        var date_input_du = $('#du').val();
        var date_input_au = $('#au').val();
        var _default_date = '';
        if (date_input_du === date_input_au){
            _default_date = date_input_du;
        }

        $("#datetimepicker").datepicker({
            defaultDate: _default_date,
            onSelect: function(dateStr) {
                var date = $(this).datepicker('getDate');
                if (date) {
                    var date = $.datepicker.formatDate('dd/mm/yy', date);
                    $("input#du").val(date);
                    $("input#au").val(date);
                    $("#optionsRadios1").prop('checked',false);
                    $("#optionsRadios2").prop('checked',false);
                    $("#optionsRadios3").prop('checked',false);
                }
            }
        });
        $(".ui-datepicker-calendar tbody td").each(function() {
            var day = $(this).children("a").text();
            var month = $(this).attr('data-month');
            var monthNames = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
                'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
            var M = monthNames[month];
            var year = $(this).attr('data-year');
            $(this).children("a").attr('title', "Le "+ day+ " "+ M + " " + year);
        });

        $(document).on('click', '.ui-datepicker-next', function () {
            $(".ui-datepicker-calendar tbody td").each(function() {
                var day = $(this).children("a").text();
                var month = $(this).attr('data-month');
                var monthNames = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
                    'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
                var M = monthNames[month];
                var year = $(this).attr('data-year');
                $(this).children("a").attr('title', "Le "+ day+ " "+ M + " " + year);
            });
        });

        $(document).on('click', '.ui-datepicker-prev', function () {
            $(".ui-datepicker-calendar tbody td").each(function() {
                var day = $(this).children("a").text();
                var month = $(this).attr('data-month');
                var monthNames = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
                    'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
                var M = monthNames[month];
                var year = $(this).attr('data-year');
                $(this).children("a").attr('title', "Le "+ day+ " "+ M + " " + year);
            });
        });
    }
    if($("#optionsRadios1").is(":checked")){
        var curr = new Date;
        $("input#du").val($.datepicker.formatDate('dd/mm/yy', new Date(curr.setDate(curr.getDate() - curr.getDay()+6))));
        $("input#au").val($.datepicker.formatDate('dd/mm/yy', new Date(curr.setDate(curr.getDate() - curr.getDay()+7))));
    }
    if($("#optionsRadios2").is(":checked")){
        var date = new Date();
        $("input#du").val($.datepicker.formatDate('dd/mm/yy', date));
        date.setDate(date.getDate() + 7); // Add 7 days
        $("input#au").val($.datepicker.formatDate('dd/mm/yy', date));
    }
    if($("#optionsRadios3").is(":checked")){
        var today = new Date();
        $("input#du").val($.datepicker.formatDate('dd/mm/yy', new Date(today.getFullYear(),today.getMonth(), 1)));
        $("input#au").val($.datepicker.formatDate('dd/mm/yy', new Date(today.getFullYear(),today.getMonth()+1, 0)));

    }
    $('.radio-group input:radio').click(function() {
        if ($(this).val() === '1') {
            var curr = new Date;
            $("input#du").val($.datepicker.formatDate('dd/mm/yy', new Date(curr.setDate(curr.getDate() - curr.getDay()+6))));
            $("input#au").val($.datepicker.formatDate('d/mm/yy', new Date(curr.setDate(curr.getDate() - curr.getDay()+7))));
        } else if ($(this).val() === '2') {
            var date = new Date();
            $("input#du").val($.datepicker.formatDate('dd/mm/yy', date));
            date.setDate(date.getDate() + 7); // Add 7 days
            $("input#au").val($.datepicker.formatDate('dd/mm/yy', date));
        } else if ($(this).val() === '3') {
            var today = new Date();
            $("input#du").val($.datepicker.formatDate('dd/mm/yy', new Date(today.getFullYear(),today.getMonth(), 1)));
            $("input#au").val($.datepicker.formatDate('dd/mm/yy', new Date(today.getFullYear(),today.getMonth()+1, 0)));
        }
    });
*/
    if (window.matchMedia("(min-width: 1201px)").matches) {
    }
    if (window.matchMedia("(max-width: 1200px)").matches) {
        var heightImgActu = $( "#eventSlider .pager" ).height();
        var heightBlocActu = $( "#eventSlider .flexslider-controls" ).height();
        $("#eventSlider .flex-caption").css("min-height",(heightImgActu+1));
        $("#eventSlider .slides li > div").css("min-height",heightBlocActu);
        $("#bloc-actualites #eventSlider .slides .fitted a").css("height",(heightImgActu*2));
    }
    if (window.matchMedia("(max-width: 991px)").matches) {
        //menuRowWrapper(".dropdown-menu .menu-bloc", 2);

        $( ".contenu-bas" ).appendTo( $( "aside.col-md-4" ) );
        $( "header .navbar-default .navbar-collapse" ).prepend( $( "header .header-top .bloc-right" ) );
        $( "header .navbar-default .navbar-right" ).insertAfter( $( "header .navbar-default .navbar-left" ) );
        $( "header .navbar-default li.translate" ).insertAfter( $( "header .navbar-default li.recherche" ) );
        $( "header .navbar-default .navbar-collapse" ).append( $( "footer .footer-content .footer-nav-2" ) );
        if($( "header .navbar-default .navbar-collapse .copyright" ).length === 0){
            $( "header .navbar-default .navbar-collapse" ).append( "<ul class='copyright'></ul>" );
        }
        $( "header .navbar-default .navbar-collapse .copyright" ).append( $( "footer .footer-bottom .copyright li:not(':first'):not(':last')" ) );


        $("#eventSlider .flex-caption").removeAttr('style');
        $("#eventSlider .slides li > div").removeAttr('style');
        $("#bloc-actualites #eventSlider .slides .fitted a").removeAttr('style');
    }
    else{
        $( "aside.col-md-4 .contenu-bas" ).appendTo( $( "section.col-md-8" ) );
        $( "header .navbar-default .navbar-collapse .bloc-right" ).appendTo( $( "header .header-top .header-top-in" ) );
        $( "header .navbar-default .navbar-right" ).appendTo( $( ".navbar-default .navbar-collapse" ) );
        $( "footer .footer-content .last-col" ).prepend( $( "header .navbar-default .navbar-collapse .footer-nav-2" ) );
        $( "header .navbar-default .navbar-collapse .copyright li" ).insertAfter( $( "footer .footer-bottom .copyright li:first" ) );
    }
    if (window.matchMedia("(max-width: 767px)").matches) {

        // $( ".introduction .container" ).append( $( ".introduction .voir-plus" ) );
        $( "#bloc-medias aside .row " ).after( $( "#bloc-medias aside .voir-plus" ));
        $( "#bloc-medias section .photos" ).after( $( "#bloc-medias section .voir-plus" ));
        var txt_with_img = $( ".visuel-article" ).next(".txt");
        $( ".visuel-article" ).insertAfter( $(txt_with_img).children("h3") );

        $("#bloc-medias.bloc-media-style2 section").append($("#bloc-medias.bloc-media-style2 section .voir-plus"));
        $("#bloc-medias.bloc-media-style2 aside").append($("#bloc-medias.bloc-media-style2 aside .voir-plus"));

    }else{

    }

    var lastWindowWidth;

    $(window).on('resize', function() {

        var $window = $(this),
            windowWidth = $window.width();

        var posElement = $('.services-container .item-service.profil').index();
        if(lastWindowWidth >= windowWidth){
            if (window.innerWidth >= 992) {
                if(posElement != 3){
                    $(".services-container .item-service:nth-child(3)").after($('.services-container .item-service.profil'));
                }
            }
            if(window.innerWidth >= 651 && window.innerWidth < 992){
                if(posElement != 2){
                    $(".services-container .item-service:nth-child(2)").after($('.services-container .item-service.profil'));
                }
            }
            if(window.innerWidth >= 480 && window.innerWidth < 651){
                if(posElement != 1){
                    $(".services-container .item-service:nth-child(1)").after($('.services-container .item-service.profil'));
                }
            }
            if(window.innerWidth < 480){
                if(posElement != 0){
                    $( ".services-container" ).prepend( $( ".services-container .item-service.profil" ) );
                }
            }
        }else{
            if (window.innerWidth >= 992) {
                if(posElement != 3){
                    $(".services-container .item-service:nth-child(4)").after($('.services-container .item-service.profil'));
                }
            }
            if(window.innerWidth >= 651 && window.innerWidth < 992){
                if(posElement != 2){
                    $(".services-container .item-service:nth-child(3)").after($('.services-container .item-service.profil'));
                }
            }
            if(window.innerWidth >= 480 && window.innerWidth < 651){
                if(posElement != 1){
                    $(".services-container .item-service:nth-child(2)").after($('.services-container .item-service.profil'));
                }
            }
            if(window.innerWidth < 480){
                if(posElement != 0){
                    $( ".services-container" ).prepend( $( ".services-container .item-service.profil" ) );
                }
            }
        }
        lastWindowWidth = windowWidth;

        var mainVideoHeight=$(".main-video .img-wrap a  img").height();
        $("#bloc-medias .photos ul > li").css("height",(mainVideoHeight/2)-5);
        $("#bloc-medias.bloc-media-style2 .publications").css("height",mainVideoHeight);

        if (window.matchMedia("(min-width: 1201px)").matches) {
            $("#eventSlider .flex-caption").removeAttr('style');
            $("#eventSlider .slides li > div").removeAttr('style');
            $("#bloc-actualites #eventSlider .slides .fitted a").removeAttr('style');
        }
        if (window.matchMedia("(max-width: 1200px)").matches) {
            var heightImgActu = $( "#eventSlider .pager" ).height();
            var heightBlocActu = $( "#eventSlider .flexslider-controls" ).height();
            $("#bloc-actualites #eventSlider .slides .fitted a").css("height",(heightImgActu*2));
            $("#eventSlider .flex-caption").css("min-height",(heightImgActu + 1));
            $("#eventSlider .slides li > div").css("min-height",heightBlocActu);
        }
        else{
            $("#eventSlider .flex-caption").removeAttr('style');
            $("#eventSlider .slides li > div").removeAttr('style');
            $("#bloc-actualites #eventSlider .slides .fitted a").removeAttr('style');
        }
        if (window.innerWidth < 992) {
            $( ".contenu-bas" ).appendTo( $( "aside.col-md-4" ) );
            $( "header .navbar-default .navbar-collapse" ).prepend( $( "header .header-top .bloc-right" ) );
            $( "header .navbar-default .navbar-right" ).insertAfter( $( "header .navbar-default .navbar-left" ) );
            $( "header .navbar-default li.translate" ).insertAfter( $( "header .navbar-default li.recherche" ) );
            $( "header .navbar-default .navbar-collapse" ).append( $( "footer .footer-content .footer-nav-2" ) );
            if($( "header .navbar-default .navbar-collapse .copyright" ).length === 0){
                $( "header .navbar-default .navbar-collapse" ).append( "<ul class='copyright'></ul>" );
            }
            $( "header .navbar-default .navbar-collapse .copyright" ).append( $( "footer .footer-bottom .copyright li:not(':first'):not(':last')" ) );
        }
        else{
            $( "aside.col-md-4 .contenu-bas" ).appendTo( $( "section.col-md-8" ) );
            $( "header .navbar-default .navbar-collapse .bloc-right" ).appendTo( $( "header .header-top .header-top-in" ) );
            $( "header .navbar-default .navbar-right" ).appendTo( $( ".navbar-default .navbar-collapse" ) );
            $( "footer .footer-content .last-col" ).prepend( $( "header .navbar-default .navbar-collapse .footer-nav-2" ) );
            $( "header .navbar-default .navbar-collapse.in" ).removeClass("in");
            $( "header .navbar-default .navbar-collapse .copyright li" ).insertAfter( $( "footer .footer-bottom .copyright li:first" ) );
        }
        if (window.innerWidth < 768) {

            // $( ".introduction .container" ).append( $( ".introduction .voir-plus" ) );
            var txt_with_img = $( ".visuel-article" ).next(".txt");
            $( ".visuel-article" ).insertAfter( $(txt_with_img).children("h3") );
        }else{

        }

    });
    /**** nicescroll ****/

        //$("body").niceScroll({cursorcolor:"rgba(52,52,52,0.5)",boxzoom:true,zindex: 999999,cursorborder: 0,cursorborderradius:0});
    $("#eventSlider .flexslider-controls").niceScroll("#eventSlider .flex-control-paging",{cursorcolor:"rgba(9,6,4,0.3)",cursorborder: 0,cursorborderradius:5,bouncescroll:false,cursorwidth:7});
    $('.scrollbar-macosx').scrollbar();
    /**** Accès scroll ancre ****/

    $('.scrollTo').click( function() { // Au clic sur un élément
        var page = $(this).attr('href'); // Page cible
        var speed = 600; // Durée de l'animation (en ms)
        $('html, body').animate( { scrollTop: $(page).offset().top }, speed ); // Go
        return false;
    });


    /**** Fontsize + - ****/

    $('body, .item-citoyen').jfontsize({
        btnMinusClasseId: '#jfontsize-m2', // Defines the class or id of the decrease button
        btnDefaultClasseId: '#jfontsize-d2', // Defines the class or id of default size button
        btnPlusClasseId: '#jfontsize-p2', // Defines the class or id of the increase button
        btnMinusMaxHits: 1, // How many times the size can be decreased
        btnPlusMaxHits: 5, // How many times the size can be increased
        sizeChange: 5 // Defines the range of change in pixels
    });



    $(".favori").click(function () {
        alert("Appuyez sur CTRL + D pour ajouter la page dans vos favoris ");
    });
    $(".print").click(function () {
        window.print();
    });


    $(window).load(function() {
        /******Height menu item principal******/
        //var max = $(".navbar-left > li.dropdown").height();
        //$(".navbar-left > li.dropdown").each(function() {
        //    var h = $(this).height();
        //    max = h > max ? h : max;
        //});
        //$(".navbar-left > li.dropdown > a").css("height",max);
        /*********/
        // Fix heights on page load
        // equalizeHeights(".liste-actus .actu-item");
        equalizeHeights("#bloc-images .video-list li");

        // Fix heights on window resize
        $(window).resize(function() {
            /******Height menu item principal******/
            //var max = $(".navbar-left > li.dropdown").height();
            //$(".navbar-left > li.dropdown > a").css("height",max);
            /*********/
            // Needs to be a timeout function so it doesn't fire every ms of resize
            setTimeout(function() {
                // equalizeHeights(".liste-actus .actu-item");
                equalizeHeights("#bloc-images .video-list li");

            }, 120);
        });

        //isotope
        var nbrItem;
        var nomclass;
        nbrItem = $(".grid .grid-item").length;

        switch (nbrItem) {
            case 5:
                nomclass = 'ligne5';
                break;
            case 6:
                nomclass = 'ligne6';
                break;
            case 8:
                nomclass = 'ligne8';
                break;
            default:
                nomclass = "item"+nbrItem.toString();
        }

        // $( ".grid .grid-item" ).addClass( nomclass);

        $('.grid').isotope({
            // options
            itemSelector: '.grid-item',
            layoutMode: 'fitRows'
        });

    });

    //nous parcourons toutes les classes chargement grâce à la fonction "each"
    $(".chargement").each(function(index, element) {

        //on récupère le chiffre contenu dans le div pourcentage
        var pourcent = parseInt($(element).text());

        //on ajoute un "div" avec une "classe loading" dans notre div pourcentage
        $(element).html('<div class="loading"></div>');

        //on applique les propriétés css à notre div loading
        $(element).find('.loading').css({"width":"0px",
            "float":"left",
            "color":"white",
            "text-align":"center",
            "height":"100%"});

        //on va attendre 1,5 seconde pour commencer l'animation.
        //puis nous faisons une opération qui va prendre la longueur du div multipliée par le nombre de vote divisé par 100

        $(element).find('.loading').delay(1500).animate({width:($(this).width() * pourcent) /100},"slow");

        //si le pourcentage est supérieur à 12, on affiche en clair dans le div loading le nombre de pourcentage.
        //supérieur à 12, car en dessous, le "div" serait trop petit pour accueillir un chiffre.
        $(this).parent(".chargement-wrap").append( pourcent +'%');

    });


    /***** bloc accès rapide droite  *****/
    if ( $('aside').children().length == 1 && $('aside').children().is(".bloc-acces")) {
        $(".bloc-acces").addClass('open');
        $(".bloc-acces .bloc-toggle").hide();

    }else{
        $(".bloc-acces h3").click(function(event) {
            var _self =$(this);
            _self.data('can-focus', 0);
            _self.closest(".bloc-acces").toggleClass('open', 'slow');
            _self.children("i").toggleClass("icon-down-open icon-up-open", "slow");
        });
        $(".bloc-acces h3").focus(function(event) {
            var _self =$(this);
            _self.data('can-focus', 1)
            setTimeout(function(){
                if(_self.data('can-focus') == 1){
                    _self.closest(".bloc-acces").addClass('open', 'slow');
                    _self.children("i").toggleClass("icon-down-open icon-up-open","slow");
                }
            }, 500);
        });
    }



    /**** fitted ****/
    if($('.fitted').length){
        $('.fitted').fitted();
    }

    $('.fitted a').each(function(){
        var targetVal = $(this).attr('target');
        if(targetVal =="_blank" ){
            $(this).attr("rel", "external");
        }
    });

    /******* paly/stop video *******/
    var video = $(".play-video").attr("src");

    //Play video
    $('.modal').each(function(){
        var video = $(".play-video",this).attr("src");
        $(this).on('show.bs.modal', function () {
            $(this).find(".play-video").attr("src",video);
        });
    })

    $('.modal').on('hidden.bs.modal', function () {
        $(this).find(".play-video").attr("src","");
    });




    function reposition() {
        var modal = $(this),
            dialog = modal.find('.modal-dialog');
        modal.css('display', 'block');
        dialog.css("margin-top", Math.max(0, ($(window).height() - dialog.height()) / 2));
    }
    $('.modal').on('show.bs.modal', reposition);
    // Reposition when the window is resized
    $(window).on('resize', function() {
        $('.modal:visible').each(reposition);
    });


    $(".lien-faq").on('click focus', function(e) {
        if ( !$(this).data('fired') ) {
            $(this).next(".faq_response").slideToggle( "slow" ).siblings(".faq_response:visible").slideUp("slow");
            $(this).toggleClass( "lien-faq-actif" );
            e.preventDefault();

        }

        $(this).data('fired', true);

        setTimeout(function(self) {
            $(self).data('fired', false);
        }, 200, this);
        e.preventDefault();
    });


    var mainVideoHeight=$(".main-video .img-wrap a img").height();
    $("#bloc-medias .photos ul > li").css("height",(mainVideoHeight/2)-5);
    $("#bloc-medias.bloc-media-style2 .publications").css("height",mainVideoHeight);



    // Cache selectors
    var lastId,
        topMenu = $("#barre-acces"),
        topMenuHeight = topMenu.outerHeight()+15,
    // All list items
        menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
        scrollItems = menuItems.map(function(){
            var item = $($(this).attr("href"));
            if (item.length) { return item; }
        });

// Bind click handler to menu items
// so we can get a fancy scroll animation
    menuItems.click(function(e){
        var href = $(this).attr("href"),
            offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
        $('html, body').stop().animate({
            scrollTop: offsetTop
        }, 500);
        e.preventDefault();
    });

// Bind to scroll
    $(window).scroll(function(){
        // Get container scroll position
        var fromTop = $(this).scrollTop()+topMenuHeight;

        // Get id of current scroll item
        var cur = scrollItems.map(function(){
            if ($(this).offset().top < fromTop)
                return this;
        });
        // Get the id of the current element
        cur = cur[cur.length-1];
        var id = cur && cur.length ? cur[0].id : "";

        if (lastId !== id) {
            lastId = id;
            // Set/remove active class
            menuItems
                .parent().removeClass("active")
                .end().filter("[href='#"+id+"']").parent().addClass("active");
        }
    });

    if ( $( "#bloc-focus" ).length ==0 ) {
        $('header .header-in').addClass("no-focus");
    }

    if ( $( "#bloc-focus .slides li" ).length == 1 ) {
        $('#slideFocus div.flex-viewport').addClass("one-element");
    }
}());


$(window).load(function() {
    // The slider being synced must be initialized first
    $('#carouselPhotos').flexslider({
        animation: "slide",
        controlNav: false,
        animationLoop: false,
        slideshow: false,
        itemWidth: 210,
        itemMargin: 5,
        asNavFor: '#sliderPhotos'
    });

    $('#sliderPhotos').flexslider({
        animation: "slide",
        smoothHeight : true,
        controlNav: false,
        animationLoop: false,
        slideshow: false,
        sync: "#carouselPhotos"
    });
    var mainVideoHeight=$(".main-video .img-wrap a img").height();
    $("#bloc-medias .photos ul > li").css("height",(mainVideoHeight/2)-5);
    $("#bloc-medias.bloc-media-style2 .publications").css("height",mainVideoHeight);
});
