function multiBackgroundFade() {
	const changers = document.querySelectorAll('[class*="multi-bg-fade-"]');
	if (!changers) {
		return;
	}

	const contentElement = document.querySelector('#site-content');

	const observer = new IntersectionObserver((entries) => {
		entries.forEach((entry) => {
			if (entry.isIntersecting) {

				let color = '';
				entry.target.classList && entry.target.classList.forEach((className) => {
					if (className.includes('multi-bg-fade-')) {
						color = '#' + className.replace('multi-bg-fade-', '');
					}
				});
				if (color) {
					document.body.style.backgroundColor = color;
					if (contentElement) {
						contentElement.style.backgroundColor = color;
					}
				}
			}
		})
	}, {
		rootMargin: '0px 0px -70% 0px'
	});

	changers.forEach((el) => {
		observer.observe(el);
	})
}

document.addEventListener('DOMContentLoaded', multiBackgroundFade);
/**
 * Checks element's offset (distance prom page edge)
 * @param {Object} el
 * @param {String} whichOffset
 */
const getElementOffset = function (el, whichOffset) {
    'use strict';

    var elem = el;
    var distance = 0;

    do {
        distance += parseInt(elem[whichOffset]);
        elem = elem.offsetParent;
    } while (elem);

    distance = distance < 0 ? 0 : distance;

    return distance;
}

/**
 * Returns all ancestors with a given class
 * @param {Object} el
 * @param {String} className
 */
const getAllParents = function (el, className) {
    'use strict';

    const nodes = [];

    while (el.parentNode) {
        if (el.parentNode.classList.contains(className)) {
            nodes.unshift(el.parentNode);
        }
        el = el.parentNode;
    }
    return nodes;
}
window.addEventListener('load', function() {
    'use strict';

	document.querySelector('html').classList.remove('no-scroll');

    const setBodyWidth = function () {
		const width = document.body.clientWidth;
        document.documentElement.style.setProperty('--body-width', width + 'px');
        document.documentElement.style.setProperty('--fullwidth-margin', (width / -2) + 'px');
	}

	const setHeaderHeight = function () {
		const header = document.querySelector('.single-post-header.sticky-enabled') || document.querySelector('.site-header');

		var headerHeight = header ? header.clientHeight : 0;
		document.documentElement.style.setProperty('--header-height-negative', '-' + headerHeight + 'px');
		document.documentElement.style.setProperty('--header-height', headerHeight + 'px');
	}

	setBodyWidth();
	setHeaderHeight();

    window.addEventListener('resize', function() {
        setTimeout(function() {
            setBodyWidth();
			setHeaderHeight();
        }, 150);
	});


});


document.addEventListener('DOMContentLoaded', function() {
    'use strict';

    function setBgOffset () {
        setTimeout(function() {
            const siteHeaderHeight = document.querySelector('.site-header') ? document.querySelector('.site-header').offsetHeight : 0;
            const adminBarHeight = document.querySelector('#wpadminbar') ? document.querySelector('#wpadminbar').offsetHeight : 0;
            var h = siteHeaderHeight + adminBarHeight;
            document.documentElement.style.setProperty('--subheader-bg-offset', h + 'px');
        }, 300);
    }

    window.addEventListener('load', function() {
        setBgOffset();
    });

    const parallaxSubheader = document.querySelectorAll('.subheader.parallax');
    if (parallaxSubheader.length) {
        window.addEventListener('resize', function() {
            setBgOffset();
        });
        window.addEventListener('stickyHeaderOn', function() {
            setBgOffset();
        });
        window.addEventListener('stickyHeaderOff', function() {
            setBgOffset();
        });
        window.addEventListener('toggleMenu', function() {
            setBgOffset();
        });
    }
});
/*global window, document*/

document.addEventListener('DOMContentLoaded', function () {
    'use strict';

    // country select
    document.querySelectorAll('.country_select').forEach(function (countrySelect) {
        const wrapper = document.createElement('span');
        wrapper.classList.add('limit75');
        countrySelect.parentNode.insertBefore(wrapper, countrySelect);
        wrapper.appendChild(countrySelect);
    });

    // messages
    document.querySelectorAll('.msg a.hide').forEach(function (closeLink) {
        closeLink.addEventListener('click', function (event) {
            event.preventDefault();
            closeLink.parentNode.style.height = 0;
            closeLink.parentNode.style.padding = '0 20px 0 77px';
            closeLink.parentNode.style.margin = 0;
            closeLink.parentNode.style.borderWidth = 0;
        });
    });

    document.querySelectorAll('.wc-block-grid__product .wp-block-button__link, .wc-block-featured-category .wp-block-button__link, .wc-block-featured-product .wp-block-button__link').forEach(function (btn) {
        btn.classList.remove('wp-block-button__link');
        btn.classList.add('button');
    });
});
/*global window, $*/

