(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 woh = window.outerHeight
		// const wih = window.innerHeight
		// const vh = $(window).height()
		// const boh = document.body.offsetHeight
		// const dch = document.documentElement.clientHeight

		// console.log('pixelratio:', window.devicePixelRatio)


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

		// const cssWidths = {
		// 	w_vw: vw,
		// 	w_wow: wow,
		// 	w_wiw: wiw,
		// 	w_bw: bw,
		// 	// desktophomemargin: desktophomemargin,
		// 	h_wih: wih,
		// 	h_vh: vh,
		// 	// bottomScrollHeight: bottomScrollHeight,
		// 	// h_woh: woh,
		// 	h_boh: boh,
		// 	h_dch: dch
		// }
		// console.log(cssWidths)


		/* -------------------------------------------------------------------------- */
		/*                                  FUNCTIONS                                 */
		/* -------------------------------------------------------------------------- */

		/* --------------------------- css values to vars --------------------------- */

		function calcWidths() {
			let wow = window.outerWidth
			let wiw = window.innerWidth
			let mw = $(".header-1")[0].getBoundingClientRect().width
			return { wow: wow, wiw: wiw, desktophomemargin: mw }
		}

		/**
		 * Returns true or false for mobile and tablet query
		 * @param {string} device 'tablet' or 'mobile'
		 */
		function checkDevice(device) {
			let ww = calcWidths()

			// let wow = window.outerWidth
			// let wiw = window.innerWidth

			if ((ww.wow < 769 || ww.wiw < 769) && device == 'mobile') {
				//mobile settings
				return true
			} else if (768 < ww.wow && ww.wow < 1024 && 768 < ww.wiw && ww.wiw < 1024 && device == 'tablet') {
				return true
			} else {
				return 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
			}
		}

		/**
		 * 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
		}


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

		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 & ARCHIVES FUNCTIONS                         */
		/* -------------------------------------------------------------------------- */


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

		function wrapArts() {
			//calculate wrappable elements
			if ($(".hbox").length) {
				return
			}
			$('#content>article, #content>.archivetitle, #content>.archivedescription').addClass("hbox")
			var wrapArticles = $(".hbox").length

			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

			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++) {
				let j = i + 1
				if (isHome) {
					j = i + 3
				}
				let 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")
				}
			}
		}

		function unWrapArts() {
			$('.home_wrapper-big .hbox').unwrap('.home_wrapper-big')


			var wrapArticles = $(".hbox").length
			for (let i = 0; i < wrapArticles; i++) {
				let hs = 'home-thumbnail-small-' + (i + 1)
				$('.' + hs).removeClass(hs)
			}
			$('.hbox').removeClass('home-small').removeClass('hbox').unwrap('.home_wrapper-small')
			$('.home_wrapper-s1').removeClass('home_wrapper-s1')

			$('.home-big').removeClass('home-big')
		}

		/* ---------------- move bevezeto out from metadata on mobile --------------- */

		function moveBevezetoMobile() {
			$("article .metadata .bevezetoWrapper").each(function () {
				$(this).parents('article').append($(this))
			})
		}

		function moveBevezetoDesktop() {
			$("article>.bevezetoWrapper").each(function () {
				$(this).parent('article').children('.metadata').children('.postedon').after($(this))
			})
		}

		/* ---------------------------- 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)

			let ww = calcWidths()

			//if loadmore is the next, do not scroll, but load:
			if (nextelem.attr("class") == "misha_loadmore") {
				loadmore()
				return target
			} else if (isEsemeny) {
				offset = offset - (ww.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 - (ww.desktophomemargin / 2)
				} else if (wNum > 3 || !isHome) {
					offset = offset - ww.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;
			}
		}


		/* -------------------------------------------------------------------------- */
		/*                                   SEARCH                                   */
		/* -------------------------------------------------------------------------- */


		//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 {
					let ww = calcWidths()
					//if it's closed open:
					bar.show().stop().animate({ width: ww.wiw - (ww.desktophomemargin * 2) }, 400, function () {
						bar.addClass("opensearch")
						$(".search-input").focus()
					})
				}
			})
		}

		/* -------------------------------------------------------------------------- */
		/*                                    MENU                                    */
		/* -------------------------------------------------------------------------- */

		/* ------------------------------ menufunctions ----------------------------- */

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

		function mwCalc() {
			let ww = calcWidths()
			if (isMobile) {
				return ww.wow
			} else if (isTablet) {
				return 350
			} else {
				return 500
			}
		}

		/* ----------------------------- Set up the menu ---------------------------- */

		var menuWidth = mwCalc()

		$("#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: {
						open: function () {
							if (isMobile) {
								$('.social-link, .events-link').removeClass('hidden')
							}
						},
						close: function () {
							$(".menubutton button").removeClass("inverted")
							if (isMobile) {
								$('.social-link, .events-link').addClass('hidden')
							}
						},
						freezePage: false
					}
				}
			}

		});


		/* -------------------------------------------------------------------------- */
		/*                                  BOOLEANS                                  */
		/* -------------------------------------------------------------------------- */

		var isMobile = checkDevice('mobile')
		var isTablet = checkDevice('tablet')

		//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


		/* -------------------------------------------------------------------------- */
		/*                            Set up specific pages                           */
		/* -------------------------------------------------------------------------- */

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

		if (isMasonryPage && $("article").hasClass('no-result')) {
			$('body').addClass("no-result")
		}

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

		// default current elem for scrolling
		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"))
			}
		}

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

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

		/* --------------------- generic page load for onresize --------------------- */

		var articleWrapCounter = 0

		function loadPage() {
			if (isMobile) {
				// hide social buttons
				$('.social-link, .events-link').addClass('hidden')

				// move search to menu
				$(".search-box>.search-bar").prependTo("#sidebar-wrapper")

				// set up no results
				$('article.no-result').show()
				$('body.no-result .archivetitle>h2').appendTo('article.no-result')


			} else {
				// not mobile

				//show social links
				$('.social-link, .events-link').removeClass('hidden')

				// move search to back
				$("#sidebar-wrapper>.search-bar").appendTo(".search-box")

				// set up no results
				$('article.no-result h2').appendTo('.archivetitle')
				$('article.no-result').hide()
			}

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

					unWrapArts()

					moveBevezetoMobile()
				} else {
					//no overflowY
					$('html').css({ overflowY: "hidden" })

					wrapArts()

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

					moveBevezetoDesktop()

					// add random classes
					if (!$('.random').length) {
						$(".home_wrapper-small").each(function () {
							$(this).addRandomClasses()
						})
					}

				}
			}

			if (isMasonryPage || isEsemeny) {
				if (isMobile) {

				} else {
					currElem = $(selector + ':first-child')
				}
			}
		}

		loadPage()

		/* --------------------------- hide loading scree --------------------------- */

		$('.loadingscreen').hide()

		/* -------------------------------------------------------------------------- */
		/*                       Black logo on scroll on mobile                       */
		/* -------------------------------------------------------------------------- */

		$.fn.scrollStopped = function (callback) {
			var that = this, $this = $(that);
			$this.scroll(function (ev) {
				clearTimeout($this.data('scrollTimeout'));
				$this.data('scrollTimeout', setTimeout(callback.bind(that), 250, ev));
			});
		};

		var isMenuOpen = function () {
			let menuopen = ($('#sidebar').attr('data-simplersidebar') == 'opened') ? true : false
			return menuopen
		}

		$(window).scroll(function () {
			if (isMobile && !isMenuOpen() && (isHome || isSingle)) {
				$('.dis-logo, .menubutton-icon').addClass('black')
			}
		})

		$(window).scrollStopped(function () {
			if (isMobile && !isMenuOpen() && (isHome || isSingle)) {
				$('.dis-logo, .menubutton-icon').removeClass('black')
			}
		})

		/* -------------------------------------------------------------------------- */
		/*                                   SCROLL                                   */
		/* -------------------------------------------------------------------------- */

		/* ------------------------ scroll on home on desktop ----------------------- */

		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 || isEsemeny) {
						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 || isEsemeny) {
					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

		$('body').on('mouseenter', '.home-big h2 a', function () {
			bigArticleHoverShow($(this))
		})
		$('body').on('mouseleave', '.home-big h2 a', function () {
			bigArticleHoverHide($(this))
		})

		function bigArticleHoverHide(cc) {
			// let cc = $(this)
			if (!isMobile) {
				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()
					cMetadata.css({ height: '' })
				})
			}
		}

		function bigArticleHoverShow(cc) {
			if (!isMobile) {
				// 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();
				})
			}
		}

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


		/* ------------------------- hover on small articles ------------------------ */

		function showTitle(th) {
			if (!$('body').hasClass('no-result') && !isMobile) {
				$(th).children("h2").show()
				$(th).children(".metadata").addClass("vis")
			}
		}

		function hideTitle(th) {
			if (!$('body').hasClass('no-result') && !isMobile) {
				$(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")


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

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

		//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 .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 captiontext = $(this).html()
				$(this).prev('.cb-gallery').attr({ title: captiontext })
			})

			const lightBoxMaxHeight = isMobile ? '65%' : '80%'

			//http://www.jacklmoore.com/colorbox/
			const colorboxSettings = {
				transition: 'none',
				rel: 'cb-ballery',
				maxWidth: '90%',
				maxHeight: lightBoxMaxHeight,
				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.'

			}

			//swipe on mobile on lightbox
			$('#cboxOverlay, #colorbox').swipe({
				swipeLeft: function () {
					$.colorbox.next()

				},
				swipeRight: function () {
					$.colorbox.prev()
				},
				swipeUp: function () {
					return false
				},
				swipeDown: function () {
					return false
				},
			})

			// 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

		/* -------------------------------------------------------------------------- */
		/*                             window resize event                            */
		/* -------------------------------------------------------------------------- */

		$(window).resize(function () {
			let ww = calcWidths()

			//check if mobile
			isMobile = checkDevice('mobile')
			isTablet = checkDevice('tablet')

			// calc other vars
			menuWidth = mwCalc()

			articleWrapCounter = 0

			//run load script
			loadPage()


			//resize search
			if ($('.search-bar').hasClass("opensearch")) {
				$('.search-bar').css({ width: ww.wiw - (ww.desktophomemargin * 2) })
			}

		});




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

	});

})(jQuery, this);
