import $ from "jquery";
import anime from 'animejs';
import Swiper from 'swiper/bundle';
import LocomotiveScroll from 'locomotive-scroll';
import Splitting from "splitting";
import Plyr from 'plyr';
import '@justinribeiro/lite-youtube';

import Utils from './utils/Utils';
import WindowUtils from './utils/WindowUtils';
import PageTransition from "./PageTransition";
import Carousel from "./Carousel";
import Cursor from "./Cursor";
import TextRotator from "./TextRotator";
import TrailEffect from "./TrailEffect";

// import GridDebug from './utils/GridDebug';
// new GridDebug(18,1);

const WU = new WindowUtils();

if (WU.isTouch()){
    $('html').addClass('touch');
}

let cursor = new Cursor();
let loaded = false;


/////////////////////////////////
// YOUTUBE //////////////////////
/////////////////////////////////

let videoPlayers = [];
let plyrPlayers = [];
let playerYT;

const initLYT = (elt) => {
    let vid = elt.getAttribute('data-player');
    if (!vid) {
        vid = videoPlayers.length;
        elt.setAttribute('data-player', vid);
        videoPlayers.push('xx');
    }

    setTimeout(() => {
        playerYT = new YT.Player(elt.shadowRoot.querySelector('iframe'), {
            events: {
                'onStateChange': onPlayerStateChange,
                'onReady': (e) => { onPlayerReady(e, elt); },
            }
        });
        videoPlayers[vid] = playerYT;
    }, 500);
}

document.addEventListener('liteYoutubeIframeLoaded', (event) => {
    initLYT(event.target);
}, false);

const onPlayerStateChange = (event) => {
    let playerStatus = event.data;

    if (playerStatus == -1) { /* unstarted */ }
    else if (playerStatus == 0) { /* ended */
        event.target.playVideo(); 
    } else if (playerStatus == 1) { /* playing */ }
    else if (playerStatus == 2) { /* paused */ }
    else if (playerStatus == 3) { /* buffering */ }
    else if (playerStatus == 5) { /* video cued */ }
};

const onPlayerReady = (event, parent) => {
    if (parent.hasAttribute('lyt-mute')) {
        event.target.mute();
    }
    if (!parent.hasAttribute('lyt-paused')) {
        event.target.playVideo();
    }
};

const playVideo = (playerId) => {
    if (playerId && videoPlayers[playerId]) {
        videoPlayers[playerId].playVideo();
    }
};

const pauseVideo = (playerId) => {
    if (playerId && videoPlayers[playerId]) {
        videoPlayers[playerId].pauseVideo();
    }
};