window.addEventListener('load', function() {
    'use strict';

	const gotop = document.querySelector('.go-top');

	if (!gotop) {
		return;
	}
    const contentStart = document.querySelector('.content-start');
    gotop.classList.remove('show');

    if (contentStart && "IntersectionObserver" in window) {
        var contentStartObserver = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                if (entry.boundingClientRect.y < 0) {
                    if (gotop.classList.contains('show-down')) {
						gotop.classList.add('show');
					}
                } else {
                    gotop.classList.remove('show');
                }
            })
        });
        contentStartObserver.observe(contentStart);
	}

	if (gotop && gotop.classList.contains('show-up')) {
		var lastScrollTop = 0;

		window.addEventListener('scroll', function() {
		   var scrollTop = window.pageYOffset || document.documentElement.scrollTop;

		   if (scrollTop < lastScrollTop) {
				if (window.pageYOffset > 200) {
					gotop.classList.add('show');
				} else {
					gotop.classList.remove('show');
				}
		   } else {
				gotop.classList.remove('show');
		   }
		   lastScrollTop = scrollTop <= 0 ? 0 : scrollTop;
		}, false);
	}
});
document.addEventListener('DOMContentLoaded', function () {
	'use strict';

	const floated = document.querySelectorAll('.float-label');
	floated.forEach(function(floatedEl) {
		const formField = floatedEl.querySelector('input, textarea, select');
		if (formField.value !== '') {
			floatedEl.classList.add('active');
		}

		formField.addEventListener('focus', function () {
			floatedEl.classList.add('active');
		});

		formField.addEventListener('blur', function () {
			if (formField.value !== '') {
				floatedEl.classList.add('active');
			} else {
				floatedEl.classList.remove('active');
			}
		});
	});
})
/*
 * fancy borders
 */

function fancyBorders(el) {
    'use strict';

    const wrapper = document.createElement('span');
    wrapper.classList.add('img-border');

    if (el.classList.contains('aligncenter')) {
        wrapper.classList.add('aligncenter');
    }
    if (el.classList.contains('alignleft')) {
        wrapper.classList.add('alignleft');
    }
    if (el.classList.contains('alignright')) {
        wrapper.classList.add('alignright');
    }
    if (el.classList.contains('size-thumbnail')) {
        wrapper.classList.add('th');
    }

    el.parentNode.insertBefore(wrapper, el);
    wrapper.appendChild(el);

    if (el.classList.contains('aligncenter')) {
        wrapper.style.width = el.getAttribute('width') + 'px';
    }
}

function applyFancyBorders() {
    'use strict';

    const imageList = document.querySelectorAll('.content img, .widget_photos img');
    const excludes = document.querySelectorAll('.mb-before-after img, .revslider img, .wpml-ls-flag, .mb-tabs-slider img, .product-review .avatar, .content img.avatar-20, .content img.avatar-14, .content .mb-testimonial img, img.emoji, .logo, h3 img, button img, .product-meta img, .img-border img, img.no-fancy-border, .no-fancy-border img, .forum .bbp-author-avatar img, .bbp-author-avatar img.avatar-14, .bbp-template-notice img, .banner img, .content img.client-logo, .post-header.with-image img, .mb-circle-chart img, .mb-icon-progress img, .mb-icon-heading img, img[role="presentation"]');

    var images = Object.values(imageList);
    var excludedImages = Object.values(excludes);

    excludedImages.forEach(function (excluded) {
        var index = images.indexOf(excluded);
        if (index > -1) {
            images.splice(index, 1);
        }
    });

    images.forEach(function (image) {
        fancyBorders(image);
    });
}

document.addEventListener('related-post-loaded', function (event) {
    'use strict';

    applyFancyBorders();
});

window.addEventListener('load', function () {
    'use strict';

    applyFancyBorders();
});
/*global window, document*/

const clickableHandleClick = function (event) {
    'use strict';

    event.preventDefault();

    const mainLink = this.querySelector('.main-link');
    const url = mainLink.getAttribute('href');

    if (url) {
        window.location = url;
    }
}

const initClickable = function () {
    'use strict';

    const clickables = document.querySelectorAll('.clickable');

    clickables.forEach(function (clickable) {
        clickable.removeEventListener('click', clickableHandleClick);
        clickable.addEventListener('click', clickableHandleClick);
    });
}

document.addEventListener('DOMContentLoaded', function () {
    'use strict';

    initClickable();
});

