( function() {
	'use strict';

	if ( 'querySelector' in document && 'addEventListener' in window ) {
		/**
		 * matches() pollyfil
		 * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Browser_compatibility
		 */
		if ( ! Element.prototype.matches ) {
			Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
		}

		/**
		 * closest() pollyfil
		 * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Browser_compatibility
		 */
		if ( ! Element.prototype.closest ) {
			Element.prototype.closest = function( s ) {
				var el = this;
				var ancestor = this;
				if ( ! document.documentElement.contains( el ) ) {
					return null;
				}
				do {
					if ( ancestor.matches( s ) ) {
						return ancestor;
					}
					ancestor = ancestor.parentElement;
				} while ( ancestor !== null );
				return null;
			};
		}

		var getSiblings = function( elem ) {
			return Array.prototype.filter.call( elem.parentNode.children, function( sibling ) {
				return sibling !== elem;
			} );
		};

	}

})();

/**
 * :scope polyfill
 * https://stackoverflow.com/a/17989803/2573521
 */
(function(doc, proto) {
	try { // check if browser supports :scope natively
	  doc.querySelector(':scope body');
	} catch (err) { // polyfill native methods if it doesn't
	  ['querySelector', 'querySelectorAll'].forEach(function(method) {
		var nativ = proto[method];
		proto[method] = function(selectors) {
		  if (/(^|,)\s*:scope/.test(selectors)) { // only if selectors contains :scope
			var id = this.id; // remember current element id
			this.id = 'ID_' + Date.now(); // assign new unique id
			selectors = selectors.replace(/((^|,)\s*):scope/g, '$1#' + this.id); // replace :scope with #ID
			var result = doc[method](selectors);
			this.id = id; // restore previous id
			return result;
		  } else {
			return nativ.call(this, selectors); // use native code for other selectors
		  }
		}
	  });
	}
})(window.document, Element.prototype);

/**
 * fallback for requestAnimationFrame & cancelAnimationFrame
 */
(function() {
	var lastTime = 0;
	var vendors = ['ms', 'moz', 'webkit', 'o'];
	for(var x = 0; x > vendors.length && !window.requestAnimationFrame; ++x) {
	  window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
	  window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
								 || window[vendors[x]+'CancelRequestAnimationFrame'];
	}
  
	if (!window.requestAnimationFrame)
	  window.requestAnimationFrame = function(callback, element) {
		var currTime = new Date().getTime();
		var timeToCall = Math.max(0, 16 - (currTime - lastTime));
		var id = window.setTimeout(function() { callback(currTime + timeToCall); },
		  timeToCall);
		lastTime = currTime + timeToCall;
		return id;
	  };
  
	if (!window.cancelAnimationFrame)
	  window.cancelAnimationFrame = function(id) {
		clearTimeout(id);
	  };
}());




