(function() {

    let scrollStep = 0.5;
    let delay = 120;
    let pause = false;

    if ('scrollRestoration' in history) {
        history.scrollRestoration = 'manual';
    }

    document.addEventListener('mouseover', () => pause = true);
    document.addEventListener('mouseout', () => pause = false);

    let scrolling = setInterval(() => {
        if (pause) return;

        window.scrollBy(0, scrollStep);

        if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 2) {
            clearInterval(scrolling);

            setTimeout(() => {
                goToNextPost();
            }, 3000);
        }

    }, delay);

    function goToNextPost() {
        let nextLink = document.querySelector('a[rel="next"], .nav-next a, .next-post a');

        if (nextLink && nextLink.href) {
            window.location.href = nextLink.href + "#top";
        } else {
            sessionStorage.setItem("forceTop", "true");
            location.reload(true);
        }
    }

    window.addEventListener("load", () => {
        if (sessionStorage.getItem("forceTop") === "true") {
            window.scrollTo(0, 0);
            sessionStorage.removeItem("forceTop");
        }
    });

})();