document.addEventListener('related-post-loaded', function () {
    'use strict';

    initClickable();
});
document.addEventListener('DOMContentLoaded', function () {
    'use strict';

    const contentStart = document.querySelector('.content-start');

    if (contentStart && "IntersectionObserver" in window) {
        var contentStartObserver = new IntersectionObserver(function (entries) {
			entries.forEach(function (entry) {
				const header = document.querySelector('.single-post-header.sticky-enabled') || document.querySelector('.site-header.sticky-enabled.sticky-static');
				const style = window.getComputedStyle(document.body);
				const headerTop = parseInt(style.getPropertyValue('--sticky-header-pos'));

				const boundary = header?.classList.contains('single-post-header') ? 0 : headerTop;

				if (entry.boundingClientRect.y < boundary) {
                    if (header) {
						header.classList.add('sticky');
						setTimeout(function () {
							var widgetStop = parseInt(header.clientHeight);
							if (document.querySelector('.admin-bar')) {
								widgetStop += 60;
							} else {
								widgetStop += 30;
							}
							document.documentElement.style.setProperty('--sticky-widget-stop', widgetStop + 'px');
						}, 300);
                        window.dispatchEvent(new Event('stickyHeaderOn'));
                    }
                } else {
                    if (header) {
						if (header.classList.contains('sticky')) {
							header.classList.remove('sticky');
							window.dispatchEvent(new Event('stickyHeaderOff'));
						}
                    }
                }
            })
        }, {
            rootMargin: '-10px 0px 0px 0px'
        });
        contentStartObserver.observe(contentStart);
    }

    var header = document.querySelector('.site-header.sticky-enabled.sticky-animate-scroll-up, .site-header.sticky-enabled.sticky-animate-scroll-down');
	const headerHeight = header?.clientHeight || 0;
    var singleHeader = document.querySelector('.single-post-header');

    if (header && !singleHeader) {
        var oldScrollPos = 0;
		var pageContent = document.querySelector('.content');
		var chosenDirection;
		if (header.classList.contains('sticky-animate-scroll-up')) {
			chosenDirection = 'up';
		} else if (header.classList.contains('sticky-animate-scroll-down')) {
			chosenDirection = 'down';
		}

		var animating = false;

		const stick = function() {
			animating = true;
			header.classList.add('sticky');
			window.dispatchEvent(new Event('stickyHeaderOn'));
			setTimeout(() => {
				animating = false;
			}, 300);
		}

		const unstick = function() {
			animating = true;
			header.classList.remove('sticky');
			window.dispatchEvent(new Event('stickyHeaderOff'));
			setTimeout(() => {
				animating = false;
			}, 300);
		}

		const update = function(currentScrollPos, chosenDirection, scrollingDirection) {
			if (currentScrollPos === 0) {
				animating = false;
				unstick();
			}

			if (animating) {
				return;
			}
			const boundary = headerHeight + 50;


			if (chosenDirection === 'up') {
				if (scrollingDirection === 'up' && currentScrollPos > boundary) {
					stick();
				} else if (scrollingDirection === 'down' && currentScrollPos <= 0) {
					unstick();
				}
			}

			if (chosenDirection === 'down') {
				if (scrollingDirection === 'down' && currentScrollPos > boundary) {
					stick();
				} else if (scrollingDirection === 'up' && currentScrollPos <= 0) {
					unstick();
				}
			}
		}

        window.addEventListener('scroll', function () {
            var currentScrollPos = window.pageYOffset;

			let scrollingUp = currentScrollPos < oldScrollPos  && currentScrollPos > pageContent.offsetTop;
			let scrollingDown = currentScrollPos > oldScrollPos;
			let scrollingDirection = scrollingUp
				? 'up'
				: scrollingDown
					? 'down'
					: '';

			update(currentScrollPos, chosenDirection, scrollingDirection);

            oldScrollPos = currentScrollPos;
        }, { passive: true });
    }

    // swapping logo in sticky header
    const logo = document.querySelector('.site-header .main-logo');
    const stickyLogo = logo ? logo.dataset.stickyLogo : null;
    if (stickyLogo && logo) {
        const basicLogo = logo.getAttribute('src');
        const basicLogoWidth = logo.getAttribute('width');
        const basicLogoHeight = logo.getAttribute('height');
        const stickyLogoWidth = logo.dataset.stickyLogoWidth;
        const stickyLogoHeight = logo.dataset.stickyLogoHeight;

        window.addEventListener('stickyHeaderOn', function () {
            const logos = document.querySelectorAll('.site-header.sticky .main-logo');
            logos.forEach(function (logoImage) {
                logoImage.setAttribute('src', stickyLogo);
                if (stickyLogoWidth) {
                    logoImage.setAttribute('width', stickyLogoWidth);
                }
                if (stickyLogoHeight) {
                    logoImage.setAttribute('height', stickyLogoHeight);
                }
            })
        });

        window.addEventListener('stickyHeaderOff', function () {
            const logos = document.querySelectorAll('.site-header .main-logo');
            logos.forEach(function (logoImage) {
                logoImage.setAttribute('src', basicLogo);
                if (stickyLogoWidth) {
                    logoImage.setAttribute('width', basicLogoWidth);
                }
                if (stickyLogoHeight) {
                    logoImage.setAttribute('height', basicLogoHeight);
                }
            })
        });
    }

});

/*jslint for:true */
/*global window, document*/