jQuery(document).ready(function($){

	/**
	 * Breakpoint of mobile device
	 */
	const mobileBreakpoint = sunset_params.mobile_breakpoint;

	/**
	 * Check if window size is less than $mobileBreakpoint value
	 * @returns {boolean}
	 */
	const isMobile = () => {return window.matchMedia(`(max-width: ${mobileBreakpoint}px)`).matches};

	/**
	 * Check if script running in iframe
	 * @returns {boolean} True if script runs in iframe
	 */
	const isInIframe = () => {
		try {
			return window.self !== window.top;
		} catch (e) {
			return true;
		}
	}

	/**
	 * Get offset for sticky header/topbar
	 * @returns {integer}
	 */
	const getStickyHeaderOffset = () => {		
		let headerHeight = $('.site-header--fixed:not(.site-header--mobile-sticky-disable.is-mobile) .header')[0]?.offsetHeight || 0;
		let topbarHeight = $('.site-header--with-sticky-topbar .topbar')[0]?.offsetHeight || 0;
		let offsetTop = headerHeight + +topbarHeight;

		return offsetTop;
	}

	const handleAnchorLinkClick = (event) => {

		// The id of the section we want to go to.
		let href = $(event.target)?.attr("href");
		
		if (href) {
			let id = href.substring(href.indexOf('#'));
			let url = href.substring(0, href.indexOf('#'));
			let currentUrl = window.location.href.substring(0, window.location.href.indexOf('#'));

			if ( event.target.tagName === 'A' && 
				id && id !== "#" && $(`${id}`).length > 0 && 
				( url === '' || url === currentUrl ) &&
				!$(event.target).hasClass('comment-reply-link') ) {

				//prevent the page from jumping down to our section.
				event.preventDefault();

				// An offset to push the content down from the top.
				let offset = getStickyHeaderOffset();

				// Our scroll target : the top position of the
				// section that has the id referenced by our href.
				let target = $(id).offset().top - offset;

				// The magic...smooth scrollin' goodness.
				$('html, body').animate({scrollTop:target}, sunset_params.animation_speed);
			}
		}
	}

	/**
	 * Calculating progress for the animation
	 * @param {integer} time 
	 * @param {integer} start 
	 * @param {integer} duration 
	 * @returns 
	 */
	const calcProgress = (time, start, duration) => {
		return ((time - start) / duration); 
	}

	/**
	 * Animating element
	 * @param {HTMLElement} runlineText - a gtext element to animate
	 * @param {integer} runlineSpeed - speed of the animation 1-10
	 */
	const animateLine = (runlineText, runlineSpeed) => {

		let animateID;
		let progress = 0;
		let pausedAt = 0;
		let startRunline = performance.now();
		let durationRunline = (11 - runlineSpeed) * 3; // animation speed in ms.

		const animateRunline = (time) => {
			progress = calcProgress(time, startRunline, durationRunline);

			if (progress >= runlineText.offsetWidth / 2) {
				startRunline = performance.now();
			}
			
			if (document.body.classList.contains('rtl')) {
				runlineText.style.transform = `translate3d(${progress}px, 0px, 0px)`;
			} else {
				runlineText.style.transform = `translate3d(-${progress}px, 0px, 0px)`;
			}
			
			animateID = requestAnimationFrame(animateRunline);
		} 

		animateID = requestAnimationFrame(animateRunline);

		/**
		 * Pause on hover
		 */
		runlineText.addEventListener("mouseenter", function( event ) {
			cancelAnimationFrame(animateID);
			pausedAt =  performance.now();
		})
		
		/**
		 * Rresume on unhover
		 */
		runlineText.addEventListener("mouseleave", function( event ) {
			startRunline += window.performance.now() - pausedAt;
			animateID = requestAnimationFrame(animateRunline);
		})
	}

	/**
	 * Cloning text to fill the full width multiplied by 2
	 * @param {HTMLElement} runlineText - a text to clone
	 * @param {HTMLElement} runlineEl - a parent element of the text
	 */
	const cloneTextFront = (runlineText, runlineEl, step = 1) => {
		if (runlineText.offsetWidth < runlineEl.offsetWidth * 2) {
			let newRunlineText = runlineText.querySelectorAll(':scope > *');
			for (let i = 0; i < newRunlineText.length; i+= 1) {
				let newEl = newRunlineText[i].cloneNode(true);
				newEl.className += ' editor-clones';
				runlineText.append(newEl);
			}
			step += 1;		
			cloneTextFront(runlineText, runlineEl, step);
		} else {
			if (step % 2 !== 0) { // add extra clone to animate without offsets
				let newRunlineText = runlineText.querySelectorAll(':scope > *');
				for (let i = 0; i < newRunlineText.length; i+= 1) {
					let newEl = newRunlineText[i].cloneNode(true);
					newEl.className += ' editor-clones';
					runlineText.append(newEl);
				}
			}
		}
	}

	/**
	 * Init runlines (topbar and copyright)
	 */
	const initRunlineFunctions = () => {
		let runlines = document.querySelectorAll(".topbar--runline, .site-copyright--runline");

		if (runlines.length > 0 && !isInIframe()) {
			for (let i=0; i < runlines.length; i += 1) {
				let runline = runlines[i];
				
				let runlineContent = runline.querySelector(".topbar__inner__content, .site-copyright__inner__content");
				let runlineSpeed = runline.getAttribute('data-speed'); // 1-10 - bigger => faster
				
				runline.querySelectorAll(".editor-clones").forEach(e => e.remove());

				if (runlineContent.innerHTML.trim() !== '') {
					cloneTextFront(runlineContent, runline);
					animateLine(runlineContent, runlineSpeed);
				}
				
			}
		}
	}

	/**
	 * Launch animations for elements
	 * @param {HTMLCollection} elements 
	 */
	const detectAnimationElements = (elements) => {
		for (let i = 0; i< elements.length; i += 1) {
			let element = elements[i];
			let elementHeight = element.offsetHeight;
			let windowHeight = window.innerHeight;

			if ( (elementHeight * 100 / windowHeight) <= 40 ) { // element's height is less than 40% of window's height
				// animate element if 10% of it's height is in viewport
				if( isInViewport(element, 10) && !element.classList.contains('visible') ){ 
					element.classList.add('visible');
				}
			} else {
				// animate element if 5% of it's height is in viewport
				if( isInViewport(element, 5) && !element.classList.contains('visible') ){ 
					element.classList.add('visible');
				}
			}
		}
	}

	/**
	 * Set the real VW and VH variables to the :root
	 */
	const setVwVh = () => {
		let vw = document.documentElement.clientWidth / 100;
		let vh = document.documentElement.clientHeight / 100;
		document.documentElement.style.setProperty('--vw', `${vw}px`);
		document.documentElement.style.setProperty('--vh', `${vh}px`);
	}

	/**
	 * Set the the width of sidebar
	 */
	const setSidebarWidth = () => {
		const sidebars = document.querySelectorAll(".sidebar__inner");
		for (let i = 0; i < sidebars.length; i++) {
			let sidebarWidth = sidebars[i].offsetWidth;
			sidebars[i].style.setProperty('--sidebar-width', `${sidebarWidth}px`);
		}
	}

	/**
	 * Checks if user's device has pointer (mouse)
	 * @returns {boolean}
	 */
	const isTouchDevice = () => {
		return window.matchMedia('(hover: none)').matches;
	}

	/**
	 * Checks if an element is in the viewport for X percents
	 * @param {HTMLElement} el element to check
	 * @param {integer} percentVisible percentage of visibility when detect element
	 * @returns {boolean}
	 */
	const isInViewport = function(el, percentVisible = 60) {
		let rect = el.getBoundingClientRect();
		let	windowHeight = (window.innerHeight || document.documentElement.clientHeight);
	
		return !(
			Math.floor(100 - (((rect.top >= 0 ? 0 : rect.top) / +-(rect.height / 1)) * 100)) < percentVisible ||
			Math.floor(100 - ((rect.bottom - windowHeight) / rect.height) * 100) < percentVisible
		)
	};

	/**
	 * Detect when element becomes wrapped in flex mode
	 * https://codepen.io/brettdewoody/pen/rrKpPp 
	 * 
	 * @param string elements - name of the element
	 * @returns {array} Array of elements that were wrapped
	 */
	const detectWrap = (elements) => {
		let wrappedItems = [];
		let prevItem = {};
		let currItem = {};
		let items = document.querySelectorAll(elements);

		for (let i = 0; i < items.length; i++) {
			currItem = items[i].getBoundingClientRect();
			
			if ( prevItem ) {
				let prevItemTop = prevItem.top;
				let prevItemWidth = prevItem.width;
				let currItemTop = currItem.top;
				let currItemWidth = currItem.width;
				
				if ( prevItemTop < currItemTop || 
					// special hack for split heading type - check if width of image and text content equal
					(items[i].classList.contains('heading-section--split__content') && prevItemWidth === currItemWidth) ) {
					wrappedItems.push(items[i]);
				}	
			}

			prevItem = currItem;
		};
		
		return wrappedItems;
	}

	/**
	 * Handle burger button click
	 */
	const handleBurgerClick = () => {
		const burgers = document.querySelectorAll('.burger');
		const header = document.querySelector('.site-header');
		const fullscreenBlock = document.querySelector('.fullscreen-menu-block');
		const body = document.body;

		for (let i = 0; i < burgers.length; i += 1) {
			burgers[i].classList.toggle("opened");

			if (burgers[i].classList.contains("opened")) {
				burgers[i].setAttribute("tabindex", null);
			} else {
				burgers[i].setAttribute("tabindex", "-1");
			}
		}
		header.classList.toggle("mobile-menu-opened");
		fullscreenBlock.classList.toggle("opened");
		body.classList.toggle("no-scroll");

		$(fullscreenBlock).find(".main-nav-menu.opened").find("a").attr('tabindex', function(index, attr){
			return attr == -1 ? null : -1;
		});

		if (fullscreenBlock.classList.contains("opened")) {
			$(header).find(".main-nav-menu:not(.main-nav-menu--mobile) a").attr("tabindex", "-1")
			$(".site-main a").attr("tabindex", "-1")
			$(".site-footer a").attr("tabindex", "-1")
			$(fullscreenBlock).find(".main-nav-menu.main-nav-menu--social a").attr("tabindex", null)
		} else {
			$(header).find(".main-nav-menu:not(.main-nav-menu--mobile) a").attr("tabindex", null)
			$(".site-main a").attr("tabindex", null)
			$(".site-footer a").attr("tabindex", null)
			$(fullscreenBlock).find(".main-nav-menu.main-nav-menu--social a").attr("tabindex", "-1")
		}
	}

	/**
	 * Handle search icon click
	 */
	const handleSearchIconClick = (event) => {
		event.preventDefault();

		const button = jQuery('.header-search-button');
		const header = jQuery('.site-header');
		const form = jQuery('div:not(.fullscreen-menu-block) .header-search-form');
		
		button.toggleClass('open');
		form.toggleClass('open');
		header.toggleClass('search-open');

		if (form.hasClass('open')) {
			form.find("input, button").attr('tabindex', null);
			form.find('input[type="search"]').focus();
		} else {
			form.find("input, button").attr('tabindex', '-1');
		}
	}

	/**
	 * Set position of search form in header
	 */
	const setHeaderSearch = () => {
		
		const button = $('.header-search-button');
		const header = $('.site-header');
		const burger = $('.site-header .main-nav > .burger');

		if (button.length === 0)
			return;

		let main_nav = button.closest('.header__inner');
		let form = $('div:not(.fullscreen-menu-block) .header-search-form');
		let item = $('div:not(.fullscreen-menu-block) .header-search-item');
		let offsetChild = item[0].getBoundingClientRect();
		let offsetParent = main_nav[0].getBoundingClientRect();
		let offsetBurger = burger[0].getBoundingClientRect();
		let offset = 0;
		
		//console.log(offsetChild, 'offsetChild')
		//console.log(offsetParent, 'offsetParent')

		// for centered header in mobile mode search goes to the edge, so we need to recalculate its position
		if (header.hasClass('site-header--centered') && header.hasClass('site-header--auto-responsive') && header.hasClass('is-mobile')) { 
			if (item.hasClass('header-search-item--rtl')) {
				offset = offsetChild.right - offsetChild.width - offsetParent.right;
				offset = offset < 0 ? offset * -1 : offset;
				form.css('left', offsetParent.left - offsetBurger.right);
				form.css('right', offset);
			} else {				
				offset = offsetChild.left - offsetChild.width - offsetParent.left;
				offset = offset < 0 ? offset * -1 : offset;
				form.css('right', offsetParent.right - offsetBurger.left);
				form.css('left', offset);
			}
		} else {
			if ( form.hasClass('header-search-form--inline') ) {
				if (item.hasClass('header-search-item--rtl')) {
					offset = offsetChild.right;
					form.css('left', offset);
					header.css('--offset-left', offset);
					form.css('right', '');
				} else {	
					offset = offsetParent.right - offsetChild.left;
					offset = offset < 0 ? offset * -1 : offset;
					form.css('right', offset);
					header.css('--offset-right', offset);
					form.css('left', '');
				}
			}
		}
	}
	
	/**
	 * Set classes for the header when menu items become wrapped
	 */
	const setHeaderWrappedClasses = () => {
		
		const headerMenuItems = '.main-nav:not(.main-nav--fullscreen) > .main-nav-menu > li';
		const burger = $('.burger');
		const header = $('.site-header');
		const body = $('body');
		const fullscreenMenuBlock = $('.fullscreen-menu-block');
		const menuRegular = $('.site-header .main-nav-menu--regular');
		const menuSocial = $('.site-header .main-nav > .main-nav-menu--social');
		const menuSearch = $('.site-header .main-nav-menu--search');

		if (!header.hasClass('site-header--auto-responsive')) // if header is not auto-responsive then skip it all
			return;

		// remove wrapped and mobile classes 
		header.addClass('hidden');
		header.removeClass('is-mobile');
		body.removeClass('is-mobile');
		header.removeClass('mobile-menu-opened');

		burger.removeClass('visible');
		burger.removeClass('opened');

		fullscreenMenuBlock.removeClass('visible');
		fullscreenMenuBlock.removeClass('opened');

		$('body').removeClass('no-scroll');

		menuRegular.removeClass('was-wrapped');
		menuSocial.removeClass('was-wrapped');
		menuSearch.removeClass('was-wrapped');

		// show burger if chosed option to show the burger menu always
		if (header.hasClass('site-header--burger-always')) {
			burger.addClass('visible');
			fullscreenMenuBlock.addClass('visible');

			if ( isMobile() ) {
				header.addClass('is-mobile');
				body.addClass('is-mobile');
			}
		}

		// detect wrapped elements
		let wrappedItems = detectWrap(headerMenuItems);

		// add wrapped and mobile classes if wrapped items were found
		if (wrappedItems.length > 0) {
			header.addClass('is-mobile');
			body.addClass('is-mobile');
			burger.addClass('visible');
			fullscreenMenuBlock.addClass('visible');

			for (let k = 0; k < wrappedItems.length; k++) {
				wrappedItems[k].closest('ul').classList.add("was-wrapped");

				if ( wrappedItems[k].closest('ul').classList.contains('main-nav-menu--regular') ) {
					menuRegular.addClass('was-wrapped');
					//menuSearch.addClass('was-wrapped');
					menuSocial.addClass('was-wrapped');
				}
			}
		}

		header.removeClass('hidden');
		
	}
	
	/**
	 * Set classes for the footer when columns become wrapped
	 */
	const setFooterWrappedClasses = () => {
		
		const footer_columns = '.footer-column-1, .footer-column-2';
		const footer = $('.site-footer');
		const footerInner = footer.find('.site-footer__inner');

		if (!footer.hasClass('site-footer--cross-style'))
			return;

		footer.addClass('hidden');
		footer.removeClass('is-mobile');
		footerInner.removeClass('was-wrapped');

		let wrappedItems = detectWrap(footer_columns);

		if (wrappedItems.length > 0) {
			footer.addClass('is-mobile');
			footerInner.addClass("was-wrapped");
		}
		
		footer.removeClass('hidden');
		
	}

	/**
	 * Set classes for the copyright when items become wrapped
	 */
	const setCopyrightWrappedClasses = () => {
		
		const copyrightWidgets = '.site-copyright .copyright-widget';
		const copyright = $('.site-copyright');
		const copyrightInner = $('.site-copyright').find('.site-copyright__inner__content');
		let wrappedItems = [];
		
		copyright.addClass('hidden');
		copyright.removeClass('is-mobile');
		copyrightInner.removeClass('was-wrapped');

		wrappedItems = detectWrap(copyrightWidgets);

		if (wrappedItems.length > 0) {
			copyright.addClass('is-mobile');
			copyrightInner.addClass("was-wrapped");
		}
		
		copyright.removeClass('hidden');
		
	}

	/**
	 * Set wrapped classes for blocks
	 * 
	 * @param {Selector} elements to check if they changed their positions
	 * @param {Selector} elementsHolder to which apply class .was-wrapped
	 */
	const setWrappedClasses = (elements, elementsHolder) => {
		let wrappedItems = [];

		$(elements).closest(elementsHolder).removeClass("was-wrapped");

		wrappedItems = detectWrap(elements);
		
		if (wrappedItems.length > 0) {
			$(wrappedItems).closest(elementsHolder).addClass("was-wrapped");
		}
	}

	/**
	 * Sticky header on scroll up
	 * https://codepen.io/tutsplus/pen/WNerWWp
	 */
	const stickyHeaderOnScrollUp = () => {
		const header = document.querySelector(".site-header--fixed");

		if (!header) return true;

		const scrollUp = "scroll-up";
		const scrollDown = "scroll-down";
		const currentScroll = window.pageYOffset;
		let headerHeight = header.offsetHeight;
		let lastScroll = 0;

		if (!header) return true;		

		if (currentScroll > headerHeight) {
			header.classList.add(scrollDown);
			header.classList.remove(scrollUp);
			document.body.classList.add(scrollDown);
			document.body.classList.remove(scrollUp);
		}		

		window.addEventListener("scroll", () => {
			const currentScroll = window.pageYOffset;

			if (document.getElementById('fullscreen-menu-block').classList.contains('opened')) {
				return;
			}

			if (currentScroll <= headerHeight) {
				header.classList.remove(scrollUp);
				header.classList.remove(scrollDown);
				document.body.classList.remove(scrollUp);
				document.body.classList.remove(scrollDown);
				return;
			}
		
			if (currentScroll > lastScroll && !header.classList.contains(scrollDown)) {
				// down
				header.classList.remove(scrollUp);
				header.classList.add(scrollDown);
				document.body.classList.remove(scrollUp);
				document.body.classList.add(scrollDown);
			} else if (
			currentScroll < lastScroll &&
			header.classList.contains(scrollDown)
			) {
				// up
				header.classList.remove(scrollDown);
				header.classList.add(scrollUp);
				document.body.classList.remove(scrollDown);
				document.body.classList.add(scrollUp);
			}
			lastScroll = currentScroll;
		});
	}
    

	/**
	 * Add attributes to the topbar and header
	 */
	const setHeights = () => {
		const topbar = document.querySelector(".site-header .topbar");
		const header = document.querySelector(".site-header .header");
		
		setTimeout(() => {
			let topbarHeight = topbar ? topbar.offsetHeight : '0';
			let headerHeight = header ? header.offsetHeight : '0';
			document.documentElement.style.setProperty('--topbar-height', topbarHeight + 'px');
			document.documentElement.style.setProperty('--header-height', headerHeight + 'px');
		}, 100) // set delay to wait all animations
		
	}

	/**
	 * Get scrollbar width
	 * https://davidwalsh.name/detect-scrollbar-width
	 */
	const getScrollbarWidth = () => {
		// Create the measurement node
		let scrollDiv = document.createElement("div");
		scrollDiv.className = "scrollbar-measure";
		document.body.appendChild(scrollDiv);

		// Get the scrollbar width
		let scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
		document.documentElement.style.setProperty('--scrollbar-width', `${scrollbarWidth}px`);

		// Delete the DIV 
		document.body.removeChild(scrollDiv);
	}

	/**
	 * scrollShadows
	 * 
	 * @param el - string Selector to attach shadows
	 */
	const scrollShadows = (el) => {
		let wrapper = document.querySelector(el);
		let content = document.querySelector(`${el} .simplebar-content-wrapper`);
		if ( typeof(wrapper) === 'undefined' || wrapper === null ) return;
		
		let shadowTop = wrapper.querySelector('.shadow--top');
		let shadowBottom = wrapper.querySelector('.shadow--bottom');
		let contentScrollHeight = (content.scrollHeight - wrapper.offsetHeight);

		if (content.scrollHeight < wrapper.offsetHeight) {
			shadowBottom.style.opacity = 0;
		}

		$(content).off('scroll'); // detach scroll to apply to current menu screen only
		content.addEventListener('scroll', function(){
			contentScrollHeight = (content.scrollHeight - wrapper.offsetHeight); // need to update scroll height
			let currentScroll = Math.round(this.scrollTop) / (contentScrollHeight);  
			shadowTop.style.opacity = currentScroll;
			shadowBottom.style.opacity = 1 - currentScroll;
		});
	}

	/**
	 * Zoom in/out image on scroll (for cover heading)
	 * 
	 * @param selector - string Selector of the image
	 */
	 const zoomImageOnScroll = (selector) => {
		let image = document.querySelector(selector);
		if ( typeof(image) === 'undefined' || image === null ) return;		
		
		let imageTop = image.getBoundingClientRect().top;
		let imageHeight = image.getBoundingClientRect().height;
		let windowScrollY = window.scrollY;
		let currentScroll = Math.round(windowScrollY) / (imageHeight + +imageTop);
		let coeff = 0.75;
		
		if (currentScroll < 0) {
			currentScroll = 0;
		}
		if (currentScroll > 1) {
			currentScroll = 1;
		}

		let scale = currentScroll + coeff;

		if (scale < 1) scale = 1;

		image.style.transform = `scale(${scale})`;
	}

	/**
	 * Show/hide TOC
	 */
	const toggleTOC = (isOnScroll = false) => {
		const toc = document.querySelector('.post__contents');
		const content = document.querySelector('.content-section');

		if (!toc) return;

		if (!isOnScroll) // remove class only on resize/on load event
			toc.classList.remove('on-top');

		let tocTop = toc.getBoundingClientRect().top;
		let tocBottom = toc.getBoundingClientRect().bottom;
		let tocRight = toc.getBoundingClientRect().right;
		let tocWidth = toc.getBoundingClientRect().width;
		let contentTop = content.getBoundingClientRect().top;
		let contentBottom = content.getBoundingClientRect().bottom;
		let contentRight = content.getBoundingClientRect().right;
		let contentWidth = content.getBoundingClientRect().width;
		let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
		let scrollableContent = $(toc).find('.simplebar-content-wrapper');
		let layout = sunset_params.current_page_layout;

		if ($('body').hasClass('rtl')) {
			contentRight = content.getBoundingClientRect().left;
			tocRight = toc.getBoundingClientRect().left;
		}

		if ( (layout !== 'full' && contentRight > (tocRight - tocWidth / 2)) || 
			(layout === 'full' && (isMobile() || contentWidth / 4 < tocWidth)) ) { // stick TOC on top if overlaps post's content
			toc.classList.add('on-top');
		} else {
			if (tocTop > contentTop && contentBottom > tocBottom ) {
				toc.classList.add('active');

				// searching for the current TOC item and highlight it
				if ($(content).find(`:header`).length > 0) {
					$(content).find(`:header`).each(function(){
						let heading = $(this);
						let headingText = heading.text();
						let headingTop = heading.offset().top;
						let item = $(toc).find(`li:contains('${headingText}')`);

						if ( (scrollTop + +getStickyHeaderOffset() + +heading.height()) >= headingTop ) {
							item.addClass('active');
							$(toc).find('.active').prevAll('li').removeClass('active');

							if (item.length > 0) {
								scrollableContent.stop( true, false ).animate({ // scroll TOC to active item if overflows
									scrollTop: item.offset().top - scrollableContent.offset().top + scrollableContent.scrollTop()
								});
							}
						} else {
							item.removeClass('active');
						}
					})
				}
			} else {
				toc.classList.remove('active');
			}
		}
	}
	
	/**
	 * Toggle background for the header on the single post if split content header enabled
	 */
	 const toggleHeaderBackground = () => {
		const header = document.querySelector('body.single .site-header, body.page:not(.home) .site-header');
		const content = document.querySelector('.content');

		if (!header || !header.classList.contains('site-header--heading-cover')) return;

		let headerBottom = header.getBoundingClientRect().bottom;
		let contentTop = content.getBoundingClientRect().top;

		if ( header.classList.contains('site-header--fixed') && !header.classList.contains('is-mobile') ) {
			if (headerBottom < contentTop ) {
				header.classList.add('site-header--with-transparent');
			} else {
				header.classList.remove('site-header--with-transparent');
			}
		} else {
			if ( contentTop >= 0 ) {
				header.classList.add('site-header--with-transparent');
			} else {
				header.classList.remove('site-header--with-transparent');
			}
		}
		
	}

	/**
	 * Get ID of item from its classes
	 * @param {HTMLCollection} item 
	 * @returns {integer}
	 */
	const getItemIdByClass = (item) => {
		let itemClasses = item.attr("class");
		let itemID;

		let itemClassesArr = itemClasses.split(/\s+/);
		$.each(itemClassesArr, function(index, value){
			if (value.startsWith('menu-item-')) {
				itemID = value.replace("menu-item-", "");
			}
		});

		return itemID;
	}

	/**
	 * Show active item's image in fullscreen menu
	 * 
	 * @param {HTMLCollection} activeMenu current opened sub-menu in fullscreen menu
	 */
	const showActiveItemImage = (activeMenu) => {
		let menuBlock = $('.fullscreen-menu-block');
		let itemID;

		// if current screen has current menu item
		if (activeMenu.find('.current-menu-item').length > 0) {
			itemID = getItemIdByClass(activeMenu.find('.current-menu-item'));			
		}

		// if current screen has current menu parent, but not current menu item 
		if (activeMenu.find('.current-menu-item').length === 0 && activeMenu.find('.current-menu-parent').length > 0) {
			itemID = getItemIdByClass(activeMenu.find('.current-menu-parent'));
		}

		// if current screen has current menu ancestor, but not current menu item 
		if (activeMenu.find('.current-menu-item').length === 0 && activeMenu.find('.current-menu-ancestor').length > 0) {
			itemID = getItemIdByClass(activeMenu.find('.current-menu-ancestor'));
		}

		if (menuBlock.find(`.menu-item-image-${itemID}`).length > 0) {
			menuBlock.find(`.menu-item-image`).removeClass('show');
			menuBlock.find(`.menu-item-image-${itemID}`).addClass('show');
		} else {
			menuBlock.find(`.menu-item-image:eq(0)`).addClass('show');
		}
	}

	/**
	 * Handle click on mobile menu item arrow
	 */
	const handleMobileMenuArrowClick = (event) => {
		let backButton = $(".fullscreen-menu__back-button");
		let menu = $('.main-nav.main-nav--fullscreen');
		let parentItemClasses = $(event.target).parent().attr("class");
		let parentItemClass;

		menu.find('.main-nav-menu--mobile').removeClass("opened");
		$(event.target).closest('.sub-menu').removeClass("opened");
		backButton.removeClass('hidden');

		parentItemClasses = parentItemClasses.split(/\s+/);
		$.each(parentItemClasses, function(index, value){
			if (value.startsWith('menu-item-')) {
				parentItemClass = '.parent-' + value;
			}
		});

		menu.find(`${parentItemClass}`).addClass("opened");

		showActiveItemImage(menu.find(`${parentItemClass}`));

		$('.fullscreen-menu-block').find(".main-nav-menu.opened").find("a").attr('tabindex', null);

		$('.fullscreen-menu-block').find(".main-nav-menu:not(.opened):not(.main-nav-menu--social)").find("a").attr('tabindex', "-1");
	}

	/**
	 * Handle click on mobile menu back button
	 */
	const handleMobileMenuBackButtonClick = () => {		
		let backButton = $(".fullscreen-menu__back-button");
		let menu = $('.main-nav.main-nav--fullscreen');
		let currentMenu = menu.find('.sub-menu.opened');

		if (currentMenu.length === 0) return true;

		let currentMenuClasses = currentMenu.attr("class");
		let currentMenuID;

		let currentMenuClassesArr = currentMenuClasses.split(/\s+/);
		$.each(currentMenuClassesArr, function(index, value){
			if (value.startsWith('parent-menu-item-')) {
				currentMenuID = value.replace("parent-menu-item-", "");
			}
		});
		
		currentMenu.removeClass('opened');
		menu.find(`.menu-item-${currentMenuID}`).closest('.sub-menu').addClass('opened');
		
		showActiveItemImage(menu.find(`.menu-item-${currentMenuID}`).closest('.sub-menu'));

		if (menu.find(`.menu-item-${currentMenuID}`).closest('.main-nav-menu--mobile').length > 0) {
			menu.find(`.menu-item-${currentMenuID}`).closest('.main-nav-menu--mobile').addClass('opened');
			menu.find(`.menu-item-${currentMenuID}`).closest('.main-nav-menu--mobile').siblings('.main-nav-menu--mobile').addClass('opened');
			backButton.addClass('hidden');
			
			showActiveItemImage(menu.find(`.menu-item-${currentMenuID}`).closest('.main-nav-menu--mobile'));
		}

		$('.fullscreen-menu-block').find(".main-nav-menu.opened").find("a").attr('tabindex', null);

	}

	/**
	 * Handle click on mobile menu item with # as href
	 */
	 const handleMobileMenuBlankItemClick = (event) => {
		//event.preventDefault();

		let itemArrow = event.currentTarget.nextElementSibling;

		if (itemArrow) {
			itemArrow.click();
		}

	 }

	/**
	 * Handle hover on desktop menu item with children
	 */
	const handleMenuItemHover = () => {
		let itemsWithChildren = $('.site-header .header .main-nav-menu:not(.main-nav-menu--mobile) li.menu-item-has-children');
		itemsWithChildren.each(function(){
			if (isTouchDevice()) return true;

			let item = $(this);
			let timeoutID;
			item.hover(
				function(){
					clearInterval(timeoutID);
					$(this).addClass('hovered');
				},
				function(){
					timeoutID = setTimeout(() => {
						$(this).removeClass('hovered');
					}, 300)
				}
			)
		})
	}

	/**
	 * Handle click on desktop menu item with children (if no mouse detected)
	 */
	 const handleMenuItemClick = () => {
		//if (!isTouchDevice()) return true;
		let itemsWithChildren = $('.site-header .header .main-nav-menu:not(.main-nav-menu--mobile) li.menu-item-has-children');
		
		itemsWithChildren.each(function(){
			let item = $(this);
			
			item.find('> a, > .menu-item-arrow').on('click', function(e){
				if (e.currentTarget.tagName === "A" && !isTouchDevice()) return true;
				if (item.hasClass('hovered')) { // open link on a second click
					itemsWithChildren.removeClass('hovered');
					item.removeClass('hovered');
					item.parents('li.menu-item-has-children').each(function(){
						$(this).removeClass('hovered');
					})
				} else {
					e.preventDefault();
					itemsWithChildren.removeClass('hovered');
					item.addClass('hovered');
					item.parents('li.menu-item-has-children').each(function(){
						$(this).addClass('hovered');
					})
				}
				
			})
		})
	}

	/**
	 * Load more posts in load-more-button pagination type
	 */
	const loadMorePosts = () => {
		let paginationBlock = $(".pagination");
		let buttonLoadMore = $(".pagination-loadmore");
		let contentSection = $(".content-section__inner");

		buttonLoadMore.click(function(){
 
			let button = $(this);
			let data = {
				'action': 'sunset_loadmore',
				'query': sunset_params.posts, // that's how we get params from wp_localize_script() function
				'page' : sunset_params.current_page
			};
	 
			$.ajax({ // you can also use $.post here
				url : sunset_params.ajaxurl, // AJAX handler
				data : data,
				type : 'POST',
				beforeSend : function ( xhr ) {
					button.prop("disabled", true);
					button.text(button.data('loading-text')); // change the button text, you can also add a preloader image
				},
				success : function( data ){
					if( data ) { 
						button.prop("disabled", false);
						button.text( button.data('more-text') );

						if (contentSection.find(".loop-grid-empty-block").length > 0) {
							contentSection.find(".loop-grid-empty-block:eq(0)").before(data); // insert new posts
						} else {
							contentSection.append(data); // insert new posts
						}
						
						initSimpleBar(); // attach simplebar to new posts

						$(document).trigger('onLoadMorePosts');
						
						sunset_params.current_page++;
	 
						if ( sunset_params.current_page == sunset_params.max_page ) {
							button.remove(); // if last page, remove the button
							paginationBlock.remove(); // if last page, remove the .pagination block
						}
	 
						// you can also fire the "post-load" event here if you use a plugin that requires it
						// $( document.body ).trigger( 'post-load' );
					} else {
						button.remove(); // if no data, remove the button as well
						paginationBlock.remove(); // if last page, remove the .pagination block
					}
				}
			});
		});
	}

	/**
	 * Load more posts in infinite-scroll pagination type
	 */
	const loadMorePostsOnScroll = () => {
		let canBeLoaded = true; // this param allows to initiate the AJAX call only if necessary
		let contentSection = $(".content-section__inner");
	    let spinner = $(".pagination-spinner");
		let paginationBlock = $(".pagination");

		if (spinner.length === 0) return true;
 
		window.addEventListener("scroll", () => {
			let data = {
				'action': 'sunset_loadmore',
				'query': sunset_params.posts,
				'page' : sunset_params.current_page
			};
			if( isInViewport(spinner[0], 100) && canBeLoaded == true ){
				$.ajax({
					url : sunset_params.ajaxurl,
					data:data,
					type:'POST',
					beforeSend: function( xhr ){
						// you can also add your own preloader here
						// you see, the AJAX call is in process, we shouldn't run it again until complete
						canBeLoaded = false;
						spinner.addClass('loading');
					},
					success:function(data){
						if( data ) {
							spinner.removeClass('loading');

							if (contentSection.find(".loop-grid-empty-block").length > 0) {
								contentSection.find(".loop-grid-empty-block:eq(0)").before(data); // insert new posts
							} else {
								contentSection.append(data); // insert new posts
							}

							initSimpleBar(); // attach simplebar to new posts

							$(document).trigger('onLoadMorePosts');

							canBeLoaded = true; // the ajax is completed, now we can run it again
							sunset_params.current_page++;
						} else {
							spinner.remove(); // if no data, remove the button as well
							paginationBlock.remove(); // if no data, remove the .pagination block
						}
					}
				});
			}
		});
	}

	/**
	 * Toggle checkboxes and radiobuttons
	 */
	const toggleCheckboxes = () => {
		let inputs = $('label > [type="checkbox"], label > [type="radio"]');

		const toggleState = (el) => {
			if (el.is(":checked")) {			
				if (el.attr('type') === 'radio') {
					let radioName = el.attr('name');
					$(`input[name="${radioName}"]`).parent().removeClass('checked');
				}
				el.parent().addClass('checked');
			} else {
				el.parent().removeClass('checked');
			}
		}

		inputs.each(function(){
			let input = $(this);
			
			toggleState(input);

			if (input.attr('type') === 'checkbox') {
				input.parent().addClass('has-checkbox');
			} 
			if (input.attr('type') === 'radio') {
				input.parent().addClass('has-radio');
			}
			
			input.on("change", function(){
				toggleState($(this));
			})
			input.on("focus", function(){
				$(this).parent().addClass('focused');
			})
			input.on("blur", function(){
				$(this).parent().removeClass('focused');
			})
		})
	}

	/**
	 * Select2
	 */
	const enableSelect2 = () => {
		let isSelect2Enabled = sunset_params.select2_enable;

		if (isSelect2Enabled) {
			$("select").select2({
				dropdownParent: $('.site-main'),
				allowClear: false
			});
		}
	}

	/**
	 * Build the mobile menu
	 */
	let mobileMenuWasBuilt = false;
	const buildMobileMenu = () => {
		if (mobileMenuWasBuilt) return true;

		let menu = $('.main-nav.main-nav--fullscreen');
		let subMenus = menu.find('.sub-menu');
		let primaryMenus = menu.find('.main-nav-menu--mobile');
		let primaryMenusCount = 1;

		// detach sub-menus from its parents and append them to the parent <ul>
		subMenus.each(function(){
			let subMenu = $(this);
			let parentItem = subMenu.closest('.menu-item');

			if (!parentItem) return true;

			let parentItemID = getItemIdByClass(parentItem);			
			
			subMenu.addClass(`parent-menu-item-${parentItemID}`);
			subMenu.addClass(`main-nav-menu`);
			menu.append(subMenu);
		})

		primaryMenus.each(function(){
			if (primaryMenusCount > 1) {
				$(this).find('li').appendTo(primaryMenus.eq(0));
				$(this).remove();
			}
			primaryMenusCount += 1;
		});

		// Append mobile images to #fullscreen-menu-block
		menu.find('.menu-item-image').each(function(){
			$(this).appendTo($("#fullscreen-menu-block"));
		})

		menu.find("a").attr('tabindex', '-1');

		mobileMenuWasBuilt = true;
	}

	/**
	 * Handle displaying mobile menu images
	 */
	const handleMobileImages = () => {
		let menu = $('.main-nav.main-nav--fullscreen');
		let menuBlock = $('.fullscreen-menu-block');

		menu.find('.menu-item').each(function() {
			let item = $(this);
			let itemID = getItemIdByClass(item);

			if (item.hasClass('current-menu-item') || item.hasClass('current-menu-parent') || item.hasClass('current-menu-ancestor')) {
				menuBlock.find(`.menu-item-image-${itemID}`).addClass('show');
			} else {
				item.hover(
					function() {
						menuBlock.find(`.menu-item-image-${itemID}`).addClass('show');
						menuBlock.find(`.menu-item-image-${itemID}`).css('z-index', '2');
					},
					function() {
						menuBlock.find(`.menu-item-image-${itemID}`).removeClass('show');
					}
				)
			}
		});
		
		showActiveItemImage(menuBlock.find('.main-nav-menu.opened'));
	}

	/**
	 * Place current archive title on center
	 */
	const placeTitleOnCenter = () => {
		const titles = document.querySelector('.heading-section__titles');

		if (!titles) return true;
		
		const currentTitle = titles.querySelector('.title--current');

		if (!currentTitle) return true;

		titles.style.transform = ''; // must clean to get original values on resize!
		let windowWidth = window.innerWidth;
		let currentTitleX = currentTitle.getBoundingClientRect().x;
		let currentTitleWidth = currentTitle.getBoundingClientRect().width;
		let titlesOffsetX = (currentTitleX + currentTitleWidth / 2 - windowWidth / 2) * -1;
		titles.style.transform = `translateX(${titlesOffsetX}px)`;
	}

	/**
	 * Fullfill posts query block with empty items (to prevent last item stretching)
	 */
	const fillEmptyItems = () => {
		let blockPosts = $('.wp-block-post-template');

		blockPosts.each(function() {
			let block = $(this);
			let blockPostsClasses = block.attr('class').split(/\s+/);
			let columnsCount = 1;
			$.each(blockPostsClasses, function(index, value){
				if (value.startsWith('columns-')) {
					columnsCount = value.split("-")[1];
				}
			});
			for (let i = 0; i < (columnsCount - 1); i += 1) {
				block.append('<li class="loop-grid-empty-block"></li>');
			}
		})
	}

	const removePipesFromTermsBlock = () => {
		let termsBlock = $(".wp-block-post-terms");

		termsBlock.each(function(){
			let elem = $(this);
			elem.html(elem.html().replaceAll("|",''));
		})
	}

	const handleTOCItemClick = (event) => {
		event.preventDefault();

		const content = $('.content-section__inner');
		let text = $(event.target).text();

		if (content.find(`:header:contains('${text}')`).length > 0) {
			$([document.documentElement, document.body]).animate({
				scrollTop: content.find(`:header:contains('${text}')`).eq(0).offset().top - getStickyHeaderOffset()
			}, sunset_params.animation_speed);
		}
	}

	/**
	 * Init SimpleBar
	 */
	const initSimpleBar = () => {
		Array.prototype.forEach.call(
			document.querySelectorAll(`
			.fullscreen-menu-block__inner
			`),
			el => new SimpleBar(el)
		);

		// make topbar draggable by mouse and by touch
		if (document.querySelector('.topbar:not(.topbar--runline) .topbar__inner'))
			new SimpleBar(document.querySelector('.topbar:not(.topbar--runline) .topbar__inner'), {classNames: {contentWrapper: 'dragscroll'}})
		
		// make posts tags draggable and scrollable
		Array.prototype.forEach.call(
			document.querySelectorAll(`
			.content-section--with-primary-post .content-section__inner > *.aside-posts .loop-post__tags
			`),
			el => new SimpleBar(el, {classNames: {contentWrapper: 'dragscroll'}})
		);

		// make posts categories draggable and scrollable
		Array.prototype.forEach.call(
			document.querySelectorAll(`
			.content-section--with-primary-post .content-section__inner > *.aside-posts .loop-post__categories
			`),
			el => new SimpleBar(el, {classNames: {contentWrapper: 'dragscroll'}})
		);
		
		// make related posts draggable and scrollable in slider mode
		Array.prototype.forEach.call(
			document.querySelectorAll(`
			.related-posts.related-posts--slider .related-posts__inner
			`),
			el => {

				// handle mousewheel scroll event too
				if (!isTouchDevice()) {
					new SimpleBar(el, {classNames: {contentWrapper: 'dragscroll'}});
					el.onwheel = (event) => {
						event.preventDefault();
						let elementToScroll = el.querySelector('.dragscroll');
						let itemWidth = el.querySelector('.loop-post').clientWidth;
					
						clearTimeout(elementToScroll.timer);
						elementToScroll.timer = setTimeout(() => {
							elementToScroll.scrollTo({ left: event.deltaY > 0 ? elementToScroll.scrollLeft + itemWidth : elementToScroll.scrollLeft - itemWidth, behavior: 'instant' });
						}, 20);
					};
				} else {
					new SimpleBar(el);
				}
			}
		);

		dragscroll.reset();
	}

	/**
	 * detect wrap on loop posts
	 */
	const setLoopPostsWrappedClasses = () => {
		$('.content-section--full-width .loop-post').each(function(){
			let postId = $(this).attr("id");
			setWrappedClasses(`#${postId} .loop-post__inner > *`, '.loop-post');
		})
	}

	/**
	 * detect wrap on posts headings
	 */
	 const setHeadingsWrappedClasses = () => {
		$('.heading-section--split.with-image > * > *').each(function(){
			setWrappedClasses(`.heading-section--split.with-image > * > *`, '.heading-section--split');
		})
	}

	/**
	 * detect wrap on content with sidebar
	 */
	 const setContentWrappedClasses = () => {
		$('body.has-sidebar .site-content > *').each(function(){
			setWrappedClasses(`body.has-sidebar .site-content > *`, 'body.has-sidebar .site-content');
		})
	}

	/**
	 * detect wrap on content with aside posts
	 */
	 const setAsidePostsWrappedClasses = () => {
		$('.content-section--with-primary-post .content-section__inner > *:nth-last-child(-n+2)').each(function(){
			setWrappedClasses(`.content-section--with-primary-post .content-section__inner > *:nth-last-child(-n+2)`, '.content-section--with-primary-post .content-section__inner');
		})
	}

	/**
	 * Init Sticky Sidebar
	*/
	const initStickySidebar = () => {
		let offsetTop = getStickyHeaderOffset();

		let stickySidebars = $(`		
			.post-sidebar-sticky--left .sidebar-post--left .sidebar__inner,
			.post-sidebar-sticky--right .sidebar-post--right .sidebar__inner,
			.blog-sidebar-sticky--left .sidebar-blog--left .sidebar__inner,
			.blog-sidebar-sticky--right .sidebar-blog--right .sidebar__inner
		`);

		const contentSection = $('.content-section__inner');

		if (!contentSection[0]) return true;

		let windowHeight = $(window).height();
		
		// set top offset for the sidebar if header is sticky (to prevent overlap)
		const setTopOffset = () => {
			let contentBottom = contentSection[0].getBoundingClientRect().bottom;
			let contentTop = contentSection[0].getBoundingClientRect().top;
			
			if ($('body').hasClass('scroll-up')) { // if scrolling up
				
				if (contentBottom > windowHeight && contentTop < 0) { // if not reaches to the bottom of content 
					stickySidebars.css('transform', 'translate3d(0, ' + offsetTop + 'px, 0)');
				}
				if (contentTop > 0) { // if reaches top of the content
					if (contentTop < offsetTop) { // if there's a gap between header height and content
						stickySidebars.css('transform', 'translate3d(0, ' + (offsetTop - contentTop) + 'px, 0)');
					} else {
						stickySidebars.css('transform', 'translate3d(0, 0, 0)');
					}
					
				}
			} else {
				stickySidebars.css('transform', 'translate3d(0, 0, 0)');
			}
		}
		setTopOffset();

		$(window).on('scroll', function(){
			setTopOffset();
		})

		if ( contentSection.outerHeight() > stickySidebars.outerHeight() && !$('.site-content').hasClass('was-wrapped') ) {
			stickySidebars.sticky(
				{
					defaultPosition: 'hidden',
					offsetBottom: 1
				}
			);
		}
	}

	/**
	 * Init Lightbox
	*/
	const initLightbox = () => {
		let isLightboxEnabled = sunset_params.lightbox_enable;

		if (isLightboxEnabled) {
			lightbox.option({
				'resizeDuration': sunset_params.animation_speed,
				'fadeDuration': sunset_params.animation_speed,
				'imageFadeDuration': sunset_params.animation_speed,
				'showImageNumberLabel': false,
				'wrapAround': true,
				'alwaysShowNavOnTouchDevices': true,
				'disableScrolling': true,
			})

			let singleImages = $('.content-section__inner a[href*=".jpg"] > img, .content-section__inner a[href*=".jpeg"] > img, .content-section__inner a[href*=".png"] > img, .content-section__inner a[href*=".heic"] > img, .content-section__inner a[href*=".svg"] > img, .content-section__inner a[href*=".gif"] > img, .content-section__inner a[href*=".webp"] > img');
			let galleryImages = $('.wp-block-gallery a[href*=".jpg"] img, .wp-block-gallery a[href*=".jpeg"] img, .wp-block-gallery a[href*=".png"] img, .wp-block-gallery a[href*=".heic"] img, .wp-block-gallery a[href*=".svg"] img, .wp-block-gallery a[href*=".gif"] img, .wp-block-gallery a[href*=".webp"] img');

			singleImages.each(function(index){
				let img = $(this);
				let link = img.closest('a');
				let alt = img.attr('alt');
				let caption = img.attr('alt');

				link.attr('data-lightbox', `image-${index}`);

				if (alt) {
					link.attr('data-alt', `${alt}`);
				}
			})
			galleryImages.each(function(index){
				let img = $(this);
				let link = img.closest('a');
				let galleryIndex = link.closest('.wp-block-gallery').index();
				let alt = img.attr('alt');
				let caption = link.siblings('figcaption').html();

				link.attr('data-lightbox', `image-gallery-${galleryIndex}`);	
				
				if (alt) {
					link.attr('data-alt', `${alt}`);
				}

				if (caption) {
					link.attr('data-title', `${caption}`);
				}
			})
		}
	}

	/**
	 * Creates masonry grid
	 * @see https://css-tricks.com/a-lightweight-masonry-solution/
	 * @param {string} selector css selector for the parent element of masonry grid
	 */
	const initMasonryGrid = (selector) => {
		let grids = [...document.querySelectorAll(selector)];

		if(grids.length && getComputedStyle(grids[0]).gridTemplateRows !== 'masonry') {
			grids = grids.map(grid => ({
				_el: grid, 
				gap: parseFloat(getComputedStyle(grid).gridRowGap), 
				items: [...grid.childNodes].filter(c => c.nodeType === 1), 
				ncol: 0
			}));

			function layout(grids) {
				grids.forEach(grid => {
					/* get the post relayout number of columns */
					let ncol = getComputedStyle(grid._el).gridTemplateColumns.split(' ').length;

					/* if the number of columns has changed */
					if(grid.ncol !== ncol) {
						/* update number of columns */
						grid.ncol = ncol;

						/* revert to initial positioning, no margin */
						grid.items.forEach(c => c.style.removeProperty('margin-top'));

						/* if we have more than one column */
						if(grid.ncol > 1) {
							grid.items.slice(ncol).forEach((c, i) => {
								let prev_fin = grid.items[i].getBoundingClientRect().bottom /* bottom edge of item above */, 
										curr_ini = c.getBoundingClientRect().top /* top edge of current item */;
								
								c.style.marginTop = `${prev_fin + grid.gap - curr_ini}px`
							})
						}
					}
				})
			}
			layout(grids);
		}
	}

	const removeNovalidationFromCommentForm = () => {
		if ($("#commentform").length > 0)
			$("#commentform").removeAttr("novalidate");
	}

	// Add event listener to the 'keydown' event on the document
	document.addEventListener("keydown", function (e) {
		const target = e.target;
		const shiftPressed = e.shiftKey;
	
		// If TAB key pressed
		if (e.keyCode === 9) {
			// If inside a fullscreen menu (determined by attribute #fullscreen-menu-block)
			if (target.closest('#fullscreen-menu-block')) {
				// Find the first or the last input element in the dialog parent (depending on whether Shift was pressed).
				// Get the focusable elements (links and buttons)
				let focusElements = target
				.closest('#fullscreen-menu-block')
				.querySelectorAll("a[href], button");
				let borderElem = shiftPressed
				? focusElements[0]
				: focusElements[focusElements.length - 1];
		
				if (borderElem) {
				// If the current target element is the first or last focusable element in the dialog, prevent the default behaviour.
				if (target === borderElem) {
					e.preventDefault();
		
					// move focus to the first element when the last one is reached and vice versa
					borderElem === focusElements[0]
					? focusElements[focusElements.length - 1].focus()
					: focusElements[0].focus();
				}
				}
			}
		}
	});

	/**
	 * Load functions
	 */
	const onLoadFunctions = () => {
		console.log('onLoadFunctions')
		initSimpleBar();
		initLightbox();
		getScrollbarWidth();
		setVwVh(); // run again to get more accurate values
		setHeaderWrappedClasses();
		setFooterWrappedClasses();
		setCopyrightWrappedClasses();
		setLoopPostsWrappedClasses();
		setHeadingsWrappedClasses();
		setContentWrappedClasses();
		setAsidePostsWrappedClasses();
		stickyHeaderOnScrollUp();
		setHeaderSearch();
		setHeights();
		setSidebarWidth();
		toggleTOC();
		toggleHeaderBackground();
		loadMorePosts();
		loadMorePostsOnScroll();
		toggleCheckboxes();
		buildMobileMenu();
		handleMobileImages();
		enableSelect2();
		initRunlineFunctions();
		fillEmptyItems();
		removePipesFromTermsBlock();
		handleMenuItemHover();
		handleMenuItemClick();
		placeTitleOnCenter();
		initStickySidebar();
		zoomImageOnScroll('.heading-section.heading-section--cover .wp-post-image');
		initMasonryGrid('.content-section--grid.content-section--grid-fluid .content-section__inner');
		initMasonryGrid('.wp-block-gallery.has-nested-images.is-style-sunset-gallery-chaotic');
		removeNovalidationFromCommentForm();
	}

	/**
	 * Functions running on scroll
	 */
	const onScrollFunctions = () => {
		toggleTOC(true);
		toggleHeaderBackground();
		zoomImageOnScroll('.heading-section.heading-section--cover .wp-post-image');
		detectAnimationElements(document.querySelectorAll('.sunset-animation, .content-section--blog .content-section__inner > *'));
	}

	/**
	 * Functions running on window resize
	 */
	const onResizeFunctions = () => {
		console.log('onResizeFunctions')
		zoomImageOnScroll('.heading-section.heading-section--cover .wp-post-image');
		getScrollbarWidth();
		setVwVh();
		setHeaderWrappedClasses();
		setFooterWrappedClasses();
		setCopyrightWrappedClasses();
		setLoopPostsWrappedClasses();
		setHeadingsWrappedClasses();
		setContentWrappedClasses();
		setAsidePostsWrappedClasses();
		stickyHeaderOnScrollUp();
		setHeaderSearch();
		setHeights();
		setSidebarWidth();
		toggleTOC();
		toggleHeaderBackground();
		initRunlineFunctions();
		placeTitleOnCenter();
		//initStickySidebar();
		initMasonryGrid('.content-section--grid-fluid .content-section__inner');
		initMasonryGrid('.wp-block-gallery.has-nested-images.is-style-sunset-gallery-chaotic');
	}
	

	/**
	 * Attach events
	 */
	onLoadFunctions();

	const burger = document.querySelector('.site-header .main-nav > .burger');
	const burgers = document.querySelectorAll('.burger');
	const searchButton = document.querySelector('.header-search-button');
	const mobileMenuBackButton = document.querySelector('.fullscreen-menu__back-button');
	const mobileMenuBlankItems = document.querySelectorAll('.main-nav.main-nav--fullscreen .menu-item > a[href="#"]');
	const mobileMenuArrows = document.querySelectorAll('.menu-item-arrow');
	const TOCItems = document.querySelectorAll('.post__contents__headline--no-anchor > a');
	const anchorLinks = document.querySelectorAll('a[href*="#"]');
	
	let resizeTimeout;
	
	if (burgers) {
		for (let i = 0; i < burgers.length; i += 1) {
			burgers[i].addEventListener('click', handleBurgerClick);
		}
	}

	if (searchButton) searchButton.addEventListener('click', handleSearchIconClick);

	if (mobileMenuBackButton) mobileMenuBackButton.addEventListener('click', handleMobileMenuBackButtonClick, true);

	if (mobileMenuArrows) {
		for (let i = 0; i < mobileMenuArrows.length; i += 1) {
			mobileMenuArrows[i].addEventListener('click', handleMobileMenuArrowClick);
		}
	}

	if (mobileMenuBlankItems) {
		for (let i = 0; i < mobileMenuBlankItems.length; i += 1) {
			mobileMenuBlankItems[i].addEventListener('click', handleMobileMenuBlankItemClick);
		}
	}

	if (TOCItems) {
		for (let i = 0; i < TOCItems.length; i += 1) {
			TOCItems[i].addEventListener('click', handleTOCItemClick);
		}
	}

	if (anchorLinks) {
		for (let i = 0; i < anchorLinks.length; i += 1) {
			anchorLinks[i].addEventListener('click', handleAnchorLinkClick);
		}
	}

	const actualResizeHandler = () => {
		let burgerClasses = burger.classList.value;

		// handle the resize event
		// check if resize not caused by burger click (because of the scrollbar offset)
		if (burgerClasses === burger.classList.value) {			
			onResizeFunctions();
		} else {
			burgerClasses = burger.classList.value;
		}
	}

	let width = window.innerWidth;
	const resizeThrottler = () => {		
		if (window.innerWidth !== width) {
			// ignore resize events as long as an actualResizeHandler execution is in the queue
			if ( !resizeTimeout ) {
				resizeTimeout = setTimeout(function() {
					resizeTimeout = null;
					actualResizeHandler();
		
					// The actualResizeHandler will execute after animations are done
				}, sunset_params.animation_speed);
			}
			width = window.innerWidth;
		}
	}
	
	window.addEventListener("scroll", onScrollFunctions, false);
	window.addEventListener("resize", resizeThrottler, false);
	  
	$(document).on('onLoadMorePosts', e => {
		console.log('onLoadMorePosts')
		setTimeout(() => {
			initMasonryGrid('.content-section--grid.content-section--grid-fluid .content-section__inner');
		}, 100);
		
	})
	
	if ($('#sunset-preloader').length > 0) { // if preloader enabled, first hide preloader, then set body to loaded
		$('#sunset-preloader').addClass('loaded');

		setTimeout(() => {
			document.body.classList.add('loaded');
		}, sunset_params.animation_speed * 2);
	} else {
		document.body.classList.add('loaded');
	}
	
});

window.onload = function() {
    if (window.jQuery) { 
        jQuery(document).on('onLoadMorePosts', e => {
            detectAnimationElements(document.querySelectorAll(`
                .sunset-animation, 
                .content-section--blog .content-section__inner > *
            `));
            initCursor(); // re-attach hover events for custom cursor
            customCursorHover();
        });
    }
}