(function ($, root, undefined) {

	$(function () {

		'use strict';

		// DOM ready, take it away

		/* ========================================================================== */
		/*                                  VARIABLES                                 */
		/* ========================================================================== */

		/* -------------------------------- geometry -------------------------------- */

		const vw = $(window).width()
		const wow = window.outerWidth
		const wiw = window.innerWidth
		const bw = $('body').width()

		const wih = window.innerHeight
		const vh = $(window).height()


		const desktophomemargin = $(".header-1")[0].getBoundingClientRect().width


		// height of scrollbar at bottom
		const bottomScrollHeight = (_ => {
			if (wih / vh > 1.5) {
				return 0
			} else {
				let bs = wih - vh
				return bs
			}
		})()

		const cssWidths = {
			vw: vw,
			wow: wow,
			wiw: wiw,
			bw: bw,
			desktophomemargin: desktophomemargin,
			wih: wih,
			vh: vh,
			bottomScrollHeight: bottomScrollHeight
		}
		console.log(cssWidths)


		/* --------------------------- css values to vars --------------------------- */
		//isMobile
		const isMobile = (_ => {
			if (wow < 769 || wiw < 769) {
				//mobile settings
				$('.social-link, .events-link').addClass('hidden')
				return true

			} else {
				return false
			}
		})()

		const isTablet = (!isMobile && (wow < 1024 && wiw < 1024)) ? true : false

		/**
		 * Checks if body has a class
		 * @param {string} classname The class to check
		 * @param {string} notclassname Optional: this classname makes it false
		 * @returns {boolean} True if body has that class, false if not OR it contains the notclassname
		 */
		function bodyHasClass(classname, notclassname) {
			if ($('body').hasClass(classname)) {
				if (notclassname) {
					if ($('body').hasClass(notclassname)) {
						return false
					} else {
						return true
					}
				} else {
					return true
				}
			} else {
				return false
			}
		}

		//isHome
		const isHome = bodyHasClass('home')

		//isArchive
		const isArchive = bodyHasClass('archive', 'category-esemeny')

		//isSearch
		const isSearch = bodyHasClass('search-results')

		//isSearchNoResults
		const isSearchNoResults = bodyHasClass('search-no-results')

		//isEsemeny
		const isEsemeny = bodyHasClass('category-esemeny')

		//isSingle
		const isSingle = bodyHasClass('single')

		// Masonrypage: archive, home or search results
		var isMasonryPage = isArchive || isHome || isSearch || isSearchNoResults


		/* ========================================================================== */
		/*                                  FUNCTIONS                                 */
		/* ========================================================================== */


		var rotateMenuButton = function () {
			if ($(".menubutton button").hasClass("rotated")) {
				$(".menubutton button").removeClass("rotated");
			} else {
				$(".menubutton button").addClass("rotated");
			}
		}

		var showHideSocial = function () {
			if (isMobile && $('.social-link').hasClass('hidden')) {
				$('.social-link, .events-link').removeClass('hidden')
			} else if (isMobile) {
				$('.social-link, .events-link').addClass('hidden')
			}
		}

		function convertRemToPixels(rem) {
			return rem * parseFloat(getComputedStyle(document.documentElement).fontSize);
		}

		/* ========================================================================== */
		/*                                   SEARCH                                   */
		/* ========================================================================== */

		// on mobile add to sidebar:
		if (isMobile) {
			$(".search-bar").prependTo("#sidebar-wrapper")
		}

		//clicking on desktop
		if (!isMobile) {
			$(".search-box button").click(function (e) {
				// e.preventDefault()
				var bar = $(this).next(".search-bar")
				if (bar.hasClass("opensearch")) {
					//if search is opened close:
					bar.stop().animate({ width: "0" }, 400, function () {
						bar.hide().removeClass("opensearch")
					})
				} else {
					//if it's closed open:
					bar.show().stop().animate({ width: wiw - (desktophomemargin * 2) }, 400, function () {
						bar.addClass("opensearch")
						$(".search-input").focus()
					})
					// console.log("calc(100% - " + (desktophomemargin * 2) + "px)")
				}

			})
		}

		/* ========================================================================== */
		/*                                    MENU                                    */
		/* ========================================================================== */

		var menuWidth = wow

		if (isTablet) {
			menuWidth = 350
		}
		if (!isMobile && !isTablet) {
			menuWidth = 500
		}

		$("#sidebar").simplerSidebar({

			selectors: {
				trigger: "#toggle-sidebar",
				quitter: "#toggle-sidebar"
			},
			sidebar: {
				width: menuWidth
			},
			mask: {
				display: false,
				css: {
					backgroundColor: "black",
					opacity: 1,
					filter: "Alpha(opacity=100)" // IE opacity fix
				}
			},
			gap: 0,
			events: {
				on: {
					animation: {
						both: rotateMenuButton

					}
				},
				callbacks: {
					animation: {
						both: showHideSocial,
						freezePage: false
					}
				}
			}

		});


		/* -------------------------------------------------------------------------- */
		/*                               HOME & ARCHIVES                              */
		/* -------------------------------------------------------------------------- */


		/* ------------------------------- no results ------------------------------- */


		if (isMasonryPage && $("article").hasClass('no-result')) {
			$('body').addClass("no-result")
			if (!isMobile) {
				$('article.no-result h2').appendTo('.archivetitle')
				$('article.no-result').hide()
			}
		}


		/* ----------------------------- css on desktop ----------------------------- */

		/* ------------------------------ wrap articles ----------------------------- */

		if (!isMobile) {
			if (isMasonryPage) {
				//no overflowY
				$('html').css({ overflowY: "hidden" })

				//calculate wrappable elements
				$('#content>*:not(.misha_loadmore)').addClass("hbox")
				var wrapArticles = $(".hbox").length

				//wrapping for big-small difference
				if (isHome) {
					$('.hbox:first-child').wrap('<div class="home_wrapper-big home_wrapper-1"></div>').addClass("home-big")
					$('.hbox:nth-child(2)').wrap('<div class="home_wrapper-big home_wrapper-2"></div>').addClass("home-big")
					wrapArticles = $(".hbox").length - 2
				}

				//add classes to articles and elements
				var articleWrapCounter = 0
				for (let i = 0; i < wrapArticles; i++) {
					var j = i + 1

					if (isHome) {
						j = i + 3
					}

					if (i % 6 == 0) {
						articleWrapCounter++
					}
					//console.log($('.hbox:nth-child(' + j + ')').attr("id"), i, j)
					$('.hbox:nth-child(' + j + ')').addClass("home-small home-thumbnail-small-" + articleWrapCounter)
					//change order if there is a description
					if ($("body").is('.archive, .tag') && articleWrapCounter == 1) {
						if (j == 3 || j == 4) {
							$('.hbox:nth-child(' + j + ')').css({ order: j - 1 })
						} else if (j == 5 || j == 6) {
							$('.hbox:nth-child(' + j + ')').css({ order: j })
						}

					}
				}
				//wrap classes
				for (let i = 0; i < articleWrapCounter; i++) {
					var j = i + 1
					if (isHome) {
						j = i + 3
					}
					var k = i + 1
					$(".home-thumbnail-small-" + k).wrapAll('<div class="home_wrapper-small home_wrapper-' + j + '"></div>')
					if (i == 0) {
						$(".home_wrapper-" + j).addClass("home_wrapper-s1")
					}
				}

				/* -------------------------------- other css ------------------------------- */

				//add bottom scrollbar to div on bottom:
				if (bottomScrollHeight > 0) {
					$(".home_wrapper-big .metadata").css({ bottom: bottomScrollHeight })
				}

				//fit title
				$("body:not(.no-result) .archivetitle h1").fitText(0.7)





			}//isMasonryPage end
		}// !isMobile end

		/* ----------------------------- random cutouts ----------------------------- */

		function random2() {
			const choices = [
				[1, 3],
				[1, 5],
				[1, 6],
				[2, 4],
				[2, 6],
				[3, 4],
				[3, 5],
				[4, 6]
			]
			let nr = Math.floor(Math.random() * choices.length);
			return choices[nr]
		}

		//jquery function, adds random class to 3 random cihldren
		(function ($) {
			$.fn.addRandomClasses = function () {
				let rn = random2()
				for (let i = 0; i < 2; i++) {
					var j = rn[i]
					this.children("article:nth-child(" + j + ")").addClass("random")
				}
				return this
			};
		})(jQuery);


		$(".home_wrapper-small").each(function () {
			$(this).addRandomClasses()
		})


		/* ---------------------------- Cutouts on mobile --------------------------- */

		//add class to odd elems

		function mobileHomeClass() {
			if (isMobile && isMasonryPage) {
				$('article:not(.post_nr):not(.cutOk) ').addClass('cutCurr')
				$('article.cutCurr:nth-child(even)').addClass('cut-even')
				$('article.cutCurr').addClass('cutOk').removeClass('cutCurr')
			}

		}

		mobileHomeClass()

		/* ----------------------------- Snap on mobile ----------------------------- */

		// if (isMobile) {
		// 	if (isMasonryPage) {
		// 		$("article.post").SnapScroll({
		// 			animateDuration: 400
		// 		});
		// 	}
		// }

		/* --------------------------------- To top --------------------------------- */

		$(".totop>a").click(function (e) {
			e.preventDefault()
			$('html, body').stop().animate({ scrollTop: 0 }, 800);
		})

		//hide totop if not needed
		if (!($("main").height() > $(window).height()) && isMobile) {
			$(".totop").hide()
		}


		/* ---------------------------- Scroll on desktop --------------------------- */

		/**
		 * scroll to next or previous section
		 * Ex:
		 * currElem = homeScroll(currElem, "prev")
		 * currElem = homeScroll(currElem, "next")
		 * 
		 * @param {jQuery} target put here currElem
		 * @param {String} direction "next" of "prev"
		 */
		function homeScroll(target, direction) {
			// console.log(target.attr('class'))
			var nextelem;

			if (direction == "next") {
				nextelem = target.next()
			} else {
				nextelem = target.prev()
			}
			if (nextelem.length == 0) {
				nextelem = target
			}

			var offset = ($(nextelem).position().left)

			//if loadmore is the next, do not scroll, but load:
			if (nextelem.attr("class") == "misha_loadmore") {
				loadmore()
				return target
			} else if (isEsemeny) {
				offset = offset - (desktophomemargin)
			} else {
				//from the third wrap modify the offset
				var wNum = parseInt($(nextelem).attr("class").split(" ")[1].split("-")[1])
				console.log(wNum)
				if (wNum == 3) {
					offset = offset - (desktophomemargin / 2)
				} else if (wNum > 3 || !isHome) {
					offset = offset - desktophomemargin
				}
			}
			console.log("scrolling to: " + nextelem.attr("class") + " - offset: " + offset)

			const scrollspeed = isEsemeny ? 500 : 800


			$('html, body, .wrapper').stop().animate({ scrollLeft: offset }, scrollspeed, function () {
				//hide the left arrow if on start
				if (nextelem.is(selector + ':first-child')) {
					$(".header-scroll-left").hide()
				} else {
					$(".header-scroll-left").show()
				}
			});
			return nextelem;
		}

		//extractDelta(e): extract the scroll direction and length from an event
		function extractDelta(e) {
			if (e.wheelDelta) {
				return e.wheelDelta;
			}

			if (e.originalEvent.detail) {
				return e.originalEvent.detail;
			}

			if (e.originalEvent.deltaY) {
				return e.originalEvent.deltaY * -1;
			}

			if (e.originalEvent && e.originalEvent.wheelDelta) {
				return e.originalEvent.wheelDelta;
			}
		}

		const selector = isEsemeny ? 'main>section>article' : 'main>#content>div'

		var currElem = $(selector + ':first-child')

		//checking the current scroll location for refresh:
		if (!isMobile) {
			if (isMasonryPage || isEsemeny) {
				const homeDivWidths = []
				const homeFullWidths = []
				homeDivWidths[0] = 0

				$(selector).each(function () {
					homeDivWidths.push($(this)[0].getBoundingClientRect().width)
				})
				for (let i = 0; i < homeDivWidths.length; i++) {
					let prev = homeFullWidths[i - 1]
					if (i == 0) {
						prev = 0
					}
					homeFullWidths[i] = homeDivWidths[i] + prev
				}
				// console.log(homeDivWidths)
				// console.log(homeFullWidths)

				var currscroll = $('html').scrollLeft()

				var closest = homeFullWidths.reduce(function (prev, curr) {
					return (Math.abs(curr - currscroll) < Math.abs(prev - currscroll) ? curr : prev);
				});
				var scrollnr = homeFullWidths.indexOf(closest) + 1


				currElem = $(selector + ':nth-child(' + scrollnr + ')')

				if (scrollnr == 1) {
					$(".header-scroll-left").hide()
				}

				// console.log("currscroll", currscroll, "scrollnr", scrollnr, "closest", closest)
				console.log("start location: " + currElem.attr("class"))




			}
		}

		var scrolltimer = false;
		$(window).on('wheel DOMMouseScroll', function (e) {
			//e.preventDefault();
			if (!isMobile) {
				if (isMasonryPage || isEsemeny) {
					if (scrolltimer) {
						return false;
					}
					scrolltimer = true;
					setTimeout(() => {
						scrolltimer = false;
					}, 500);

					var wd = extractDelta(e)

					if (wd > 0) {
						currElem = homeScroll(currElem, "prev")
					}
					else {
						currElem = homeScroll(currElem, "next")
					}
				}
			}
		});

		/* -------------------------- scroll click on home -------------------------- */
		$(".header-scroll-left button").click(() => {
			currElem = homeScroll(currElem, "prev")
		})
		$(".header-scroll-right button").click(() => {
			currElem = homeScroll(currElem, "next")
		})

		/* --------------------------- scroll with keyboard --------------------------- */
		var kd = false
		$('html *:not(input)').keydown(function (event) {
			if (kd) {
				event.preventDefault();
				return
			} else {
				if (!isMobile) {
					if (isMasonryPage) {
						if (!$('.search-bar *').is(':focus')) {
							// console.log("keydown!")
							kd = true

							switch (event.which) {
								case 40: //down
								case 39: //right
								case 74: //J
									event.preventDefault();
									currElem = homeScroll(currElem, "next")
									break;
								case 38: //up
								case 37: //left
								case 75: //K
									event.preventDefault();
									currElem = homeScroll(currElem, "prev")
									break;

								default:
									break;
							}
						}

					}
				}
			}
		})

		//check for keyup for disabling counter
		$('html *:not(input)').keyup(function (event) {
			if (!isMobile) {
				if (isMasonryPage) {
					if (!$('.search-bar *').is(':focus')) {
						kd = false
					}
				}
			}
		})

		/* -------------------------- loadmore: ajax loads -------------------------- */

		$('.misha_loadmore').on("moreload-start", function () {
			currElem = $(this).prev()
			console.log("currelem: " + currElem.attr("class"))

		})

		$('.misha_loadmore').on("moreload-finish", function (e, scroll) {

			//wrap new elements on load
			articleWrapCounter++
			var wrapnum = articleWrapCounter + 2

			if (isMobile) {
				mobileHomeClass()
			} else {
				$("#content>article")
					.addClass("home-small home-thumbnail-small-" + articleWrapCounter)
					.wrapAll('<div class="home_wrapper-small home_wrapper-' + wrapnum + '"></div>')
				$(".home_wrapper-" + wrapnum).addRandomClasses()
			}

			//Scroll to new element
			if (scroll) {
				currElem = homeScroll(currElem, "next")
			}

		})

		/* ----------------------------- loadmore click ----------------------------- */
		var touched = false
		$('.misha_loadmore')//.click(function (e) {
			.on('touchstart', function (e) {
				touched = true
			})
			.on('touchend', function (e) {
				touched = false
				e.preventDefault()
				loadmore($(this), false)
			})
			.on('mouseup', function (e) {
				if (touched) {
					return
				}
				e.preventDefault()
				loadmore($(this))
			})

		var noMoreAjax = false

		function loadmore(element, scroll = true) {
			if (noMoreAjax) {
				// console.log("no more ajax")
				return false
			}
			// var button = $(this),
			var button = element || $('.misha_loadmore'),
				data = {
					'action': 'loadmore',
					'query': misha_loadmore_params.posts, // that's how we get params from wp_localize_script() function
					'page': misha_loadmore_params.current_page
				};
			// button.trigger("moreload-start")

			$.ajax({ // you can also use $.post here
				url: misha_loadmore_params.ajaxurl, // AJAX handler
				data: data,
				type: 'POST',
				beforeSend: function (xhr) {

					button.html('<p>Betöltés...</p>'); // change the button text, you can also add a preloader image
				},
				success: function (data) {
					if (data) {
						if (data.length < 102) {
							button.children().remove(); // if last page, remove the button
							noMoreAjax = true
							return false
						}

						// console.log(data.length)

						button.html('<a>Mutass többet</a>').before(data); // insert new posts
						misha_loadmore_params.current_page++;
						button.trigger("moreload-finish", scroll)
						// console.log("loading:", data.length)

						// you can also fire the "post-load" event here if you use a plugin that requires it
						// $( document.body ).trigger( 'post-load' );

					} else {
						button.children().remove(); // if no data, remove the button as well
						noMoreAjax = true
						// console.log("no data")
					}
				}
			});
		}

		/* ------------------------- Click on small articles ------------------------ */

		$('article.home-small').click(function () {
			let href = $(this).children('a.thumbnailwrapper').attr("href")
			window.open(href, "_self")
		})

		/* ------------------------------ hover on home ----------------------------- */



		const metadataHeights = {}

		//hover on big articles

		$(".home-big h2 a").hover(function () {
			bigArticleHoverShow($(this))

		}, function () {

			let cc = $(this)
			let cArticle = cc.parents("article")
			let cMetadata = cArticle.children(".metadata")

			//remove hovered class
			cArticle.removeClass("hovered")

			//remove tag from header and body
			let headerClasses = $(".header-1").attr("class").split(" ")
			var hoverClass = findClassByStart(headerClasses, "hover")
			$("body, .header-1, .header-2").removeClass(hoverClass)

			//transparent metadata
			cMetadata.children(".alcimWrapper, .bevezetoWrapper").addClass("transparent")

			//animate height change
			cMetadata.stop().animate({ height: metadataHeights.collapsedHeight }, 400, _ => {
				//hide and show metadata
				cMetadata.children(".alcimWrapper, .bevezetoWrapper").css({ display: 'none' }).removeClass("transparent")
				cMetadata.children(".categories, .postedon").removeClass("transparent").show()
			})
		})


		function bigArticleHoverShow(cc) {
			// let cc = $(this)
			let cArticle = cc.parents("article")
			let cMetadata = cArticle.children(".metadata")
			let cBevezetoWrapper = cMetadata.children(".bevezetoWrapper")
			let cBevezeto = cBevezetoWrapper.children(".bevezeto")

			// calculate default metadata height
			if (!metadataHeights.collapsedHeight) {
				metadataHeights.collapsedHeight = cMetadata[0].getBoundingClientRect().height
			}

			//calculate opened metadata height
			if (!metadataHeights.openedHeight) {
				let h2H = 0
				$(".home-big h2").each(function () {
					if ($(this)[0].getBoundingClientRect().height > h2H) {
						h2H = $(this)[0].getBoundingClientRect().height
					}
				})

				let artH = cArticle[0].getBoundingClientRect().height
				metadataHeights.openedHeight = artH - bottomScrollHeight - h2H

				console.log('h2h', h2H, artH)

				//add height to bevezetoWrapper
				$('.bevezetoWrapper').css({ height: metadataHeights.openedHeight })

				$('.alcimWrapper').css({ height: metadataHeights.openedHeight })
			}

			//add hovered class
			cArticle.addClass("hovered")

			//add tag to header for bg
			let artClasses = cArticle.attr("class").split(" ")
			let theTag = findClassByStart(artClasses, "tag")
			$("body, .header-1, .header-2").addClass("hover-" + theTag)

			//transparent metadata
			cMetadata.children(".categories, .postedon").addClass("transparent")

			//animate border
			cMetadata.stop().animate({ height: metadataHeights.openedHeight }, 400, _ => {

				//hide metadata
				cMetadata.children(".categories, .postedon").hide().removeClass("transparent")
				cMetadata.children(".bevezetoWrapper").show()
				cMetadata.children(".alcimWrapper").css({ display: 'flex' })

				//set height for ellipsis
				if (!metadataHeights.bevezetoHeight) {
					metadataHeights.bevezetoHeight = cBevezetoWrapper.height()
					let bWidth = cBevezetoWrapper.width()
					// let bWidth = cBevezetoWrapper[0].getBoundingClientRect().width
					$('.bevezeto').css({
						height: metadataHeights.bevezetoHeight,
						width: bWidth + 'px'
					})
					$('.alcim').css({
						height: metadataHeights.bevezetoHeight,
					})

				}

				//show bev+alcim
				cMetadata.children(".bevezetoWrapper, .alcimWrapper").removeClass("transparent")


				//clamp bevezető
				let ellipsis = new Ellipsis(cBevezeto[0]);
				ellipsis.calc();
				ellipsis.set();
			})
		}

		if (!isMobile && isHome) {
			setTimeout(() => {
				bigArticleHoverShow($(".home_wrapper-1 .home-big h2 a"))
			}, 2000);
		}



		/**
		 * finds a name of a class, from the first element 
		 * @param {Array} classlist the list of classes to search from as an array
		 * @param {String} startString the string to search for
		 * @param {String} sep the separator that separates the startString from the rest of the classname
		 */
		function findClassByStart(classlist, startString, sep = "-") {
			var fullstring
			for (let i = 0; i < classlist.length; i++) {
				let curr = classlist[i].split(sep)
				if (curr[0] == startString) {
					fullstring = classlist[i]
				}
			}
			return fullstring
		}

		//hover on small articles
		function showTitle(th) {
			if (!$('body').hasClass('no-result')) {
				$(th).children("h2").show()
				$(th).children(".metadata").addClass("vis")
			}

		}

		function hideTitle(th) {
			if (!$('body').hasClass('no-result')) {
				$(th).children("h2").hide()
				$(th).children(".metadata").removeClass("vis")
			}

		}

		$(document).on({
			mouseenter: function () {
				if (!Modernizr.touchevents) {
					showTitle(this)
				}
			},
			mouseleave: function () {
				if (!Modernizr.touchevents) {
					hideTitle(this)
				}
			}
		}, '.home-small');

		//touch on small articles
		$(document).on({
			'touchend': function (e) {
				e.preventDefault()
				var art = $(this).parents("article")
				var metadata = art.children(".metadata")
				if (metadata.hasClass("vis")) {
					hideTitle(art)
				} else {
					hideTitle($(".vis").parents("article"))
					showTitle(art)
				}
			}
		}, ".home-small a.thumbnailwrapper")


		/* -------------------------------------------------------------------------- */
		/*                             EVENTS - ESEMÉNYEK                             */
		/* -------------------------------------------------------------------------- */

		if (isEsemeny) {
			if (!isMobile) {
				$('html').css({ overflowY: "hidden" })
			}
		}


		/* -------------------------------------------------------------------------- */
		/*                                CIRCULAR TEXT                               */
		/* -------------------------------------------------------------------------- */

		const bedoListItems = ".wrapper .header #tag-nav ul li"
		const bedoWords = bedoListItems + " a"
		const bedoLetters = bedoWords + " span"


		//move subs to wrapper
		$(bedoListItems).each(function () {
			let itemId = $(this).attr("id")
			let tagClass = $(this).attr("class").split(" ")
			let itemClass = findClassByStart(tagClass, 'tag')

			// add wrapper div
			// $(".sub-wrapper").append('<div id="' + itemId + '" class="bedo-sub-wrapper ' + itemClass + '"></div>')

			// add tag title
			// $(this).children("a").clone().appendTo(".sub-wrapper #" + itemId)

			//add sub text
			// $(this).children("span").appendTo(".sub-wrapper #" + itemId)

			//add circle
			// $(".sub-wrapper #" + itemId + " span").append('<div class="circle">')
		})

		//wrap each letter to spans
		var charnum = 0
		$(bedoWords).each(function () {
			let chars = $(this).html().length + 1
			$(this).lettering()
			$(this).children("span").each(function () {
				let origClass = $(this).attr("class")
				let origClassNum = parseInt(origClass.split("r")[1])
				let newClassNum = origClassNum + charnum
				$(this).removeClass(origClass).addClass("char" + newClassNum)
			})
			charnum += chars
		})

		/* ---------------------------------- hover --------------------------------- */

		$(bedoWords).hover(function () {
			$(bedoLetters).addClass("pause")
			$(this).children("span").addClass("current")
			let currTagClass = $(this).parent().attr("class").split(" ")
			let tagClass = findClassByStart(currTagClass, "tag")
			console.log(".bedo-sub-wrapper ." + tagClass)
			$(".sub-wrapper>.opened").removeClass("opened")
			$(".sub-wrapper>." + tagClass).addClass("opened")
		}, function () {
			$(bedoLetters).removeClass("pause")
			$(this).children("span").removeClass("current")
			$(".sub-wrapper>.opened").removeClass("opened")
		})


		/* -------------------------------------------------------------------------- */
		/*                                   SINGLE                                   */
		/* -------------------------------------------------------------------------- */


		if (isSingle) {

			/* ---------------------------- wrap figcaptions --------------------------- */


			$("figcaption").wrapInner("<span></span>")



			/* ----------------------------- images, gallery ---------------------------- */

			//hide caption on desktop
			if (!isMobile) {
				// $('.wp-block-gallery img, .wp-block-image img, .vis').hover(function () {
				// 	$(this).parent('a').next("figcaption").addClass("vis")
				// }, function () {
				// 	$('.wp-block-gallery .vis, .wp-block-image .vis')
				// 		.removeClass("vis")
				// })

				$('.wp-block-gallery .blocks-gallery-item, .wp-block-image').hover(function () {
					$(this).find("figcaption").addClass("vis")

				}, function () {
					$('.wp-block-gallery .vis, .wp-block-image .vis').removeClass("vis")
				})



			}


			/* -------------------------------- Lightbox -------------------------------- */



			//group gallery images:
			$('.wp-block-gallery a, .wp-block-image a').addClass('cb-gallery')

			//copy figcaption to title
			$("a.cb-gallery ~ figcaption").each(function () {
				let captiotext = $(this).html()
				$(this).prev('.cb-gallery').attr({ title: captiotext })
			})

			//http://www.jacklmoore.com/colorbox/
			const colorboxSettings = {
				transition: 'none',
				rel: 'cb-ballery',
				maxWidth: '90%',
				maxHeight: '80%',
				trapFocus: false,
				scrolling: false,
				fixed: true,
				previous: '',
				next: '',
				close: '',
				xhrError: 'A tartalom betöltése nem sikerült. Kérlek próbáld meg később.',
				imgError: 'A kép betöltése nem sikerült. Kérlek próbáld meg később.'

			}

			// lightbox for galleries
			$(".wp-block-gallery a").colorbox(colorboxSettings)

			//single images
			$(".wp-block-image a").colorbox(colorboxSettings)


			/* ---------------------------- hover and click on related ---------------------------- */

			$(document).on({
				mouseenter: function () {
					if (!Modernizr.touchevents) {
						let wrapper = $(this).children(".relatedWrapper")
						showTitle(wrapper)
					}
				},
				mouseleave: function () {
					if (!Modernizr.touchevents) {
						let wrapper = $(this).children(".relatedWrapper")
						hideTitle(wrapper)
					}
				}
			}, '#related_posts li');

			//touch on small articles
			$(document).on({
				'touchend': function (e) {
					e.preventDefault()
					var art = $(this).parents("li").children(".relatedWrapper")
					hideTitle($(".vis").parents(".relatedWrapper"))
					showTitle(art)

				}
			}, "#related_posts li a.related_thumbnailwrapper")

			//click on related
			$('#related_posts li .relatedWrapper').click(function () {
				let href = $(this).children('a.related_thumbnailwrapper').attr("href")
				window.open(href, "_self")
			})

			/* ----------------------------- scroll to title ---------------------------- */

			if (!isMobile) {
				const titleWrapperHeight = $('article>.titlewrapper')[0].getBoundingClientRect().height
				if ($('html, body').scrollTop() == 0) {
					$('html, body').stop().animate({ scrollTop: titleWrapperHeight }, 400);
				}
			}


		}//if single end





		/* ------------------------------- END OF FILE ------------------------------ */

	});

})(jQuery, this);