document.addEventListener('DOMContentLoaded', function () {
    'use strict';

    const largeScreen = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--header-mobile-breakpoint'));
    const doc = document.querySelector('html');
    const body = document.querySelector('body');
    const siteHeader = document.querySelector('.site-header');
    const overlayMenus = body.classList.contains('overlay-menus');
    const diagonalMenu = body.classList.contains('diagonal-menu');
    const standardMenus = body.classList.contains('show-menus');
    const menuToggle = document.querySelectorAll('.main-header .menu-toggle');
    const mainMenu = document.querySelector('.site-header .mainmenu');
	const mainMenuItems = mainMenu?.querySelectorAll('.menu > li');
    const iconPullDownDefault = body.dataset.pulldownDefault;
    const iconPullDownExpanded = body.dataset.pulldownExpanded;
    var showingMenu = false;
    var screenWidth = window.innerWidth;

    // apply icons to links
    document.querySelectorAll('.menu li[class*="m-icon"]>a').forEach(function (link) {
        const classes = link.parentNode.className.split(' ');
        const pattern = /\bm-icon-/;
        var i;

        link.classList.add('m-icon');
        for (i = 0; i < classes.length; i += 1) {
            if (pattern.test(classes[i])) {
                link.classList.add(classes[i]);
            }
        }
    });

    function hideSubMenus(subMenus) {
        if (mainMenu && (!subMenus || !subMenus.length)) {
            subMenus = mainMenu.querySelectorAll('.sub-menu');
        }

        if (!subMenus.length) {
            return;
        }

        subMenus.forEach(function (subMenu) {
            subMenu.classList.add('hidden');
            const link = subMenu.parentNode.querySelector('a');
            if (link) {
                const icon = link.querySelector('.pull-down .m-icon');
                if (icon) {
                    icon.classList.remove(iconPullDownExpanded);
                    icon.classList.add(iconPullDownDefault);
                }
            }
        });
    }

    function showMainMenu() {
        hideSubMenus();

        if (!overlayMenus) {
            if (siteHeader && siteHeader.classList.contains('mobile-sticky')) {
                const adminBar = document.querySelector('#wpadminbar');
                const adminBarHeight = adminBar ? adminBar.offsetHeight : 0;
                const headerHeight = siteHeader.offsetHeight + adminBarHeight;
                mainMenu.style.maxHeight = 'calc(100vh - ' + headerHeight + 'px)';
            }
        } else {
            doc.classList.add('no-scroll');
        }

        if (!diagonalMenu) {
            const currentElements = mainMenu.querySelectorAll('.current-menu-item, .current_page_ancestor, .current-menu-parent');
            const parentMenus = [];
            currentElements.forEach(function (menuEl) {
                const ancestor = menuEl.closest('.sub-menu');
                if (ancestor) {
                    parentMenus.push(ancestor);
                }
            });
            parentMenus.forEach(function (menu) {
                menu.classList.remove('hidden');
                const pullDown = menu.parentNode.querySelector('a .pull-down .m-icon');
                if (pullDown) {
                    pullDown.classList.add(iconPullDownExpanded);
                    pullDown.classList.remove(iconPullDownDefault);
                }
            });
        }
        if (overlayMenus || diagonalMenu) {
            mainMenu.classList.add('show');
			if (diagonalMenu) {
				setTimeout(showMenuItems, 300);
			} else {
				showMenuItems();
			}
        } else {
            mainMenu.classList.toggle('show');
        }
    }

	function hideMenuItems() {
		mainMenuItems.forEach(function (menuItem) {
			menuItem.classList.remove('show');
		});
	}

	function showMenuItems() {
		var timeout = 0;
		mainMenuItems.forEach(function (menuItem) {
			timeout += 100;
			setTimeout(function () {
				menuItem.classList.add('show');
			}, timeout);
		});
	}

    function hideMainMenu() {
        if (overlayMenus || diagonalMenu) {
            mainMenu.classList.remove('show');
            mainMenu.removeAttribute('style');
			hideMenuItems();
            hideSubMenus();
        } else {
            mainMenu.classList.toggle('show');
            mainMenu.removeAttribute('style');
            hideSubMenus();
        }
        doc.classList.remove('no-scroll');
    }

	// navigation menus
	if (menuToggle) {
		menuToggle.forEach(function (toggle) {
			toggle.addEventListener('click', function (event) {
				event.preventDefault();

				if (showingMenu) {
					hideMainMenu();
					menuToggle.forEach(function (toggle) {
						toggle.classList.remove('expanded');
					});
					showingMenu = false;
				} else {
					showMainMenu();
					menuToggle.forEach(function (toggle) {
						toggle.classList.add('expanded');
					});
					showingMenu = true;
				}

				const toggleMenuEvent = new Event('toggleMenu');
				window.dispatchEvent(toggleMenuEvent);
			});
		});

		if (overlayMenus || diagonalMenu) {
			document.querySelectorAll('.close-menu').forEach(function (closeLink) {
				closeLink.addEventListener('click', function (event) {
					event.preventDefault();

					if (overlayMenus) {
						mainMenu.querySelectorAll('.pull-down .m-icon').forEach((pullDownIcon) => {
							pullDownIcon.classList.add(iconPullDownDefault);
						});
						mainMenu.querySelectorAll('.sub-menu').forEach((submenu) => {
							submenu.classList.add('hidden');
						});
						doc.classList.remove("no-scroll");
					}

					mainMenu.classList.remove('show');
					hideMenuItems();
					menuToggle.forEach((toggle) => {
						toggle.classList.remove('expanded');
					});
					showingMenu = false;
				});
			});
		}
	}

	if (siteHeader) {
		siteHeader.querySelectorAll(".site-header .menu .pull-down").forEach((pullDown) => {
			pullDown.addEventListener('click', (event) => {
				event.stopPropagation();
				event.preventDefault();

				if (window.innerWidth < largeScreen || !document.querySelector('.show-menus')) {
					const pullDownIcon = pullDown.querySelector('.m-icon');
					pullDownIcon.classList.toggle(iconPullDownDefault);
					pullDownIcon.classList.toggle(iconPullDownExpanded);

					const submenu = pullDown.parentNode.parentNode.querySelector('.sub-menu');
					submenu.classList.toggle('hidden');
				}
			});

			pullDown.addEventListener('keydown', (event) => {
				if (event.key === 'Enter' || event.key === ' ') {
					event.preventDefault();
					pullDown.dispatchEvent(new Event('click'));
				}
			});
		});
	}

    document.querySelectorAll(".widget .menu .pull-down").forEach(function (widgetPullDown) {
        widgetPullDown.addEventListener('click', (event) => {
            event.stopPropagation();
            event.preventDefault();
            const pullDownIcon = widgetPullDown.querySelector('.m-icon');
            pullDownIcon.classList.toggle(iconPullDownDefault);
            pullDownIcon.classList.toggle(iconPullDownExpanded);

            const submenu = widgetPullDown.parentNode.parentNode.querySelector('.sub-menu');
            submenu.classList.toggle('hidden');
        });
    });

    document.querySelectorAll('.mainmenu .menu a[href="#"]').forEach(function (link) {
        link.addEventListener('click', function (event) {
            event.stopPropagation();
            event.preventDefault();
            const pullDown = link.querySelector('.pull-down');
            if (pullDown) {
                pullDown.dispatchEvent(new Event('click'));
            }
        });
    });

	const setStickyHeaderPos = function() {
		const newScreenWidth = window.innerWidth;
		let isLargeScreen = newScreenWidth > largeScreen;
		let stickyHeaderPos = 0;

		const topBar = document.querySelector('.top-bar');
		if (
			(isLargeScreen && topBar?.classList.contains('is-sticky-desktop')) ||
			(!isLargeScreen && topBar?.classList.contains('is-sticky-mobile'))
		) {
			stickyHeaderPos = document.querySelector('.top-bar').offsetHeight;
		}
		let root = document.querySelector(':root');
		root.style.setProperty('--sticky-header-pos', stickyHeaderPos ? stickyHeaderPos + 'px' : '0px');
	}

	window.addEventListener('load', setStickyHeaderPos);

    window.addEventListener('resize', function () {
		setStickyHeaderPos();
		const newScreenWidth = window.innerWidth;
		const topBar = document.querySelector('.top-bar');

		if (!siteHeader) {
			return;
		}
        const subMenus = siteHeader.querySelectorAll('.mainmenu .sub-menu');

        if (standardMenus) {
            if (newScreenWidth > largeScreen) {
                subMenus.forEach(function (subMenu) {
                    subMenu.classList.remove('hidden');
                });
                mainMenu.removeAttribute('style');
            } else if (menuToggle[0].classList.contains('expanded') && newScreenWidth < largeScreen && screenWidth >= largeScreen) {
                showMainMenu();
            } else if (siteHeader.classList.contains('mobile-sticky')) {
                let topBarHeight = topBar?.classList.contains('is-sticky-mobile') ? topBar.offsetHeight : 0;
                let headerHeight = document.querySelector('.site-title').offsetHeight + topBarHeight;
                mainMenu.style.maxHeight = 'calc(100vh - '+ headerHeight + 'px)';
            }
            screenWidth = newScreenWidth;

        } else if (diagonalMenu) {
            subMenus.forEach(function (subMenu) {
                subMenu.classList.remove('hidden');
            });
            mainMenu.removeAttribute('style');
            menuToggle.forEach(function (toggle) {
				toggle.classList.remove('expanded');
			});

        } else if (overlayMenus) {
            if (window.innerWidth >= largeScreen) {
                mainMenu.removeAttribute('style');
            } else {
                var headerHeight = parseInt(siteHeader.querySelector('#wpadminbar').offsetHeight);
                siteHeader.querySelector('.overlay-menu').style.maxHeight = 'calc(100vh - ' + headerHeight + 'px)';
            }
        }

        if (newScreenWidth >= largeScreen) {
            siteHeader.removeAttribute('style');
        }

        // setMegaMenuPosition();
    });

    // submenu - right-aligned if close to layout boundary
    document.querySelectorAll('.boxed').forEach(function (boxed) {

        const root = document.querySelector('.root');
        var boundary = getElementOffset(root, 'offsetLeft') + root.offsetWidth - 180;

        window.addEventListener('resize', function () {
            boundary = getElementOffset(root, 'offsetLeft') + root.offsetWidth - 180;
        });

        document.querySelectorAll('.boxed header nav>ul>li').forEach(function (element) {
            var pos = getElementOffset(element, 'offsetLeft');
            if (pos > boundary) {
                element.classList.add('right');
            }
        });
    });

    // hiding submwnus in widget
    hideSubMenus(document.querySelectorAll('.widget .sub-menu'));
    document.querySelectorAll('.widget .menu').forEach(function (widgetMenu) {
        const currentElements = widgetMenu.querySelectorAll('.current-menu-item, .current_page_ancestor, .current-menu-parent');
        const parentMenus = [];
        currentElements.forEach(function (menuEl) {
            const ancestor = menuEl.closest('.sub-menu');
            if (ancestor) {
                parentMenus.push(ancestor);
            }
        });
        parentMenus.forEach(function (menu) {
            menu.classList.remove('hidden');
            const pullDown = menu.parentNode.querySelector('a .pull-down .m-icon');
			if (pullDown) {
				pullDown.classList.add(iconPullDownExpanded);
				pullDown.classList.remove(iconPullDownDefault);
			}
        });
    });

    if (siteHeader && standardMenus && window.innerWidth >= largeScreen) {
        siteHeader.querySelectorAll('.sub-menu').forEach((submenu) => {
            submenu.classList.remove('hidden');
        });
    }

});

