jQuery(function($) {
    var loading = false;
    var loadCount = 0;
    var maxLoads = 5;

    function loadMorePosts() {
        if (loading || loadCount >= maxLoads) return;

        var scrollTop = $(window).scrollTop();
        var windowHeight = $(window).height();
        var documentHeight = $(document).height();

        // Условие для определения, что мы достигли конца страницы
        var scrollTrigger = (scrollTop + windowHeight >= documentHeight - 200);

        if (scrollTrigger) {
            loading = true;

            var data = {
                'action': 'loadmore',
                'query': my_load_more_params.posts,
                'page': my_load_more_params.current_page
            };

            $.ajax({
                url: my_load_more_params.ajaxurl,
                data: data,
                type: 'POST',
                beforeSend: function(xhr) {
                    $('.articles-preview__show-next').text('Загрузка...');
                },
                success: function(data) {
                    if (data) {
                        $('.articles-preview').append(data);
                        my_load_more_params.current_page++;
                        loadCount++;
                    
                        var titleTags = document.getElementsByTagName('title');
                        var metaTitle = titleTags[0].textContent;
                        var titlePage = metaTitle;

                        ym(96621494, 'hit', location.pathname + '?page=' + my_load_more_params.current_page, {title: titlePage, referer: location.pathname});

                        if (my_load_more_params.current_page == my_load_more_params.max_page || loadCount >= maxLoads) {
                            $(window).off('scroll touchmove', loadMorePosts);
                            $('.articles-preview__show-next').remove();
                        } else {
                            loading = false;
                        }
                    } else {
                        $(window).off('scroll touchmove', loadMorePosts);
                        $('.articles-preview__show-next').remove();
                    }
                }
            });
        }
    }

    $(window).on('scroll touchmove', loadMorePosts);

});