/**
 * Animate scroll
 * Thanks to Dalton Walsch https://daltonwalsh.com/blog/using-the-intersection-observer/
 */

function initAnimateScroll() {
    const scrollElements           = document.querySelectorAll(".js-scroll");
    let scrollElementsFromSettings = [];

    if (QUI_ANIMATE_SCROLL_EFFECTS) {
        scrollElementsFromSettings = parseSelectorsFromSettings(QUI_ANIMATE_SCROLL_EFFECTS);
    }

    const allElements = Array.from(scrollElements).concat(scrollElementsFromSettings);

    function parseSelectorsFromSettings(SelectorObj) {
        const selectors = [];

        if (typeof SelectorObj !== 'object') {
            return selectors;
        }

        let elmsBottom = [],
            elmsLeft   = [],
            elmsRight  = [];

        if (SelectorObj.bottom) {
            elmsBottom = document.querySelectorAll(SelectorObj.bottom);

            elmsBottom.forEach((Elm) => {
                Elm.classList.add('js-scroll');
                Elm.classList.add('fade-in-bottom');
            });
        }

        if (SelectorObj.left) {
            elmsLeft = document.querySelectorAll(SelectorObj.left);

            elmsLeft.forEach((Elm) => {
                Elm.classList.add('js-scroll');
                Elm.classList.add('slide-left');
            });
        }

        if (SelectorObj.right) {
            elmsRight = document.querySelectorAll(SelectorObj.right);

            elmsRight.forEach((Elm) => {
                Elm.classList.add('js-scroll');
                Elm.classList.add('slide-right');
            });
        }

        return selectors.concat(Array.from(elmsBottom), Array.from(elmsLeft), Array.from(elmsRight));
    }

    const options = {
        root      : null, // relative to document viewport
        rootMargin: '0px', // margin around root. Values are similar to css property. Unitless values not allowed
        threshold : 0.7 // visible amount of item shown in relation to root
    };

    const observerCallback = function (entries) {
        entries.forEach((entry) => {
            if (entry.isIntersecting) {
                entry.target.classList.add('scrolled');
                Observer.unobserve(entry.target);
            }
        });
    };

    const Observer = new IntersectionObserver(observerCallback, options);

    allElements.forEach((Elm) => {
        Observer.observe(Elm);
    });

}

if (document.readyState === 'loading') {
    document.addEventListener("DOMContentLoaded", initAnimateScroll);
} else {
    initAnimateScroll();
}