/*global window*/
const hash = window.location.hash;

const measureHeader = function () {
	var isLargeScreen = window.innerWidth >= 1140;

	var header = document.querySelector('.single-post-header') || document.querySelector('.site-header');
	var isHeaderSticky = (isLargeScreen && header.classList.contains('sticky-enabled')) || (!isLargeScreen && header.classList.contains('mobile-sticky'));
	var headerHeight = 0;

	if (isHeaderSticky) {
		if (document.querySelector('.single-post-header')) {
			headerHeight = parseInt(header.offsetHeight);
		} else {
			const topBar = document.querySelector('.top-bar');
			const siteTitle = document.querySelector('.site-title');

			const topBarHeight = topBar && !topBar.classList.contains('sticky-hide') ? topBar.offsetHeight : 0;
			const siteTitleHeight = siteTitle ? siteTitle.offsetHeight : 0;

			headerHeight = parseInt(topBarHeight + siteTitleHeight);
		}
	}
	const adminBar = document.querySelector('#adminbar');
	if (adminBar) {
		headerHeight + adminBar.offsetHeight;
	}
	window.headerHeight = headerHeight;
	return headerHeight;
}

const scrollPageTo = function (target) {
	console.log('scrolling');
    'use strict';

    if (target) {
		const isLargeScreen = window.innerWidth >= 1140;
		const header = document.querySelector('.single-post-header') || document.querySelector('.site-header');
		const isHeaderSticky = (isLargeScreen && header.classList.contains('sticky-enabled')) || (!isLargeScreen && header.classList.contains('mobile-sticky'));
		const bodyRect = document.body.getBoundingClientRect();
		const rect = target.getBoundingClientRect();
		let targetPosition = rect.top - bodyRect.top;
		let pos = isHeaderSticky ? targetPosition - measureHeader() - 10 : targetPosition - 10;
		window.scrollTo(0, pos);
    }
}

