document.addEventListener('DOMContentLoaded', function () {
    'use strict';

    // sets and progress bar lenght as page is being scrolled

	const progressBar = document.querySelector('.show-progress .scroll-progress');
	const header = document.querySelector('header');
	var posts = document.querySelectorAll('.post-content');
    const showScrollProgress = document.querySelector('.show-progress');

    function updateProgressBar() {
        posts.forEach(function (post) {
            const artLength = post.offsetHeight;
            const artStartPos = getElementOffset(post, 'offsetTop');
            const artEndPos = artStartPos + artLength;
            const changePoint = document.documentElement.scrollTop + window.innerHeight - header.offsetHeight;

            if (showScrollProgress && artEndPos > changePoint - 30 && artStartPos < changePoint) {

                var passed = changePoint - artStartPos,
                    percentPassed = parseFloat(passed / artLength * 100);

                if (percentPassed > 100) {
                    percentPassed = 100;
                }
                progressBar.style.width = percentPassed + "%";
            }
        });
    }

	if (progressBar) {
		window.addEventListener('scroll', function() {
			updateProgressBar();
		});
		document.addEventListener('related-post-loaded', function () {
			posts = document.querySelectorAll('.post-content');
		});
	}

    const postEnds = document.querySelectorAll('.post-end');
    if (postEnds && !!window.IntersectionObserver) {

		const postEndObserver = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                if (entry.isIntersecting || entry.boundingClientRect.y < 0) {
                    const progressBar = document.querySelector('.show-progress .scroll-progress');
                    var percentPassed = 100;
                    progressBar.style.width = percentPassed + "%";
                }
            })
        });
        postEnds.forEach(function (postEnd) {
            postEndObserver.observe(postEnd);
        });
    }
});