const initPage = () => {
    loaded = true;
    
    if (!WU.isXS()) {
        scroll.update();
    }

    Splitting();

    $('.mobileHeaderButton').on('click', function(){
        scroll.scrollTo($('.pSection').get(1), 0, 1000, [0.90, 0.00, 0.00, 1.00]);
    });


    $('.intro_mobile_play').on('click', function(){
        if ($('.intro_mobile_play').hasClass('playing')) {
            $('.intro_cover_mobile').find('video').get(0).pause();
            $('.intro_cover').removeClass('playing');
            $('.intro_mobile_play').removeClass('playing');
            $('.intro_titleWrap').removeClass('playing');
        } else {
            $('.intro_cover_mobile').find('video').get(0).play();
            $('.intro_cover').addClass('playing');
            $('.intro_mobile_play').addClass('playing');
            $('.intro_titleWrap').addClass('playing');
        }
    });

    let updateNewsType = () => {
        if (document.querySelectorAll('.newsBloc_type')) {
            document.querySelectorAll('.newsBloc_type').forEach((elt) => {
                let w = elt.querySelector('.newsBloc_type_label').offsetWidth - elt.querySelector('.newsBloc_type_fake').offsetWidth;
                elt.style.setProperty('--label-size', w + 'px');
            });
        }
    };

    updateNewsType();
    window.addEventListener('resize', Utils.debounce(() => { updateNewsType() }), { passive: true });

    // ----------------------------------------------------------------------------------------
    // PODCAST --------------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    let podcastWrap = $('.podcastWrap').get(0);

    if (podcastWrap) {
        let podcastCursor = $('.podcastWrap_cursor').get(0);
        let bounds = podcastWrap.getBoundingClientRect();
        let posX, posY;
        
        podcastWrap.addEventListener('click', (e) => {
            if (podcastWrap.classList.contains('podcastWrap--playing')) {
                pausePodcast();
                podcastWrap.classList.remove('podcastWrap--playing');
            } else {
                playPodcast();
                podcastWrap.classList.add('podcastWrap--playing');
            }
        });

        podcastWrap.addEventListener('mousemove', (e) => {
            bounds = podcastWrap.getBoundingClientRect();
            posX = e.clientX - bounds.left;
            posY = e.clientY - bounds.top;

            podcastCursor.style.transform = 'translate(' + posX + 'px,' + posY + 'px) scale(1)';
            podcastCursor.style.opacity = '1';
        });

        podcastWrap.addEventListener('mouseleave', () => {
            podcastCursor.style.transform = 'translate(' + posX + 'px,' + posY + 'px) scale(0)';
            podcastCursor.style.opacity = '0';
        });
    }



    // ----------------------------------------------------------------------------------------
    // MOBILE SECTIONS ------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    if (WU.isXS()) {
        const detectSectionMobile = () => {
            document.querySelectorAll('[data-scroll-call="detectSection"]').forEach((elt) => {
                let bounds = elt.getBoundingClientRect();
                if (bounds.top < 34 && bounds.bottom >= 34) {
                    let dataUI = elt.getAttribute('data-ui-mobile') || elt.getAttribute('data-ui') || null;
                    // UI COLOR
                    if (dataUI === 'dark') {
                        setDarkUi();
                    } else if (dataUI === 'light') {
                        setLightUi();
                    }
                }
            })
        };

        window.addEventListener('scroll', Utils.debounce(() => { detectSectionMobile() }), { passive: true });
        detectSectionMobile();
    }

    // ----------------------------------------------------------------------------------------
    // MOBILE SECTIONS ------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    if (WU.isXS()) {
        const detectHomeVideoMobile = () => {
            document.querySelectorAll('[data-scroll-call="homeVideo"').forEach((elt) => {
                if ($('.intro_cover_mobile').find('video')) {
                    if (window.scrollY > window.innerHeight) {
                        $('.intro_cover_mobile').find('video').get(0).pause();
                        $('.intro_cover').removeClass('playing');
                        $('.intro_mobile_play').removeClass('playing');
                        $('.intro_titleWrap').removeClass('playing');
                    }
                }
            })
        };

        window.addEventListener('scroll', Utils.debounce(() => { detectHomeVideoMobile() }), { passive: true });
        detectHomeVideoMobile();
    }

    // ----------------------------------------------------------------------------------------
    // CURSOR ---------------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    if ($('.header').length) {
        $('.header').on('mouseenter', () => cursor.show('header') );
        $('.header').on('mouseleave', () => cursor.hide() );
        $('.header').on('mousemove', (e) => { cursor.updatePos({ x : e.clientX, y : e.clientY }); });
        $('.header').find('a').each((i, link) => {
            link.addEventListener('mouseenter', () => cursor.hide());
            link.addEventListener('mouseleave', () => cursor.show('header'));
        });
        $('.header_action').on('click', () => {
            scroll.update();
            scroll.scrollTo($('.pSection').get(1), 0, 1000, [0.90, 0.00, 0.00, 1.00]);
        });
    }
    
    if ($('.hp_intro').length) {
        $('.hp_intro').on('mouseenter', () => cursor.show('header') );
        $('.hp_intro').on('mouseleave', () => cursor.hide() );
        $('.hp_intro').on('mousemove', (e) => { cursor.updatePos({ x : e.clientX, y : e.clientY }); });
        $('.hp_intro').find('a').each((i, link) => {
            link.addEventListener('mouseenter', () => cursor.hide());
            link.addEventListener('mouseleave', () => cursor.show('header'));
        });
        $('.hp_intro').find('button').each((i, link) => {
            link.addEventListener('mouseenter', () => cursor.hide());
            link.addEventListener('mouseleave', () => cursor.show('header'));
        });
        $('.intro_action').on('click', () => {
            scroll.update();
            scroll.scrollTo('.intro_contentStart', 0, 1000, [0.90, 0.00, 0.00, 1.00]);
        });
    }

    if ($('.cabinet_publiSlider').length) {
        $('.cabinet_publiSlider').on('mouseenter', () => cursor.show('drag') );
        $('.cabinet_publiSlider').on('mouseleave', () => cursor.hide() );
        $('.cabinet_publiSlider').on('mousemove', (e) => { cursor.updatePos({ x : e.clientX, y : e.clientY }); });
    }

    if ($('.rse-carousel_wrap').length) {
        $('.rse-carousel_wrap').on('mouseenter', () => cursor.show('drag') );
        $('.rse-carousel_wrap').on('mouseleave', () => cursor.hide() );
        $('.rse-carousel_wrap').on('mousemove', (e) => { cursor.updatePos({ x : e.clientX, y : e.clientY }); });
    }


    // ----------------------------------------------------------------------------------------
    // ANCHORS NAV ----------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    let anchorsContainer = $('.anchors');
    $('[data-scroll-container]').find('[is-anchor]').each(function(itemIndex, section){
        let id;

        if (section.hasAttribute('id')) {
            id = section.getAttribute('id');
        } else {
            id = Utils.guid();
        }
        let a = $('<a href="#' + id + '"></a>');
        if (itemIndex === 0) {
            a.addClass('active');
        }
        a.appendTo(anchorsContainer);
        section.setAttribute('id', id);

        a.on('click', (e) => {
            e.preventDefault();
            scroll.scrollTo(section, 0, 800, [0.90, 0.00, 0.00, 1.00]);
        })
    });


    // ----------------------------------------------------------------------------------------
    // MENU -----------------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    $('.menuToggle').on('click', (e) => {
        e.preventDefault();
        $('.menu').addClass('menu--opened');

        let Tl = anime.timeline();
        
        Tl.add({
            targets: '.menu_mask',
            duration: 400,
            easing: "linear",
            opacity: [0, 1]
        }, 0);

        Tl.add({
            targets: '.menu_content',
            duration: 600,
            easing: "easeOutExpo",
            translateX: ["101%", 0],
            translateZ: 0
        }, 200);

        Tl.add({
            targets: '.mainMenu .menu-item',
            duration: 800,
            easing: "easeOutExpo",
            opacity: 1,
            translateX: [100,0],
            delay: anime.stagger(50)
        }, 500);
        Tl.add({ targets: '.secondMenu', duration: 800, easing: "easeOutExpo", translateX: [100,0], opacity: 1 }, 700);

        Tl.add({ targets: '.menu_top', duration: 600, easing: "linear", opacity: 1 }, 700);
        Tl.add({ targets: '.menu_bottom', duration: 600, easing: "linear", opacity: 1 }, 700);

        scroll.stop();
    });

    $('.menu_mask, .menu_top_close').on('click', (e) => {
        e.preventDefault();

        let Tl = anime.timeline({
            complete: () => {
                $('.menu').removeClass('menu--opened');
                scroll.start();
            }
        });

        Tl.add({ targets: '.menu_top', duration: 400, easing: "linear", opacity: [1,0] }, 0);
        Tl.add({ targets: '.menu_bottom', duration: 400, easing: "linear", opacity: [1,0] }, 0);

        Tl.add({
            targets: '.mainMenu .menu-item',
            duration: 600,
            easing: "easeOutExpo",
            opacity: [1, 0],
            translateX: [0,100],
            delay: anime.stagger(20)
        }, 200);

        Tl.add({ targets: '.secondMenu', duration: 600, easing: "easeOutExpo", translateX: [0,100], opacity: [1,0] }, 300);

        Tl.add({
            targets: '.menu_mask',
            duration: 400,
            easing: "linear",
            opacity: [1, 0]
        }, 400);

        Tl.add({
            targets: '.menu_content',
            duration: 600,
            easing: "easeOutExpo",
            translateX: [0, "101%"],
            translateZ: 0
        }, 400);
    });


    // ----------------------------------------------------------------------------------------
    // TEXT ROTATOR ---------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    $('.textRotator').each(function(){
        new TextRotator(this);
    });


    // ----------------------------------------------------------------------------------------
    // CAROUSELS ------------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    if ($('.hp_news .carousel').length > 0) {
        new Carousel('.hp_news .carousel');
    }
    if ($('.hp_cabinet .carousel').length > 0) {
        new Carousel('.hp_cabinet .carousel', { counterSelector: '.hp_cabinet .sectionTitle_header_additional' });
    }


    // ----------------------------------------------------------------------------------------
    // SLIDESHOW ------------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    const launchSlideshow = (slideshow) => {
        let nbItems = $(slideshow).find('.slideshow_item').length;
        let animatedItems = 0;
        let itemsData = [];
        let prev = { DOM: undefined, left: 0, duration: 0, delay: 0 };
    
        $(slideshow).find('.slideshow_item').each(function(itemIndex, item){
            let bounds = item.getBoundingClientRect();
            let data = {
                DOM: item,
                left: WU.isXS() ? Utils.randomInt(-20, 30) : Utils.randomInt(1, 80),
                duration: Utils.randomInt(100, 150) * 100,
                delay: (Utils.randomFloat(0.25, 0.5) * prev.duration) + prev.delay,
                translateY: (1 + ((bounds.height/window.innerHeight) * 1.15)) * -100
            }
            prev = data;
            itemsData.push(data);
        });

        itemsData.forEach((item, index) => {
            $(item.DOM).css('left', item.left + 'vw').css('opacity', 1);

            anime({
                targets: item.DOM,
                translateY: ['1vh', item.translateY + 'vh'],
                translateZ: 0,
                duration: item.duration,
                delay: item.delay,
                easing: 'easeOutCubic',
                complete: () => {
                    anime.remove(item.DOM);
                    anime.set(item.DOM, { opacity: 0 });
                    anime.set(item.DOM.querySelector('.slideshow_item_cover'), { scale: 1.4 });
                    anime.remove(item.DOM.querySelector('.slideshow_item_cover'));
                    animatedItems++;

                    if (animatedItems === nbItems) {
                        launchSlideshow(slideshow);
                    }
                }
            });
            anime({
                targets: item.DOM.querySelector('.slideshow_item_cover'),
                scale: [1.4, 1],
                translateZ: 0,
                duration: item.duration * 0.9,
                delay: item.delay - 200,
                easing: 'easeOutExpo'
            });
        });
    };

    $('.slideshow').each(function(index, slideshow){
        launchSlideshow(slideshow);
    });


    // ----------------------------------------------------------------------------------------	
    // CABINET --------------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------	
    if ($('body').hasClass('page-template-tpl-cabinet')) {
        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);
        if (urlParams.has('section')) {
            let section = $('[data-section="' + urlParams.get('section') + '"]');
            if (section.length > 0) {
                setTimeout(() => {
                    scroll.scrollTo(section.get(0), 0, 800, [0.90, 0.00, 0.00, 1.00]);
                }, 2000);
            }
        }

        new Swiper('.numbersCarousel', {	
            slidesPerView: 1,
            spaceBetween: 60,
            pagination: {
              el: '.numbersCarousel .swiper-pagination'
            }
        });

        new Swiper('.publiCarousel', {	
            slidesPerView: 1,
            spaceBetween: 15,
            breakpoints: {
                768: {
                    slidesPerView: 2,
                    spaceBetween: 40
                }
            }
        });

        let teamCarousel = new Swiper('.teamMobileCarousel', {	
            slidesPerView: 1,
            spaceBetween: 0,
            loop: true
        });

        $('.teamMobileCarousel_next').on('click', () => { teamCarousel.slideNext() });

        $('.publicationBloc, .newsBloc').on('mouseenter', function (e) {
            $(this).closest('.pSection--member').find('.memberMask').addClass('visible');
        });
        $('.publicationBloc, .newsBloc').on('mouseleave', function (e) {
            $(this).closest('.pSection--member').find('.memberMask').removeClass('visible');
        });
    }

    
    // ----------------------------------------------------------------------------------------
    // EXPERTISES -----------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    let prestaContainer = $('.prestaContainer');

    $('.prestaList').find('a').on('click', function(e) {
        e.preventDefault();
        
        let visiblePresta = $('.presta--visible');

        if (visiblePresta.length > 0) {
            visiblePresta.removeClass('presta--visible');
            visiblePresta.find('.presta_item').removeAttr('data-animated');
            anime.set(visiblePresta.get(0).querySelectorAll('.presta_cover'), { translateY: 100, opacity: 0 } );
            anime.set(visiblePresta.get(0).querySelectorAll('.presta_content'), { translateY: 100, opacity: 0 } );
        }

        $('.prestaList_link--active').removeClass('prestaList_link--active');
        $(this).addClass('prestaList_link--active');

        let pres = $($(this).attr('data-pres-id'));
        prestaContainer.toggleClass('prestaContainer--opened');
        
        pres.addClass('presta--visible');

        $('.prestaTitle--visible').removeClass('prestaTitle--visible');
        $('.prestaTitle[data-pres-id="' + $(this).attr('data-pres-id') + '"]').addClass('prestaTitle--visible');

        scroll.update();
        scroll.scrollTo(pres.get(0), 0, 1000, [0.90, 0.00, 0.00, 1.00]);
    });

    if ($('.prestaContainer').length > 0) {
        const resizePrestaContents = () => {
            let container = $('.prestaContainer--opened');
            let contentHeight = container.find('.presta--visible').outerHeight();
            container.height(contentHeight);
        };

        window.addEventListener('resize', Utils.debounce(() => { resizePrestaContents() }), { passive: true });
    }

    if ($('.expertises_cabinet .carousel').length > 0) {
        new Carousel('.expertises_cabinet .carousel', { interval: 8000, counterSelector: '.expertises_cabinet .sectionTitle_header_additional' });
    }

    if ($('body').hasClass('page-template-tpl-expertises')) {
        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);
        if (urlParams.has('pres')) {
            const a = $('.prestaList').find('a[data-pres-id="#pres-' + urlParams.get('pres') + '"]');
            if (a.length > 0) {
                setTimeout(() => {
                    a[0].click();
                }, 2000);
            }
        }
    }
    
    // ----------------------------------------------------------------------------------------	
    // PUBLICATIONS ---------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------	
    if ($('body').hasClass('page-template-tpl-publications')) {
        if (WU.isXS()) {
            new Swiper('.publications_introCarouselMobile', {	
                slidesPerView: 1,
                spaceBetween: 0,
                pagination: {
                el: '.publications_introCarouselMobile .swiper-pagination'
                }
            });

            let publiNavCarousel = new Swiper('.publications_navMobile_carousel', {	
                slidesPerView: 1,
                spaceBetween: 0
            });

            $('.publications_navMobile_next').on('click', () => { publiNavCarousel.slideNext() });

            const togglePublications = (year) => {
                let TL = anime.timeline({
                    easing: 'easeInOutExpo'
                });

                TL.set('.publications_list .publicationWrap', { display: 'none' });
                TL.set('.publications_list .publicationWrap[data-year="' + year + '"]', { display: 'block' });
                TL.add({ targets: '.publications_list .publicationWrap[data-year="' + year + '"]', opacity: [0, 1], translateY: [40, 0], duration: 800 });
        
            };

            let slide = publiNavCarousel.slides[publiNavCarousel.activeIndex];
            togglePublications(slide.getAttribute('data-year'));

            publiNavCarousel.on('slideChange', function () {
                slide = publiNavCarousel.slides[publiNavCarousel.activeIndex];
                togglePublications(slide.getAttribute('data-year'));
            });
        }
        else {
            $('.publicationWrap').on('mouseenter', function() {
                $('.publicationWrap').not($(this)).addClass('hidden');
            });

            $('.publicationWrap').on('mouseleave', function() {
                $('.publicationWrap').removeClass('hidden');
            });
        }
    }


    // ----------------------------------------------------------------------------------------	
    // ACTUALITES ---------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------	
    if ($('body').hasClass('page-template-tpl-actualites')) {
        if (WU.isXS()) {
            let actusNavCarousel = new Swiper('.actus_navMobile_carousel', {	
                slidesPerView: 1,
                spaceBetween: 0
            });

            $('.actus_navMobile_next').on('click', () => { actusNavCarousel.slideNext() });

            const toggleActualites = (year) => {
                let TL = anime.timeline({
                    easing: 'easeInOutExpo'
                });

                TL.set('.actus_year', { display: 'none' });
                TL.set('.actus_year[data-year="' + year + '"]', { display: 'block' });
                TL.add({ targets: '.actus_year[data-year="' + year + '"]', opacity: [0, 1], translateY: [40, 0], duration: 800 });
            };

            let slide = actusNavCarousel.slides[actusNavCarousel.activeIndex];
            toggleActualites(slide.getAttribute('data-year'));

            actusNavCarousel.on('slideChange', function () {
                slide = actusNavCarousel.slides[actusNavCarousel.activeIndex];
                toggleActualites(slide.getAttribute('data-year'));
            });
        }
    }


    // ----------------------------------------------------------------------------------------	
    // WEBINAIRES -----------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------	
    if ($('body').hasClass('page-template-tpl-webinaires')) {
        setTimeout(() => {
            scroll.start();
        }, 1000);

        if (WU.isXS()) {
            let webinarsNavCarousel = new Swiper('.webinars_navMobile_carousel', {	
                slidesPerView: 1,
                spaceBetween: 0
            });

            $('.webinars_navMobile_next').on('click', () => { webinarsNavCarousel.slideNext() });

            const toggleActualites = (year) => {
                let TL = anime.timeline({
                    easing: 'easeInOutExpo'
                });

                TL.set('.actus_year', { display: 'none' });
                TL.set('.actus_year[data-year="' + year + '"]', { display: 'block' });
                TL.add({ targets: '.actus_year[data-year="' + year + '"]', opacity: [0, 1], translateY: [40, 0], duration: 800 });
            };

            let slide = webinarsNavCarousel.slides[webinarsNavCarousel.activeIndex];
            toggleActualites(slide.getAttribute('data-year'));

            webinarsNavCarousel.on('slideChange', function () {
                slide = webinarsNavCarousel.slides[webinarsNavCarousel.activeIndex];
                toggleActualites(slide.getAttribute('data-year'));
            });
        } else {
            $('.webinarYear_prev').on('click', function(e) {
                let prevYear = $('.yearsList--current').find('li.active').prev('li').attr('data-year');
                scroll.scrollTo('.actus_year[data-year="' + prevYear + '"]', 1000, [0.90, 0.00, 0.00, 1.00]);
            });

            $('.webinarYear_next').on('click', function(e) {
                let nextYear = $('.yearsList--current').find('li.active').next('li').attr('data-year');
                scroll.scrollTo('.actus_year[data-year="' + nextYear + '"]', 1000, [0.90, 0.00, 0.00, 1.00]);
            });
        }
    }


    // ----------------------------------------------------------------------------------------
    // PAGE CONTACT ---------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    if ($('.officesCovers').length > 0){
        setTimeout(() => {
            $('.officesCovers').addClass('animated');
        }, 1500);

        let currentOffice = 1;
        let oldOffice = 2;
        let maxOffices = $('.office_title').length;
        let TL;

        const nextOffice = () => {
            if (TL && !TL.completed) return;

            oldOffice = currentOffice;
            currentOffice = (currentOffice == maxOffices) ? 1 : currentOffice + 1;

            TL = anime.timeline({
                easing: 'easeInOutExpo',
                duration: 1000,
                begin: () => {
                    $('.office_details[data-office="' + currentOffice + '"]').show();
                },
                complete: () => {
                    anime.set($('.office_title[data-office="' + oldOffice + '"]')[0], { translateX: 100 });
                    anime.set($('.office_nextTitle[data-office="' + currentOffice + '"]')[0], { translateX: 100 });
                    anime.set($('.office_details[data-office="' + oldOffice + '"]')[0], { translateX: 100 });
                    $('.office_details[data-office="' + oldOffice + '"]').hide();
                }
            });

            TL.add({ targets: $('.officeCover[data-office="' + oldOffice + '"]')[0], opacity: 0, scale: 1.1 }, 0);
            TL.add({ targets: $('.officeCover[data-office="' + currentOffice + '"]')[0], opacity: 1, scale: 1 }, 0);

            TL.add({ targets: $('.office_title[data-office="' + oldOffice + '"]')[0], opacity: 0, translateX: -100 }, 0);
            TL.add({ targets: $('.office_details[data-office="' + oldOffice + '"]')[0], opacity: 0, translateX: -100 }, 50);
            TL.add({ targets: $('.office_nextTitle[data-office="' + currentOffice + '"]')[0], opacity: 0, translateX: -100 }, 100);
            
            TL.add({ targets: $('.office_title[data-office="' + currentOffice + '"]')[0], opacity: 1, translateX: 0 }, 300);
            TL.add({ targets: $('.office_details[data-office="' + currentOffice + '"]')[0], opacity: 1, translateX: 0 }, 350);
            TL.add({ targets: $('.office_nextTitle[data-office="' + oldOffice + '"]')[0], opacity: 1, translateX: 0 }, 400);
        };

        $('.officesCarousel_next').on('click', (e) => {
            e.preventDefault();
            nextOffice();
        });

        anime.set($('.officeCover[data-office="' + currentOffice + '"]')[0], { scale: 1 });
        anime.set($('.officeCover[data-office="' + oldOffice + '"]')[0], { opacity: 0, scale: 1.1 });
        anime.set($('.office_title[data-office="' + oldOffice + '"]')[0], { opacity: 0, translateX: 100 });
        anime.set($('.office_details[data-office="' + oldOffice + '"]')[0], { opacity: 0, translateX: 100 });
        anime.set($('.office_nextTitle[data-office="' + currentOffice + '"]')[0], { opacity: 0, translateX: 100 });
        anime.set($('.office_nextTitle[data-office="' + oldOffice + '"]')[0], { opacity: 1 });
        $('.office_details[data-office="' + oldOffice + '"]').hide();
    }


    // ----------------------------------------------------------------------------------------
    // PRESTAS --------------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    $('.prestaList').on('mouseenter', function (e) {
       $('.video').addClass('hidden');
    });
    $('.prestaList').on('mouseleave', function (e) {
        $('.video').removeClass('hidden');
     });
    
    $('.prestaList').on('mousemove', function (e) {
        let offset = $(this).offset();
        let covers = $(this).find('.prestaCovers');
        anime.set(covers[0], {
            translateX: e.pageX - offset.left - ($(this).width() / 2),
            translateY: e.pageY - offset.top - ($(this).height() / 2),
        });
    });
    $('.prestaItem').on('mouseenter', function (e) {
        let itemId = $(this).attr('data-presta');
        $('.prestaCover[data-presta="' + itemId + '"').addClass('visible');
    });
    $('.prestaItem').on('mouseleave', function (e) {
        let itemId = $(this).attr('data-presta');
        $('.prestaCover[data-presta="' + itemId + '"').removeClass('visible');
    });


    // ----------------------------------------------------------------------------------------
    // NEWS POPIN -----------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    let popinPlayer;
    let originalUi;

    const openPopin = () => {
        scroll.stop();
        $('.popin').addClass('popin--opened');
        $('.anchors').hide();
        $('.menuToggle').addClass('menuToggle--dark');

        if (popinPlayer) { popinPlayer.stop(); }

        var TL = anime.timeline();
        TL.add({
            targets: document.querySelector('.popin_background'),
            duration: 400,
            easing: 'linear',
            opacity: [0, 1],
            complete: () => {
                cursor.hide();
                $('.popin').off('mouseenter');
                $('.popin').off('mouseleave');
                $('.popin').off('mousemove');
                $('.popin_content').off('mouseenter');
                $('.popin_content').off('mouseleave');

                cursor.show('popin');
                $('.popin').on('mouseenter', () => cursor.show('popin') );
                $('.popin').on('mouseleave', () => cursor.hide() );
                $('.popin').on('mousemove', (e) => { cursor.updatePos({ x : e.clientX, y : e.clientY }); });
                $('.popin_content').on('mouseenter', () => cursor.hide() );
                $('.popin_content').on('mouseleave', () => cursor.show('popin') );
            }
        }, 0);
        TL.add({
            targets: document.querySelector('.popin_close'),
            duration: 400,
            easing: 'linear',
            opacity: [0, 1]
        });
        TL.add({
            targets: document.querySelector('.popin_box'),
            duration: 800,
            easing: 'easeInOutExpo',
            opacity: [0, 1],
            translateY: ['20vh', 0]
        }, "-=700");
    };

    const closePopin = () => {
        if (popinPlayer) { popinPlayer.stop(); }
        $('.anchors').show();
        $('.menuToggle').removeClass('menuToggle--dark');
        $('html').attr('data-ui', originalUi);

        var TL = anime.timeline({
            complete: () => {
                $('.popin').removeClass('popin--opened');
                scroll.start();
                cursor.hide();
            }
        });
        TL.add({
            targets: document.querySelector('.popin_background'),
            duration: 200,
            easing: 'linear',
            opacity: [1, 0]
        }, 0);
        TL.add({
            targets: document.querySelector('.popin_close'),
            duration: 200,
            easing: 'linear',
            opacity: [1, 0]
        }, 0);
        TL.add({
            targets: document.querySelector('.popin_box'),
            duration: 400,
            easing: 'easeOutExpo',
            opacity: [1, 0],
            translateY: [0, '20vh']
        }, 0);
    };

    const initPopinLinks = () => {
        $('[data-news-id]').on('click', function (e){
            e.preventDefault();
            const newsId = $(this).attr('data-news-id');
            originalUi = $('html').attr('data-ui');
            setDarkUi();
            if (!$('.popin').hasClass('popin--opened')) {
                openPopin();
            }
            loadNews(newsId);
        });
    };

    const loadNews = (newsId) => {
        $('.popin_loading').addClass('popin_loading--visible');
        $('.popin_content').removeClass('popin_content--visible');
        $('.popin').get(0).scrollTop = 0;

        $.ajax({
            url: ajaxVars.url,
            type: 'get',
            data: {
                action: 'news_ajax',
                newsId: newsId
            },
            success: function (result) {
                $('.popin_content').html($(result).html());
                
                $('.popin_content').addClass('popin_content--visible');
                $('.popin_loading').removeClass('popin_loading--visible');

                popinPlayer = new Plyr('.pNews_video_player');

                if ($('.popin_content').find('.pNews_related').length > 0) {
                    new Swiper('.popin .relatedCarousel', {	
                        slidesPerView: 1,
                        spaceBetween: 0
                    });
                    
                    $('[data-news-id]').off('click');
                    initPopinLinks();

                    $('.relatedCarousel').off('mouseenter');
                    $('.relatedCarousel').off('mouseleave');
                    $('.relatedCarousel').off('mousemove');

                    $('.relatedCarousel').on('mouseenter', () => cursor.show('drag') );
                    $('.relatedCarousel').on('mouseleave', () => cursor.hide() );
                    $('.relatedCarousel').on('mousemove', (e) => { cursor.updatePos({ x : e.clientX, y : e.clientY }); });
                }
            },
            error: function (result) { console.log("ERROR", result); },
        });
    };

    initPopinLinks();


    $('.popin_background, .popin_close').on('click', function (e) {
        closePopin();
    });


    // ----------------------------------------------------------------------------------------
    // WEBINAIRE ------------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------
    if ($('.webinaire').length) {

        scroll.start();

        let TL = anime.timeline();

        TL.add({
            targets: '.webinaire_header',
            duration: 400,
            easing: "linear",
            opacity: [0, 1]
        }, 1600);
        
        TL.add({
            targets: '.webinaire_title .word',
            duration: 800,
            easing: "easeOutExpo",
            opacity: [0, 1],
            translateY: ['50%', 0],
            delay: anime.stagger(75)
        }, 2000);
        
        TL.add({
            targets: '.webinaire_content',
            duration: 400,
            easing: "linear",
            opacity: [0, 1]
        }, '-=600');
        
        TL.add({
            targets: '.webinaire_action',
            duration: 800,
            easing: "easeOutExpo",
            scale: [0, 1]
        }, '-=200');
    }

    if ($('.trailImg').length > 0) {
        new TrailEffect();
    }

    let isOpening = [];
    
    $('.webinaire_action').on('click', function(e) {
        e.preventDefault();
        let webinarId = $(this).attr('data-webinar');
        let webinarForm = $('.webinaire_form_content[data-webinar="' + webinarId + '"]').get(0);

        console.log(isOpening);
        

        if (webinarForm) {
            openWebinar(webinarId);
        } else {
            if (isOpening.includes(webinarId)) return;
            isOpening.push(webinarId);

            $.ajax({
                url: ajaxVars.url,
                type: 'get',
                data: {
                    action: 'webinar_ajax',
                    webinarId: webinarId
                },
                success: function (result) {
                    $('.webinaire_form').append($(result).html());
                    openWebinar(webinarId);
                    isOpening = [];
                },
                error: function (result) { console.log("ERROR", result); },
            });
        }

    });

    const openWebinar = (webinarId) => {
        let webinarForm = $('.webinaire_form_content[data-webinar="' + webinarId + '"]').get(0);
        if (webinarForm) {
            $('.webinaire_form').addClass('webinaire_form--opened');
            webinarForm.classList.add('active');
            let iframe = webinarForm.querySelector('iframe');

            if (iframe &&!iframe.hasAttribute('src') && iframe.hasAttribute('data-src')) {
                iframe.setAttribute('src', iframe.getAttribute('data-src'));
            }

            let Tl = anime.timeline();
            
            Tl.add({
                targets: '.webinaire_form_mask',
                duration: 400,
                easing: "linear",
                opacity: [0, 1]
            }, 0);

            Tl.add({
                targets: webinarForm,
                duration: 600,
                easing: "easeOutExpo",
                translateX: ["101%", "0%"],
                translateZ: 0
            }, 200);

            scroll.stop();
        }
    }

    let isClosing = false;
    $('.webinaire_form_mask').on('click', (e) => {
        e.preventDefault();

        if (isClosing) return;
        isClosing = true;

        let Tl = anime.timeline({
            complete: () => {
                isClosing = false;
                $('.webinaire_form').removeClass('webinaire_form--opened');
                document.querySelector('.webinaire_form_content.active').classList.remove('active');
                scroll.start();
            }
        });

        Tl.add({
            targets: '.webinaire_form_mask',
            duration: 400,
            easing: "linear",
            opacity: [1, 0]
        }, 0);

        Tl.add({
            targets: '.webinaire_form_content.active',
            duration: 600,
            easing: "easeOutExpo",
            translateX: ["0%", "101%"],
            translateZ: 0
        }, 0);
    });


    // // ----------------------------------------------------------------------------------------
    // // AUDIT ----------------------------------------------------------------------------------
    // // ----------------------------------------------------------------------------------------
    // if ($('.audit_iframe').length){
    //     setTimeout(() => {
    //         $('.audit_iframe').addClass('opened');
    //     }, 1000);
    // }

    // ----------------------------------------------------------------------------------------	
    // SERVICES -------------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------	
    if ($('body').hasClass('page-template-tpl-services')) {
        scroll.start();

        document.querySelectorAll('.services_list_item_link').forEach((link) => {
            link.addEventListener('click', () => {
                let serviceItem = link.closest('.services_list_item');
                let serviceId = serviceItem.getAttribute('data-service');
                let serviceBg = document.querySelector('.services_background[data-service="' + serviceId + '"]');
                let serviceMedia = document.querySelector('.services_media[data-service="' + serviceId + '"]');

                if (document.querySelector('.services_list_item--active')) {
                    document.querySelector('.services_list_item--active').classList.remove('services_list_item--active');
                }
                serviceItem.classList.add('services_list_item--active');

                if (document.querySelector('.services_background--active')) {
                    document.querySelector('.services_background--active').classList.remove('services_background--active');
                }
                if (serviceBg) {
                    serviceBg.classList.add('services_background--active');
                }

                if (document.querySelector('.services_media--active')) {
                    let lyt = document.querySelector('.services_media--active').querySelector('lite-youtube');
                    if (lyt) {
                        pauseVideo(lyt.getAttribute('data-player'));
                    }

                    document.querySelector('.services_media--active').classList.remove('services_media--active');
                }
                if (serviceMedia) {
                    serviceMedia.classList.add('services_media--active');
                    let lyt = serviceMedia.querySelector('lite-youtube');
                    if (lyt) {
                        playVideo(lyt.getAttribute('data-player'));
                    }
                }

                document.querySelector('.services_medias_inner').style.transform = 'translateY(' + (parseInt(serviceId) - 1) * -100  + '%)';
            });
        });

        document.querySelectorAll('.services_media').forEach((elt, index) => {
            let angle = index % 2 == 0 ? Utils.randomFloat(3,5) * -1 : Utils.randomFloat(3,5)
            elt.style.transform = 'rotate(' + angle  + 'deg)';
        });

        document.querySelectorAll('.services_list_item_button').forEach((link) => {
            link.addEventListener('click', () => {
                let serviceId = link.getAttribute('data-service');
                let serviceForm = document.querySelector('.services_form[data-service="' + serviceId + '"]');
    
                serviceForm.classList.add('services_form--active');
            });
        });

        document.querySelectorAll('.services_carousel_item').forEach((link) => {
            link.addEventListener('click', () => {
                let serviceId = link.getAttribute('data-service');
                let serviceForm = document.querySelector('.services_form[data-service="' + serviceId + '"]');
    
                if (document.querySelector('.services_form--active')) {
                    document.querySelector('.services_form--active').classList.remove('services_form--active')
                }
                serviceForm.classList.add('services_form--active');

                scroll.scrollTo(serviceForm);
            });
        });

        document.querySelectorAll('.services_form_close').forEach((link) => {
            link.addEventListener('click', () => {
                let serviceForm = link.closest('.services_form');
                serviceForm.classList.remove('services_form--active');
            });
        });

        document.querySelectorAll('.services_form').forEach((form) => {
            form.querySelector('.wpcf7-hidden[name="subject"]').value = form.getAttribute('data-subject');
        });

        new Swiper('.services_carousel', {	
            slidesPerView: 1,
            spaceBetween: WU.w.w * 0.06,
            pagination: {
              el: '.services_carousel .swiper-pagination'
            },
            navigation: {
              nextEl: '.swiper-button-next',
              prevEl: '.swiper-button-prev',
            },
            on: {
                slideChange: function (swiper) {
                    if (document.querySelector('.services_backgroundsMobile_item--active')){
                        document.querySelector('.services_backgroundsMobile_item--active').classList.remove('services_backgroundsMobile_item--active');
                    }
                    if (document.querySelector('.services_backgroundsMobile_item[data-service="' + (this.activeIndex + 1) + '"]')) {
                        document.querySelector('.services_backgroundsMobile_item[data-service="' + (this.activeIndex + 1) + '"]').classList.add('services_backgroundsMobile_item--active');
                    }

                    if (document.querySelector('.services_form--active')){
                        document.querySelector('.services_form--active').classList.remove('services_form--active');
                    }
                }
            }
        });

        window.addEventListener('resize', Utils.debounce(() => {
            WU.updateWindowH();
            WU.updateWindowW();
            WU.updateVh();
        }), { passive: true });
    }


    // ----------------------------------------------------------------------------------------	
    // HOME POPIN -----------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------	
    if ($('.hp_popinOpen').length > 0) {
        $('.hp_popinOpen').each(function(index, elt) {
            elt.addEventListener('click', () => {
                let popin = $('.hp_popin[data-popin="' + elt.getAttribute('data-popin') + '"]');
                popin.addClass('visible');
                if (plyrPlayers[popin.attr('data-player')]) {
                    plyrPlayers[popin.attr('data-player')].restart();
                    plyrPlayers[popin.attr('data-player')].play();
                }
                scroll.stop();
                setTimeout(() => {
                    cursor.hide();
                }, 500);
            })
        });
    }

    document.querySelectorAll('.hp_popin_close, .hp_popin_mask').forEach((elt) => {
        let popin = $(elt).closest('.hp_popin');
        elt.addEventListener('click', () => {
            popin.removeClass('visible');
            plyrPlayers[popin.attr('data-player')].pause();
            scroll.start();
        })
    })
    
    if ($('.hp_popin').length > 0) {
        $('.hp_popin').each(function(index, elt) {
            let player = new Plyr(elt.querySelector('.hp_popin_player'));
            elt.setAttribute('data-player', plyrPlayers.length)
            plyrPlayers.push(player);
        })
    }

    // ----------------------------------------------------------------------------------------	
    // RSE ------------------------------------------------------------------------------------
    // ----------------------------------------------------------------------------------------	
    if ($('.page-template-tpl-rse-parent .rse-light .carousel').length > 0) {
        $('.page-template-tpl-rse-parent .rse-light .carousel').each(function(index, elt) {
            new Carousel('.carousel-rse-' + $(elt).attr('data-id'), { interval: 5000 });
        })
    }

    if ($('.rse-video_render_player').length > 0) {
        $('.rse-video_render_player').each(function(index, elt) {
            elt.closest('.rse-video_render').setAttribute('data-player', plyrPlayers.length)
            plyrPlayers.push(new Plyr(elt));
        })
    }

    if ($('.rse-video_button').length > 0) {
        $('.rse-video_button').each(function(index, elt) {
            elt.addEventListener('click', () => {
                let render = document.querySelector(elt.getAttribute('data-render'));
                let vid = render.getAttribute('data-player');
                let player = plyrPlayers[vid];

                scroll.scrollTo(render, { offset: 0, duration: 800, easing: [0.90, 0.00, 0.00, 1.00], disableLerp: true });
                render.classList.add('-playing');
                player.play();
            })
        })
    }

    if ($('.rse-video_render_cover').length > 0) {
        $('.rse-video_render_cover').each(function(index, elt) {
            elt.addEventListener('click', () => {
                let render = elt.closest('.rse-video_render');
                let vid = render.getAttribute('data-player');
                let player = plyrPlayers[vid];

                scroll.scrollTo(render, { offset: 0, duration: 800, easing: [0.90, 0.00, 0.00, 1.00], disableLerp: true });
                render.classList.add('-playing');
                player.play();
            })
        })
    }

    if ($('.rse-audio_render_toggle').length > 0) {
        $('.rse-audio_render_toggle').each(function(index, elt) {
            elt.addEventListener('click', () => {
                let render = elt.closest('.rse-audio_render');
                let audio = render.querySelector('.rse-audio_render_audio');
                render.classList.toggle('-playing');
                audio.paused ? audio.play() : audio.pause();
            })
        });
    }
    

    if ($('.rse-carousel_swiper').length > 0) {
        $('.rse-carousel_swiper').each(function(index, elt) {
            new Swiper(elt, {	
                slidesPerView: 1,
                spaceBetween: 15,
                breakpoints: {
                    768: {
                        slidesPerView: 2,
                        spaceBetween: 40
                    }
                }
            });
        });
    }
    if ($('.rse-gallery_carousel_swiper').length > 0) {
        $('.rse-gallery_carousel_swiper').each(function(index, elt) {
            new Swiper(elt, {	
                slidesPerView: 1,
                spaceBetween: 15,
                breakpoints: {
                    768: {
                        slidesPerView: 2,
                        spaceBetween: 40
                    }
                }
            });
        });
    }

    // Force scroll update whan RSE gallery is on the page
    if ($('.rse-gallery').length > 0) {
        setTimeout(() => {
            scroll.update();
        }, 1000);
        setTimeout(() => {
            scroll.update();
        }, 5000);
        setTimeout(() => {
            scroll.update();
        }, 7000);
        setTimeout(() => {
            scroll.update();
        }, 10000);
    }

};