window.addEventListener('load', function () {
    'use strict';

    //comment link click - refresh page so it does not lead to wrong comment form on infinite scrolling pages
    document.querySelectorAll('.main').forEach(function (main) {
        if (!main.classList.contains('postlist')) {
            main.addEventListener('click', function (event) {
                var target = event.target;
                if (target.classList.contains('comment-link')) {
                    event.preventDefault();
                    var oldLocation = window.location,
                        newLocation = target.getAttribute('href'),
                        locationIndex = newLocation.indexOf(oldLocation);

                    window.location = newLocation;
                    if (locationIndex > -1 && target.closest('.related-content')) {
                        // window.location.reload(true);
						window.location.href = window.location.href;
                    }
                }
            });
        }
    });

	const closeMainMenu = function (link) {
		const mainMenu = document.querySelector('.main-header .mainmenu');
		if (link.closest('.close-on-fragment-link')) {
			mainMenu.classList.remove('show');
			mainMenu.removeAttribute('style');
			const menuToggle = document.querySelector('.main-header .menu-toggle');
			if (menuToggle) {
				menuToggle.classList.remove('expanded');
			}
		}
	}

    // scrolling to proper place in content with an offset
    const anchors = document.querySelectorAll("a[href*='#']:not(.skip-link), a[href*='#acomment'], .tabs > li > a");
    const excludedAnchors = document.querySelectorAll("a[href*='/#'], a[href='#']");

    var links = Object.values(anchors);
    var excludedLinks = Object.values(excludedAnchors);

    excludedLinks.forEach(function (exluded) {
        var index = links.indexOf(exluded);
        if (index > -1) {
            links.splice(index, 1);
        }
    });

    links.forEach(function (link) {
        link.addEventListener('click', function (event) {
			closeMainMenu(link);

            if (location.pathname.replace(/^\//, '').replace(/\/$/, '') === this.pathname.replace(/^\//, '').replace(/\/$/, '') && location.hostname === this.hostname) {
                if (link.classList.contains('woocommerce-review-link')) {
					event.preventDefault();
                    var target = document.querySelector('.woocommerce-tabs');
                    target.querySelector('[for="product-tab-reviews"]').dispatchEvent(new Event('click'));
                    scrollPageTo(target);
                }
            }
        });
    });

    document.querySelectorAll('a[href*="/#"]').forEach(function (link) {
        link.addEventListener('click', function (event) {
			closeMainMenu(link);

            if (this.pathname === location.pathname) {
                event.preventDefault();
                var target = document.querySelector(this.hash);
                scrollPageTo(target);
            }

        });
    });

    document.querySelectorAll('a[href*="/#"]').forEach(function (link) {
        const menuItem = link.closest('.current-menu-item');
        if (menuItem) {
            menuItem.classList.remove('current-menu-item');
            menuItem.querySelector('a').removeAttribute('aria-current');
        }
    });

    // observing elements moving into view and updating anchors
    const anchorElements = document.querySelectorAll('.main *[id]');

    if (anchorElements.length && "IntersectionObserver" in window) {
		measureHeader();
        const halfScreen = parseInt(window.innerHeight / 2);
        const options = {
            rootMargin: '-' + (window.headerHeight) + 'px 0px -' + halfScreen + 'px 0px'
        };
        const anchorObserver = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
				const myId = entry.target.getAttribute('id');
                const linksToMe = myId ? document.querySelectorAll('.menu a[href*="#' + myId + '"]') : [];

                if (entry.isIntersecting) {
                    if (linksToMe.length) {
                        document.querySelectorAll('.menu .current-menu-item').forEach(function (item) {
                            item.classList.remove('current-menu-item');
                        });
                        linksToMe.forEach(function (item) {
                            item.parentElement.classList.add('current-menu-item');
                            var event = new Event('activeLinkChange');
                            window.dispatchEvent(event);
                        });
                    }

                } else if (!entry.isIntersecting) {
                    if (linksToMe.length) {
                        linksToMe.forEach(function (item) {
                            const itemParent = item.parentElement;
							itemParent.classList.remove('current-menu-item', 'current_page_item');
							var event = new Event('activeLinkChange');
							window.dispatchEvent(event);
						});
                    }

                }
            })
        }, options);

        anchorElements.forEach(function(element) {
            anchorObserver.observe(element);
        });
    }
});
/*global window, $*/

