var $ = jQuery.noConflict();

$(document).on('ready', function () {
    'use strict';

    var postToLoad = 0,
        loadInto = $(".related-content"),
        loadWithSidebars = loadInto.hasClass("with-sidebars"),
        loading = false,
        relatedLinks;

    if (loadInto.data('related-links')) {
        relatedLinks = loadInto.data('related-links').split(',');
    }

	if (loadInto.length > 0) {

        if ($(".single-post-header-title").length) {
            var txt = $(".post-title a").text(),
                initTitle = $(".post-title").text().replace(txt, "");
            $(".single-post-header-title").text(initTitle);
        }

		var postEnds = document.querySelectorAll('.related-content');
		if (postEnds && 'IntersectionObserver' in window) {
			const postEndObserver = new IntersectionObserver(function (entries) {
				entries.forEach(function (entry) {
					if (entry.isIntersecting && postToLoad < relatedLinks.length && !loading) {
						loading = true;
						loadPost(postToLoad, loadInto, loadWithSidebars);
						postEndObserver.unobserve(entry.target);
					}
				});
			});
			postEndObserver.observe(postEnds[postEnds.length - 1]);

			document.addEventListener('related-post-loaded', function () {
				postEnds = document.querySelectorAll('.post-end');
				if (postEndObserver && postEnds.length) {
					postEndObserver.observe(postEnds[postEnds.length - 1]);
				}
			});
		}

		const singlePostHeader = document.querySelector('.single-post-header');
		var posts = document.querySelectorAll('.post-content[data-permalink]');
		if (posts && 'IntersectionObserver' in window) {
			const permalinkObserver = new IntersectionObserver(function (entries) {
				entries.forEach(function(post) {
					if (post.isIntersecting) {
						var permalink = post.target.dataset.permalink;
						if (permalink) {
							window.history.pushState({}, "", permalink);
						}
						// update single post header
						if (singlePostHeader) {
							const postTitleElement = post.target.querySelector('.post-title') || document.querySelector('.post-title');

							var linkText = postTitleElement.querySelector('a') ? postTitleElement.querySelector('a').textContent : '';
							var postTitle = postTitleElement ? postTitleElement.textContent.replace(linkText, '') : '';

							document.querySelector('.single-post-header-title').textContent = postTitle;

							const updateEvent = new CustomEvent('single-post-header-update', {
								detail: {
									postTitle: postTitle,
									permalink: permalink
								}
							});
							document.dispatchEvent(updateEvent);
						}
					}
				});
			}, {
				rootMargin: '-20% 0px -20% 0px'
			});

			posts.forEach(function (post) {
				permalinkObserver.observe(post);
			});

			document.addEventListener('related-post-loaded', function () {
				posts = document.querySelectorAll('.post-content');
				posts.forEach(function (post) {
					permalinkObserver.observe(post);
				});
			});
		}
    }

    // loading an article
    function loadPost(index, target, withSidebars) {
        target.append('<div class="loader"><i class="m-icon m-icon-spinner m-spin"> </i></div>');

        $.ajax({
            url: relatedLinks[index],
            dataType: "html",
            success: function (response) {
                var postMarkup = '',
                    authorMarkup = '',
                    customStyles = $(response).find('#multi-builder-blocks-inline-css');

                if (withSidebars) {
                    postMarkup = $(response).find(".content");
                    postMarkup.find(".post-nav, .related-posts, .featured-posts, .comments, .comment-form, .leave-comment, .related-content").remove();
                } else {
                    postMarkup = $(response).find(".post-content");
                    authorMarkup = $(response).find(".post-author");
                }

                // if the post has the large header, add its contents to the inserted post
                if (!withSidebars) {
                    var articleHead = null;
                    if ($(response).find(".article-head").length > 0) {
                        articleHead = $(response).find(".article-head-content");
                    } else if ($(response).find(".post-header").length > 0) {
                        articleHead = $(response).find(".post-header").html();
                    }
                    if (articleHead) {
                        postMarkup.prepend(articleHead);
                    }
                }

                target.find(".loader").remove();
                if (!withSidebars) {
                    target.append(postMarkup);
                }
                target.append(postMarkup);
                if (authorMarkup) {
                    target.append(authorMarkup);
                }

                var inlineStyles = $('#multi-builder-blocks-inline-css') || $('<style id="multi-builder-blocks-inline-css"></style>');
                var newCustomStyles = inlineStyles.text() + customStyles.text();
                inlineStyles.text(newCustomStyles);
                if ( !$("body").find('#multi-builder-blocks-inline-css').length ) {
                    $("body").append(inlineStyles);
                }

                var lastArticle = withSidebars ? target.find(".site-content").last() : target.find(".post-content").last();

                postToLoad += 1;
                loading = false;

                $(document).trigger("post-loaded", [lastArticle]); // todo: remove when every listener is moved to related-post-loaded event
                document.dispatchEvent(new CustomEvent('related-post-loaded', {detail: lastArticle}));
            }
        });
    }
});
/*global window, PhotoSwipe, PhotoSwipeUI_Default*/

/*
* Functions for various post element behaviors
*/
// adding behaviours to items inside posts

$(document).on('post-loaded', function (ignore, el) {
    'use strict';

    $(el).find(".widget .menu li.menu-item-has-children").each(function (ignore, element) {
        $(element).children("a").append('<span></span>');
    });
    // apply icons to links
    $(el).find(".widget .menu li.m-icon").each(function (ignore, element) {
        var me = $(element),
            link = me.children("a"),
            classes = me.attr("class").split(" "),
            iconClasses = "",
            pattern = /\bm-icon-/,
            i;

        for (i = 0; i < classes.length; i += 1) {
            if (pattern.test(classes[i])) {
                iconClasses += " " + classes[i];
            }
        }
        link.addClass("m-icon " + iconClasses);
    });

    var sideMenus = $(el).find('.widget .menu .parent');
    sideMenus.each(function (ignore, element) {
        var delay = 500,
            parentItem = $(element),
            submenu = parentItem.children('ul');

        if (!parentItem.hasClass('expanded')) {
            submenu.hide();
        }

        if ($('html').hasClass('no-touch')) {
            parentItem.not('.current-menu-ancestor').on("mouseenter", function () {
                submenu.stop(true, true).delay(delay).slideDown(function () {
                    parentItem.addClass("expanded");
                });
            });
            parentItem.not('.current-menu-ancestor, .current-menu-item').on("mouseleave", function () {
                submenu.stop(true, true).delay(delay).slideUp(function () {
                    parentItem.removeClass("expanded");
                });
            });
        } else {
            parentItem.children("a").children("span").on("click", function () {
                parentItem.toggleClass("expanded");
                submenu.slideToggle(function () {
                    parentItem.toggleClass("expanded");
                });
            });
        }
    });
});