const setDarkUi = () => {
    $('html').attr('data-ui', 'dark');
}

const setLightUi = () => {
    $('html').attr('data-ui', 'light');
}

const toggleMaskVideo = (way) => {
    if (way === 'enter') {
        $('.video').addClass('video--masked');
    } else {
        $('.video').removeClass('video--masked');
    }
}

const toggleGreyscaleVideo = (way) => {
    if (way === 'enter') {
        $('.video').addClass('video--greyscale');
    } else {
        $('.video').removeClass('video--greyscale');
    }
}

const togglePlayVideo = (way) => {
    if (way === 'enter') {
        document.getElementById('homeVideo').play();
    } else {
        document.getElementById('homeVideo').pause();
    }
}

const getYearIndex = (year) => {
    return $('.yearsList--current').find('li[data-year="' + year + '"]').index();
};

const slideYears = (container, pct) => {
    anime.set(container, { translateY: pct * -100 + "%", });
};

const sectionTitleAnimation = (TL, parent, delay = 0) => {                
    if (parent.querySelector('.sectionTitle_header')) {
        TL.add({
            targets: parent.querySelector('.sectionTitle_header_content_separator'),
            duration: 800,
            easing: 'easeInOutExpo',
            scaleX: [0, 1],
            delay: delay
        });
        TL.add({
            targets: parent.querySelector('.sectionTitle_header_content_title'),
            duration: 600,
            easing: 'linear',
            opacity: [0, 1]
        }, '-=500');
        
        TL.add({
            targets: parent.querySelector('.sectionTitle_header_additional'),
            duration: 600,
            easing: 'linear',
            opacity: [0, 1],
        }, '-=300');
    }

    if (parent.querySelector('.sectionTitle_footer')) {
        TL.add({
            targets: parent.querySelector('.sectionTitle_footer_separator'),
            duration: 800,
            easing: 'easeInOutExpo',
            scaleX: [0, 1]
        }, '-=1100');

        if (parent.querySelector('.sectionTitle_footer_link')) {
            TL.add({
                targets: parent.querySelector('.sectionTitle_footer_link'),
                duration: 600,
                easing: 'linear',
                opacity: [0, 1],
                complete: () => {
                    parent.querySelector('.sectionTitle_footer_link').classList.add('sectionTitle_footer_link--pulse');
                    setTimeout(() => {
                        parent.querySelector('.sectionTitle_footer_link').classList.remove('sectionTitle_footer_link--pulse');
                    }, 1500);
                }
            }, '-=450');
        }
    }

    TL.add({
        targets: parent.querySelector('.sectionTitle_content'),
        duration: 1200,
        easing: 'easeOutExpo',
        translateY: ['-25%', 0],
        opacity: [0, 1],
    }, '-=700');

    if (parent.querySelector('.sectionQuote')) {
        TL.add({
            targets: parent.querySelector('.sectionQuote'),
            duration: 1200,
            easing: 'easeOutExpo',
            translateY: ['-15%', 0],
            opacity: [0, 1],
        }, '-=1000');
    }

    if (parent.querySelector('.office_detailsWrapper')) {	
        TL.add({	
            targets: parent.querySelector('.office_detailsWrapper'),	
            duration: 600,	
            opacity: [0, 1],	
            easing: 'linear'	
        }, '-=600');	
    }

    if (parent.querySelector('.header_download')) {
        TL.add({
            targets: parent.querySelector('.header_download'),
            duration: 600,
            easing: 'linear',
            opacity: [0, 1],
        }, '-=1000');
    }
}