document.addEventListener('DOMContentLoaded', function () {
    'use strict';

    // closing popups
    document.querySelectorAll('.popup-close').forEach(function (element) {
        element.addEventListener('click', function (event){
            event.preventDefault();
			const popup = element.closest('.multi-popup');
			if (popup) {
				popup.close();
			}
			window.dispatchEvent(new CustomEvent('popup-close'));
        })
    });

    // search link in menu
    document.querySelectorAll('.search-popup-link').forEach(function (searchLink) {
        searchLink.addEventListener('click', function (event) {
            event.preventDefault();
            const searchPopup = document.querySelector('.multi-popup.popup-search');

            if (searchPopup) {
				searchPopup.showModal();
            }
        });
    });
});

/*global window*/

document.addEventListener('DOMContentLoaded', function () {
    'use strict';

    const contentStart = document.querySelector('.content-start');
    const stickyNav = document.querySelectorAll('.sticky-post-nav');

    if (contentStart && stickyNav.length && "IntersectionObserver" in window) {
        var contentStartObserver = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                if (entry.boundingClientRect.y < 0) {
                    stickyNav.forEach(function(navItem) {
                        navItem.classList.add('show');
                    });
                } else {
                    stickyNav.forEach(function(navItem) {
                        navItem.classList.remove('show');
                    });
                }
            })
        });
        contentStartObserver.observe(contentStart);
    }
});
document.addEventListener('DOMContentLoaded', function () {
    'use strict';

    const logoHolder = document.querySelector('.logo-holder');
    if (logoHolder) {
        const logo = document.querySelector('.site-title .logo');
        if (logo) {
            const logoContents = logo.innerHTML;
            const clone = logo.cloneNode();
            clone.innerHTML = logoContents;
            logoHolder.parentNode.replaceChild(clone, logoHolder);
        }
    }
});
function initHiddenSocialLinks () {
    'use strict';

    const links = document.querySelectorAll('.social-links-hidden .social-link');

    links.forEach(function (link) {
        link.addEventListener('click', function () {
			let url = '';
			try {
				url = window.atob(link.dataset.link);
			} catch(e) {
				url = link.dataset.link;
			}
            if (link.classList.contains('new-tab')) {
                window.open(url, '_blank');
            } else if (url) {
                window.location = url;
            }
        });
    });
}

