// load more posts button
var $ = jQuery.noConflict();
$(".load-posts").each(function (ignore, element) {
    'use strict';

	var postlist = $(element),
        nav = $(".navigation.pagination"),
        lastScrollTop = 0;

    postlist.loading = false;
    postlist.initURL = window.location.href;

	var markers = document.querySelectorAll('.page-marker');

	if (!!window.IntersectionObserver) {
		const pageMarkerObserver = new IntersectionObserver(function (entries) {
			if (postlist.loading) {
				return;
			}
			entries.forEach(function(marker, index) {
				if (marker.isIntersecting) {
					var permalink = marker.target.dataset.permalink;
					window.history.pushState({}, "", permalink);
				} else if (marker.boundingClientRect.top > 0) {
					var index = Array.prototype.indexOf.call(markers, marker.target);
					var url = index > 0 ? markers[index - 1].dataset.permalink : postlist.initURL;

					if (url) {
						window.history.pushState({}, '', url);
					}
				}
			});
		});

		window.addEventListener('pagination-loaded', function () {
			markers = document.querySelectorAll('.page-marker');
			markers.forEach(function(marker) {
				pageMarkerObserver.observe(marker);
			});
		});
	}

    function loadPosts(url, target) {
        $.ajax({
            url: url,
            dataType: "html",
            success: function (response) {

				const markup = $(response).find(".load-posts");
				markup.find('.single.page').remove();
				const postsMarkup = markup.find(".post, .item, .page, .portfolio-item, .post-list-item");
				const navMarkup = $(response).find(".navigation.pagination").html();

                $(".loader").remove();
				$(".load-more-posts .loading").remove();

                if (target.hasClass("masonry")) {
                    target.masonry({
                        columnWidth: '.brick',
                        itemSelector: '.brick, .page-marker',
                        stamp: '.filters, .navigation.pagination, h1',
                        containerStyle: null
                    });

                    var marker = $('<div class="page-marker" data-permalink="' + url + '"></div>');
                    target.append(marker).masonry('appended', marker).masonry();

                    postsMarkup.imagesLoaded(function () {
						postsMarkup.each(function (ignore, element) {
							var item = $(element);
							target.append(item).masonry('appended', item).masonry();
						});
                    });
                } else {
                    target.append('<div class="page-marker" data-permalink="' + url + '"></div>');
                    target.append(postsMarkup);
                }

                nav.html(navMarkup);

                target.loading = false;

                var nextPageUrl = nav.find(".current + a").attr("href");
                if (!nextPageUrl && $(".load-more-posts").length) {
                    $(".load-more-posts").hide();
                }

				window.dispatchEvent(new CustomEvent('pagination-loaded'));
            }
        });
    }

    if (postlist.hasClass('load-posts-auto')) {
		const postListEl = document.querySelector('.load-posts-auto');
		if (postListEl && !!window.IntersectionObserver) {
			const postlistObserver = new IntersectionObserver(function (entries) {
				entries.forEach(function (entry) {
					if (entry.isIntersecting && !postlist.loading) {

						var nextPageUrl = nav.find('.current + a').attr('href');
						if (nextPageUrl) {
							postlist.loading = true;
							nav.before('<div class="loader"><i class="m-icon m-icon-spinner m-spin"> </i></div>');
							loadPosts(nextPageUrl, postlist);
						}
					}
				});
			});

			const postlistEnd = document.querySelector('.pagination');
			if (postlistEnd) {
				postlistObserver.observe(postlistEnd);
			}
		}
    } else {
        $(".load-more-posts").on("click", function (event) {
            event.preventDefault();
            var nextPageUrl = nav.find(".current + a").attr("href");
            if (nextPageUrl) {
                postlist.loading = true;
                $(this).append('<i class="loading m-icon m-icon-spinner m-spin"></i>');
                loadPosts(nextPageUrl, postlist);
            }
        });
    }




});