const createScroll = (container) => {
    scroll = new LocomotiveScroll({
        el: container.querySelector('[data-scroll-container]'),
        smooth: true,
        getSpeed: true,
        getDirection: true,
        useKeyboard: true,
        tablet: {
            smooth: true,
            direction: 'vertical',
            gestureDirection: 'vertical',
            breakpoint: $('body').hasClass('page-template-tpl-services') ? 1024 : 768
        }
    });
    scroll.stop();

    if (!WU.isXS()) {
        scroll.on('scroll', (instance) => {
            const progress = instance.scroll.y / instance.limit;
            $('.pageProgress').css('transform', 'scaleX(' + progress + ')');
            document.documentElement.setAttribute('data-direction', instance.direction)

            if (typeof instance.currentElements['intro'] === 'object') {
                let data = instance.currentElements['intro'];
                let progress = data.progress;
                let cover = document.querySelector('.intro_cover_inner');
                let coverScale = 0.16667;
                let coverDistance = 1 - coverScale;
                
                // Title border
                if (progress > 0.035) {
                    document.querySelector('.intro_titleBorder').classList.remove('visible');
                } else {
                    document.querySelector('.intro_titleBorder').classList.add('visible');
                }

                // Title
                if (progress > 0.65) {
                    document.querySelector('.intro_title').classList.remove('intro_title--light');
                } else {
                    document.querySelector('.intro_title').classList.add('intro_title--light');
                }
                
                // Content
                if (progress > 0.75) {
                    document.querySelector('.intro_content').classList.add('visible');
                    // Show popin button
                } else {
                    document.querySelector('.intro_content').classList.remove('visible');
                    // Hide popin button
                }
                
                
                anime.set(cover, {
                    scale: 1 - (progress * coverDistance),
                    filter: 'grayscale(' + progress + ')'
                });

                let title = document.querySelector('.intro_title');
                let titleScale = 0.4;
                let titleDistance = 1 - titleScale;

                anime.set(title, {
                    scale: (progress * titleDistance) + titleScale,
                });
            }

            if (typeof instance.currentElements['webiNB'] === 'object') {
                let data = instance.currentElements['webiNB'];
                let progress = data.progress;
                let cover = document.querySelector('.hp_webi_cover_media');
                cover.style.filter = 'grayscale(' + (1 - progress) + ')';
            }
        });
    }

    scroll.on('call', (value, way, obj) => {
        if (WU.isXS()) return;
        
        let calls = (typeof value === 'string') ? [value] : value;
        
        calls.forEach(call => {
            if (call === 'detectSection' && way === 'enter') {
                // ACTIVE ANCHOR
                $('.anchors').find('a.active').removeClass('active');
                $('.anchors').find('a[href="#' + obj.el.getAttribute('id') + '"]').addClass('active');

                // UI COLOR
                if (obj.el.getAttribute('data-ui') === 'dark') {
                    setDarkUi();
                } else if (obj.el.getAttribute('data-ui') === 'light') {
                    setLightUi();
                }
            }
            
            else if (call === 'setUi' && way === 'enter') {
                // UI COLOR
                if (obj.el.getAttribute('data-ui') === 'dark') {
                    setDarkUi();
                } else if (obj.el.getAttribute('data-ui') === 'light') {
                    setLightUi();
                }
            }

            else if (call === 'maskVideo') {
                toggleMaskVideo(way);
            }

            else if (call === 'playVideo') {
                togglePlayVideo(way);
            }

            else if (call === 'greyscaleVideo') {
                toggleGreyscaleVideo(way);
            }

            else if (call === 'updateMember' && way === 'enter') {
                let memberId = obj.el.getAttribute('data-member');

                if (memberId === 'team') {
                    $('.cabinet_team').find('.member_link.active').removeClass('active');
                    $('.cabinet_team').find('.member_picture.active').removeClass('active');
                    $('.cabinet_team').find('.member_external').hide();
                    $('.sectionTitle--members').removeClass('sectionTitle--light');
                } else {
                    $('.cabinet_team').find('.member_link.active').removeClass('active');
                    $('.cabinet_team').find('.member_link[data-member="' + memberId + '"]').addClass('active');
                
                    $('.cabinet_team').find('.member_picture.active').removeClass('active');
                    $('.cabinet_team').find('.member_picture[data-member="' + memberId + '"]').addClass('active');
                
                    $('.cabinet_team').find('.member_external').hide();
                    $('.cabinet_team').find('.member_external[data-member="' + memberId + '"]').show();

                    $('.sectionTitle--members').addClass('sectionTitle--light');
                }
            }
            
            else if (call === 'showMember' && way === 'enter') {
                if (obj.el.getAttribute('data-animated') === 'true') return;
                obj.el.setAttribute('data-animated', true);

                anime({
                    targets: obj.el,
                    duration: 600,
                    easing: 'linear',
                    opacity: [0,1]
                });
            }

            else if (call === 'detectYear' && way === 'enter') {
                let currentYear = obj.el.getAttribute('data-year');
                
                let currentYearIndex = getYearIndex(currentYear);
                let nbYears = $('.yearsList--current').find('li').length;
                slideYears($('.yearsList--current').get(0), currentYearIndex / nbYears)

                let prevYearIndex = (currentYearIndex == nbYears - 1) ? 0 : currentYearIndex + 1;
                slideYears($('.yearsList--prev').get(0), prevYearIndex / nbYears);
            }

            else if (call === 'detectYearWebinar' && way === 'enter') {
                let currentYear = obj.el.getAttribute('data-year');
                
                let currentYearIndex = getYearIndex(currentYear);
                let nbYears = $('.yearsList--current').find('li').length;
                slideYears($('.yearsList--current').get(0), currentYearIndex / nbYears)
                $('.yearsList--current').find('li.active').removeClass('active');
                $('.yearsList--current').find('li[data-year="' + currentYear + '"').addClass('active');
            }

            else if (call === 'showNumber' && way === 'enter') {
                $(obj.el).addClass('active');
            }
            
            else if (call === 'splitQuote' && way === 'enter') {
                anime({
                    targets: obj.el.querySelectorAll('.word'),
                    duration: 500,
                    easing: "linear",
                    opacity: 1,
                    delay: anime.stagger(75)
                });
            }

            else if (call === 'animateTeam' && way === 'enter') {
                if (obj.el.getAttribute('data-animated') === 'true') return;
                obj.el.setAttribute('data-animated', true);

                anime({
                    targets: '.team_picture',
                    duration: 1200,
                    easing: 'easeOutExpo',
                    translateY: ['100vh', 0],
                    translateZ: 0,
                    delay: anime.stagger(100)
                });
                anime.set('.team_picture', { opacity : 1 });
            }

            else if (call === 'foldTeam') {
                let items = document.querySelectorAll('.team_picture');

                if (way == 'enter') {
                    items.forEach((item, index) => {
                        if (index > 0){
                            $(item).addClass('greyscale');
                        }

                        anime({
                            targets: item,
                            duration: 800,
                            easing: 'easeOutExpo',
                            left: 7.93 * index + "%",
                            delay: 50 * index
                        });
                    });
                } else {
                    if (document.documentElement.getAttribute('data-direction') === 'up') {
                        items.forEach((item, index) => {
                            $(item).removeClass('greyscale');
                            anime({
                                targets: item,
                                duration: 800,
                                easing: 'easeOutExpo',
                                left: (70 / (items.length - 1)) * index + "%",
                                delay: 75 * (items.length - index)
                            });
                        });
                    }
                }

            }

            else if (call === 'hpIntro' && way === 'enter') {
                if (obj.el.getAttribute('data-animated') === 'true') return;
                obj.el.setAttribute('data-animated', true);

                scroll.start();
            }

            // else if (call === 'hpHeader' && way === 'enter') {
            //     if (obj.el.getAttribute('data-animated') === 'true') return;
            //     obj.el.setAttribute('data-animated', true);

            //     scroll.start();

            //     var TL = anime.timeline();
                
            //     TL.add({
            //         targets: document.querySelector('.hp_header .sectionTitle_content'),
            //         duration: 800,
            //         easing: 'linear',
            //         opacity: [0, 1],
            //         delay: loaded ? 1300 : 2200
            //     });
            //     TL.add({
            //         targets: document.querySelector('.hp_header .sectionTitle_footer_separator'),
            //         duration: 800,
            //         easing: 'easeInOutExpo',
            //         scaleX: [0, 1]
            //     }, "-=600");
            //     TL.add({
            //         targets: document.querySelector('.hp_header .sectionTitle_footer_link'),
            //         duration: 600,
            //         easing: 'linear',
            //         opacity: [0, 1],
            //         complete: () => {
            //             document.querySelector('.hp_header .sectionTitle_footer_link').classList.add('sectionTitle_footer_link--pulse');
            //             setTimeout(() => {
            //                 document.querySelector('.hp_header .sectionTitle_footer_link').classList.remove('sectionTitle_footer_link--pulse');
            //             }, 1500);
            //         }
            //     }, "-=300");
            // }

            else if (call === 'hpNewsCarousel' && way === 'enter') {
                if (obj.el.getAttribute('data-animated') === 'true') return;
                obj.el.setAttribute('data-animated', true);

                anime({
                    targets: obj.el,
                    duration: 1000,
                    easing: 'linear',
                    opacity: [0, 1]
                });
            }

            else if (call === 'hpNews' && way === 'enter') {
                if (obj.el.getAttribute('data-animated') === 'true') return;

                obj.el.setAttribute('data-animated', true);

                var TL = anime.timeline();

                TL.add({
                    targets: document.querySelector('.hp_news .contentBg'),
                    duration: 1400,
                    easing: 'easeInOutExpo',
                    translateX: ['101%', '0%']
                });

                TL.add({
                    targets: document.querySelectorAll('.hp_news .newsBloc'),
                    duration: 1200,
                    easing: 'easeOutExpo',
                    translateY: [50, 0],
                    opacity: [0, 1],
                    delay: anime.stagger(200),
                    complete: () => {
                        document.querySelector('.hp_news_list').classList.add('hp_news_list--active');
                    }
                }, "-=100");

                TL.add({
                    targets: document.querySelector('.hp_news .hp_news_logo'),
                    duration: 1000,
                    easing: 'linear',
                    opacity: [0, 1],
                }, 1000);
            }

            else if (call === 'publicationsCabinet' && way === 'enter') {
                if (obj.el.getAttribute('data-animated') === 'true') return;
                obj.el.setAttribute('data-animated', true);

                anime({
                    targets: obj.el.querySelectorAll('.publicationBloc'),
                    duration: 1200,
                    easing: 'easeOutExpo',
                    translateY: ['100%', 0],
                    translateZ: 0,
                    opacity: [0, 1],
                    delay: anime.stagger(100)
                });
            }

            else if (call === 'sectionTitle' && way === 'enter') {
                if (obj.el.getAttribute('data-animated') === 'true') return;
                obj.el.setAttribute('data-animated', true);

                let delay = obj.el.getAttribute('data-delay') || 0;
                var TL = anime.timeline();

                sectionTitleAnimation(TL, obj.el, delay);
            }

            else if (call === 'counter' && way === 'enter') {
                if (obj.el.getAttribute('data-animated') === 'true') return;
                obj.el.setAttribute('data-animated', true);

                let value = parseInt(obj.el.getAttribute('data-value').replace(' ', ''));
                let maxValue = value < 100 ? value : 100;
                let step = value >= 100 ? value/100 : 1;
                for (let index = 1; index <= maxValue; index++) {
                    setTimeout(() => {
                        $(obj.el).html(Math.round(step * index));
                    }, index * 12);
                }
            }

            else if (call === 'pageHeader' && way === 'enter') {
                let parent = $(obj.el).parent().get(0);

                if (parent.getAttribute('data-animated') === 'true') return;
                parent.setAttribute('data-animated', true);

                var TL = anime.timeline();

                if (parent.classList.contains('header--withCover')) {
                    TL.add({
                        targets: parent,
                        opacity: 1,
                        delay: loaded ? 1300 : 2500,
                        duration: 0,
                        complete: () => {
                            scroll.update();
                            $(parent).addClass('animated');
                        }
                    });
                    TL.add({
                        targets: parent,
                        opacity: 1,
                        delay: 400,
                        duration: 0,
                        complete: () => {
                            if (!$(parent).attr('data-section-color-force')) {
                                setDarkUi();
                                $(parent).addClass('animated');
                                $(parent).find('[data-ui]').attr('data-ui', 'dark');
                                $(parent).find('.sectionTitle').removeClass('sectionTitle--light');
                            }
                            scroll.update();
                            scroll.start();
                        }
                    });
                }

                sectionTitleAnimation(TL,parent);
            }

            else if (call === 'prestaAnim' && way === 'enter') {
                if (obj.el.getAttribute('data-animated') === 'true') return;
                obj.el.setAttribute('data-animated', true);
                
                let presta = obj.el;
                var TL = anime.timeline();
                
                TL.add({
                    targets: presta.querySelectorAll('.presta_cover'),
                    duration: 800,
                    easing: 'easeInOutExpo',
                    translateY: [100, 0],
                    translateZ: 0,
                    opacity: [0, 1]
                });
                TL.add({
                    targets: presta.querySelectorAll('.presta_content'),
                    duration: 800,
                    easing: 'easeInOutExpo',
                    translateY: [100, 0],
                    translateZ: 0,
                    opacity: [0, 1]
                }, '-=600');
            }

            else if (call === 'rseVideoSection') {
                let vid = obj.el.getAttribute('data-player');

                if (way == 'exit') {
                    plyrPlayers[vid].pause();
                    obj.el.classList.remove('-playing');
                }
            }

            else if (call === 'rseAudioSection') {
                let audio = obj.el.querySelector('.rse-audio_render_audio');

                if (way == 'exit') {
                    audio.pause();
                    obj.el.querySelector('.rse-audio_render').classList.remove('-playing');
                }
            }

            else if (call === 'rseCarousel' && way === 'enter') {
                if (obj.el.getAttribute('data-animated') === 'true') return;
                obj.el.setAttribute('data-animated', true);

                anime({
                    targets: obj.el.querySelectorAll('.rse-carousel_swiper_slide'),
                    duration: 1200,
                    easing: 'easeOutExpo',
                    translateY: ['100%', 0],
                    translateZ: 0,
                    opacity: [0, 1],
                    delay: anime.stagger(100)
                });
            }
        });
    });

    return scroll;
};

