function initObserver() {
	var lazyImages = [].slice.call(document.querySelectorAll(".lazy"));
	if ("IntersectionObserver" in window) {
		let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
			entries.forEach(function(entry) {
				if (entry.isIntersecting) {
					let lazyImage = entry.target;
					lazyImage.src = lazyImage.dataset.src;		
					lazyImage.classList.remove("lazy");
					lazyImageObserver.unobserve(lazyImage);
				}
			});
		});
	
		lazyImages.forEach(function(lazyImage) {
			lazyImageObserver.observe(lazyImage);
		});
	} else {
		// Possibly fall back to event handlers here
	}
}

function fetchNotifications(latestDate) {
    if ( $('#notificationsMenu').hasClass('show') ) {
        setTimeout(fetchNotifications, 60000, $('#latestDate').text()); 
        return;
    }

    let oldHtml = $('#notificationsMenuContainer').html();

    $.ajax({
        url: '/clients/ajax/fetch-notifications.php',
        method: 'POST',
        data: {
            latestDate: latestDate
        },
        success: function (data) {
            if ( !$.trim(data) ) {
                return;
            }

            $('#notificationsMenuContainer').html(data);
            // $('#notificationsMenuIcon').addClass('blink');
        },
        error: function (e) {
            $('#notificationsMenuContainer').html(oldHtml);
        },
        complete: function(data) { 
            setTimeout(fetchNotifications, 60000, $('#latestDate').text()); 
        }
    });
}

function updateLatestDate(latestDate) {
    $.ajax({
        url: '/clients/ajax/update-latest-date.php',
        method: 'POST',
        data: {
            latestDate: latestDate
        }
    });
}

var loader      = '<div class="d-flex"><div class="spinner-border text-danger" role="status"><span class="visually-hidden">Loading...</span></div></div>';
var notifLoader = '<div class="d-flex align-items-center justify-content-center"><div class="spinner-border text-danger" role="status"><span class="visually-hidden">Loading...</span></div></div>';

document.addEventListener('DOMContentLoaded', function () {
    $(document).on('show.bs.dropdown', '#notificationsDropdown', function(e) {
        $('#notificationsMenuIcon').removeClass('blink');
        updateLatestDate($('#latestDate').text());
    });

    $(document).on('change', '.notifFilter', function(e) {
        let oldHtml = $('#notificationsMenuContainer').html();

        if ( $(this).next().hasClass('blink') ) {
            $(this).next().removeClass('blink');
        }

        $('.notifFilter').attr('disabled', true);

        let height = $('#notificationsMenu').css('height');
        let width  = $('#notificationsMenu').css('width');
        $('#notificationsMenu').css('min-height', height);
        $('#notificationsMenu').css('min-width', width);
        $('#notificationsItems').html(notifLoader);

        let filters = [];
        $('.notifFilter').each(function () {
            if ( $(this).is(':checked') ) {
                // console.log(this);
                filters.push(this.value);
            }
        });

        // console.log(filters);

        $.ajax({
            url: '/clients/ajax/filter-notifications.php',
            method: 'POST',
            data: {
                filters: filters
            },
            success: function (data) {
                $('#notificationsItems').html(data);
                updateLatestDate($('#latestDate').text());
            },
            error: function (e) {
                $('#notificationsMenuContainer').html(oldHtml);
            },
            complete: function(data) { 
                $('.notifFilter').removeAttr('disabled');
            }
        });
    });

    initObserver();

    //insantiate all tooltips
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    const tooltipList        = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));

    setTimeout(() => {
        fetchNotifications($('#latestDate').text());
    }, 10000);
});