// Create Element.remove() function if not exist
if (!('remove' in Element.prototype)) {
    Element.prototype.remove = function () {
        if (this.parentNode) {
            this.parentNode.removeChild(this);
        }
    };
}

$(function () {

    let parallax = skrollr.init({
        forceHeight: false
    });

    if (parallax.isMobile()) {
        parallax.destroy();
    }

    window.sr = ScrollReveal();

    sr.reveal('.reveal', {
        reset: true
    });

    lightbox.option({
        'resizeDuration': 100,
        'wrapAround': true
    });
});

// Navigation.
(() => {
    const toggle = document.querySelector('.primary-header__nav-toggle');
    const expandable = Array.from(document.querySelectorAll('.primary-header__nav__container > ul > li > ul'));
    const measure = (list) => {
        let height = 0;
        Array.from(list.children).forEach((el) => height += el.getBoundingClientRect().height);
        list.style.setProperty('--height', height + 'px');
    };
    const resize = () => expandable.forEach((list) => measure(list))
    toggle.addEventListener('click', (e) => {
        e.preventDefault();
        window.scrollTo(0, 0);
        document.querySelector('html').classList.toggle('menu-open');
    });
    expandable.forEach((list) => {
        list.previousElementSibling.addEventListener('click', (e) => {
            e.preventDefault();
            if (window.innerWidth >= 1200) {
                return;
            }
            resize();
            list.classList.toggle('--open');
            const close = expandable.filter((l) => l !== list && l.classList.contains('--open'));
            close.forEach((l) => l.classList.remove('--open'));
        });
    });
    window.addEventListener("resize", () => {
        clearTimeout(window['navigationResizeTimeout']);
        window['navigationResizeTimeout'] = setTimeout(() => {
            resize();
        }, 250);
    });
    setTimeout(() => resize(), 500);
})();

// splide.
(() => {
    const resize = () => {
        document.querySelectorAll('.splide').forEach((el) => {
            if (el.splideInstance) el.splideInstance.destroy();
            el.splideInstance = new Splide(el);
            el.splideInstance.mount();
        });
    };
    window.addEventListener("resize", () => {
        clearTimeout(window['splideResizeTimeout']);
        window['splideResizeTimeout'] = setTimeout(() => {
            resize();
        }, 250);
    });
    resize();
})();

// testimonials.
(() => {
    const elms = document.querySelectorAll('article.testimonials');
    if (!elms.length) return;
    // Shuffle the testimonials.
    elms.forEach((elm) => {
        const testimonials = elm.querySelectorAll('.testimonials__list__item');
        const shuffled = Array.from(testimonials).sort(() => Math.random() - 0.5);
        const container = elm.querySelector('.testimonials__list');
        container.innerHTML = '';
        shuffled.forEach((testimonial) => {
            container.appendChild(testimonial);
        });
    });
    const resize = () => {
        elms.forEach((el) => {
            const containerBottom = el.querySelector('.testimonials__container').getBoundingClientRect().bottom;
            const imageBottom = el.querySelector('.testimonials__image__container').getBoundingClientRect().bottom;
            offset = Math.max(imageBottom - containerBottom, 48);
            margin = 48;
            if (window.innerWidth < 992) {
                offset = offset / 2;
                margin += offset;
            }
            el.style.paddingBottom = offset + 'px';
            el.style.marginBottom = margin + 'px';
        });
    };
    window.addEventListener("resize", () => {
        clearTimeout(window['testimonialsResizeTimeout']);
        window['testimonialsResizeTimeout'] = setTimeout(() => {
            resize();
        }, 250);
    });
    resize();
})();

// Global Notices.
(() => {
    const notices = document.querySelectorAll('article.notices-global');
    const closers = document.querySelectorAll('article.notices-global .notices-global__dismiss');
    if (!notices.length) return;
    const generateHash = (string) => {
        const polynomial = 0xEDB88320;
        let crc = 0xFFFFFFFF;
        for (let i = 0; i < string.length; i++) {
            crc ^= string.charCodeAt(i);
            for (let j = 0; j < 8; j++) {
                crc = (crc >>> 1) ^ (crc & 1 ? polynomial : 0);
            }
        }
        return crc ^ 0xFFFFFFFF;
    };
    const setCookie = (cname, cvalue, exdays) => {
        const d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        let expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
    };
    const getCookie = (cname) => {
        let name = cname + "=";
        let decodedCookie = decodeURIComponent(document.cookie);
        let ca = decodedCookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    };
    const resize = () => {
        notices.forEach((notice) => {
            const container = notice.querySelector('.notices-global__container');
            const height = container.getBoundingClientRect().height;
            notice.style.height = height + 'px';
            setTimeout(() => notice.classList.add('loaded'), 1500);
        });
    };
    closers.forEach((closer) => {
        const notice = closer.closest('.notices-global');
        const hash = generateHash(notice.innerHTML);
        if (getCookie('notice_' + hash)) {
            notice.remove();
            return;
        }
        closer.addEventListener('click', (e) => {
            e.preventDefault();
            setCookie('notice_' + hash, 'dismissed', notice.dataset.dismissable);
            notice.remove();
        });
    });
    window.addEventListener("resize", () => {
        clearTimeout(window['noticesResizeTimeout']);
        window['noticesResizeTimeout'] = setTimeout(() => {
            resize();
        }, 250);
    });
    setTimeout(() => resize(), 500);
})();