document.addEventListener('DOMContentLoaded', initHiddenSocialLinks);
document.addEventListener('related-post-loaded', initHiddenSocialLinks);
window.addEventListener('load', function () {
	'use strict';

	const buttons = document.querySelectorAll('.animated-buttons-grow-c-circle .button, .animated-buttons-grow-c-circle button, .button.ani-bg.grow-c-circle');

	if (!buttons) {
		return;
	}

	buttons.forEach(function (btn) {
		btn.addEventListener('mouseenter', (event) => {
			const rect = btn.getBoundingClientRect();
			const x = event.clientX - rect.x;
			const y = event.clientY - rect.y;

			btn.style.setProperty('--mouse-x', x + 'px');
			btn.style.setProperty('--mouse-y', y + 'px');

			const button = btn;

			setTimeout(function() {
				button.classList.add('hover');
			}, 50);
		});

		btn.addEventListener('mouseleave', (event) => {
			const rect = btn.getBoundingClientRect();
			const x = event.clientX - rect.x;
			const y = event.clientY - rect.y;

			btn.style.setProperty('--mouse-x', x + 'px');
			btn.style.setProperty('--mouse-y', y + 'px');

			const button = btn;

			setTimeout(function() {
				button.classList.remove('hover');
			}, 50);
		});
	});
});
document.addEventListener('DOMContentLoaded', function() {
	'use strict';

    // sharing popup
    document.querySelectorAll('.share-popup-link').forEach(function (shareLink) {
        shareLink.addEventListener('click', function (event) {
            event.preventDefault();
            const sharePopup = document.querySelector('.multi-popup.popup-share');

            const url = this.getAttribute('href');
            const linkData = [
                {name: "Facebook", slug: "facebook", url: "https://www.facebook.com/sharer/sharer.php?u=" + url},
                {name: "Twitter", slug: "twitter", url: "https://twitter.com/home?status=" + url},
                {name: "LinkedIn", slug: "linkedin", url: "https://www.linkedin.com/shareArticle?mini=true&url=" + url + "&title=&summary=&source="}
            ];
            const linkList = sharePopup.querySelector('.share-links');

            linkList.innerHTML = '';
            linkData.forEach(function (data) {
                const link = document.createElement('a');
                link.className = 'm-icon m-icon-' + data.slug + ' share-link-' + data.slug;
                link.setAttribute('href', data.url);
                link.setAttribute('title', data.name);
                link.setAttribute('target', '_blank');
                const listItem = document.createElement('li');
                listItem.appendChild(link);
                linkList.appendChild(listItem);
            });

            sharePopup.classList.remove('copied');
            sharePopup.querySelector('.link-copy-link').value = url;
			sharePopup.showModal();
        });
    });

    const copyButton = document.querySelector('.link-copy-button');
    copyButton?.addEventListener('click', function (event) {
        event.preventDefault();
        document.getElementById('link-copy-link').select();
        document.execCommand('copy');
        document.querySelector('.multi-popup.popup-share').classList.add('copied');
    });

    const shareUrlInput = document.querySelector('.link-copy-link');
    shareUrlInput?.addEventListener('click', function (event) {
        this.select();
    });
});

document.addEventListener('single-post-header-update', function (event) {
    'use strict';

    const singlePostHeader = document.querySelector('.single-post-header');
	if (!singlePostHeader) {
		return;
	}

    var permalink = event.detail.permalink,
        shareFacebook = "https://www.facebook.com/sharer.php?u=" + permalink,
        shareTwitter = "https://twitter.com/share?url=" + permalink,
        sharePinterest = "https://pinterest.com/pin/create/button/?url=" + permalink + "&description=" + event.detail.postTitle;

    singlePostHeader.querySelector('.social-link-facebook').setAttribute('href', shareFacebook);
    singlePostHeader.querySelector('.social-link-twitter').setAttribute('href', shareTwitter);
    singlePostHeader.querySelector('.social-link-pinterest').setAttribute('href', sharePinterest);
});

document.addEventListener('DOMContentLoaded', () => {
	const toggleFade = function(el) {
		let scrolled = el.scrollWidth - Math.ceil(el.scrollLeft);
		if (el.classList && scrolled <= el.clientWidth + 50) {
			el.classList.remove('is-fading');
		} else {
			el.classList.add('is-fading');
		}
	}

	const scrollableElements = document.querySelectorAll('.scrollable-fade');
	if (!scrollableElements) {
		return;
	}
	scrollableElements.forEach((el) => {
		toggleFade(el);
		el.addEventListener('scroll', () => {
			toggleFade(el);
		});
	});
	window.addEventListener('resize', () => {
		scrollableElements.forEach((el) => {
			toggleFade(el);
		});
	})
});

/* Multimagazine: modal accessibility — keyboard focus trap + focus restoration.
   Keeps Tab/Shift+Tab focus inside an open .multi-popup <dialog> and returns
   focus to the triggering element after the dialog is closed (Esc, backdrop,
   or close button). Appended as a self-contained module. */
(function () {
	'use strict';

	function focusableElements(container) {
		var selector = 'a[href], area[href], input:not([disabled]):not([type="hidden"]), ' +
			'select:not([disabled]), textarea:not([disabled]), button:not([disabled]), ' +
			'iframe, object, embed, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';
		return Array.prototype.slice.call(container.querySelectorAll(selector)).filter(function (el) {
			return el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0;
		});
	}

	function trapKeydown(event) {
		if (event.key !== 'Tab' && event.keyCode !== 9) {
			return;
		}
		var dialog = event.currentTarget;
		var items = focusableElements(dialog);
		if (!items.length) {
			event.preventDefault();
			return;
		}
		var first = items[0];
		var last = items[items.length - 1];
		var active = document.activeElement;
		if (event.shiftKey) {
			if (active === first || !dialog.contains(active)) {
				event.preventDefault();
				last.focus();
			}
		} else {
			if (active === last || !dialog.contains(active)) {
				event.preventDefault();
				first.focus();
			}
		}
	}

	function init() {
		var lastTrigger = null;

		// Record the element that opened a popup, before showModal() runs.
		document.addEventListener('click', function (event) {
			var trigger = event.target.closest('.search-popup-link, .share-popup-link');
			if (trigger) {
				lastTrigger = trigger;
			}
		}, true);

		document.querySelectorAll('.multi-popup').forEach(function (dialog) {
			dialog.addEventListener('keydown', trapKeydown);
			// Native 'close' fires for Esc, backdrop dismissal and .close().
			dialog.addEventListener('close', function () {
				if (lastTrigger && typeof lastTrigger.focus === 'function') {
					lastTrigger.focus();
					lastTrigger = null;
				}
			});
		});
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}
}());