const togglePodcast = () => {
    let player = $('.podcastPlayer');
    if (player.hasClass('podcastPlayer--playing')) {
        pausePodcast();
    } else {
        playPodcast();
    }
}

const playPodcast = () => {
    let player = $('.podcastPlayer');
    let audio = $('.podcastPlayer_audio').get(0);
    if (audio) {
        audio.play();
        player.addClass('podcastPlayer--playing');
    }
};

const pausePodcast = () => {
    let player = $('.podcastPlayer');
    let audio = $('.podcastPlayer_audio').get(0);
    if (audio) {
        audio.pause();
        player.removeClass('podcastPlayer--playing');
    }
};

const initPodcastPlayer = () => {
    if ($('.podcastPlayer').length > 0) {
        let player = $('.podcastPlayer');
        let audio = $('.podcastPlayer_audio').get(0);
        let toggle = $('.podcastPlayer_toggle');
        let progressBar = $('.podcastPlayer_progressBar_bar').get(0);
        let timer = $('.podcastPlayer_time').get(0);

        toggle.on('click', (e) => {
            e.preventDefault();
            togglePodcast();
        });

        audio.addEventListener("timeupdate", function() {
            let duration = parseInt( audio.duration ),
                currentTime = parseInt( audio.currentTime ),
                timeLeft = duration - currentTime,
                s, m;

            let r = parseInt(progressBar.getAttribute('r'));
            let c = Math.PI * 2 * r;
            progressBar.removeAttribute('style');

            const progress = currentTime / duration;
            let pct = Math.round(c - (progress * c));
            progressBar.style.strokeDashoffset = pct + "px";

            s = timeLeft % 60;
            m = Math.floor( timeLeft / 60 ) % 60;
            
            s = s < 10 ? "0" + s : s;
            m = m < 10 ? "0" + m : m;
            
            timer.innerHTML = m + ":" + s;

            if (!$('.podcastWrap').hasClass('podcastWrap--playing')) {
                $('.podcastWrap').addClass('podcastWrap--playing');
            }

        }, false);

        audio.addEventListener("play", function() {
            if ($('.podcastWrap')) {
                $('.podcastWrap').addClass('podcastWrap--playing');
            }
        });
        audio.addEventListener("pause", function() {
            if ($('.podcastWrap')) {
                $('.podcastWrap').removeClass('podcastWrap--playing');
            }
        });

        audio.addEventListener("ended", function(){
            audio.currentTime = 0;
            audio.pause();
            player.removeClass('podcastPlayer--playing');
       });
    }
}

(function() {
    new PageTransition(initPage, createScroll);

    initPodcastPlayer();
})();