// source --> https://www.rennsteig-bike-tour.de/wp-content/plugins/nextgen-gallery/static/Lightbox/nextgen_video_helper.js?ver=4.1.3 
(function($) {
    "use strict";

    window.NextGEN_Video = {
        /**
         * Detect video platform from URL
         * @param {string} url
         * @returns {string|null} Platform name or null if not a video URL
         */
        detect_platform: function(url) {
            if (!url) return null;

            url = url.trim().toLowerCase();

            // YouTube patterns
            if (url.match(/youtube\.com|youtu\.be|youtube-nocookie\.com/)) {
                return 'youtube';
            }

            // Vimeo patterns
            if (url.match(/vimeo\.com/)) {
                return 'vimeo';
            }

            // Dailymotion patterns
            if (url.match(/dailymotion\.com|dai\.ly/)) {
                return 'dailymotion';
            }

            // Twitch patterns
            if (url.match(/twitch\.tv/)) {
                return 'twitch';
            }

            // VideoPress patterns
            if (url.match(/videopress\.com|video\.wordpress\.com/)) {
                return 'videopress';
            }

            // Wistia patterns
            if (url.match(/wistia\.com|wistia\.net/)) {
                return 'wistia';
            }

            // Local video patterns (direct video file URLs)
            if (url.match(/\.(mp4|webm|ogg|ogv|mov|avi|wmv|flv|mkv)(\?|$)/i)) {
                return 'local';
            }

            return null;
        },

        /**
         * Extract video ID from YouTube URL
         * @param {string} url
         * @returns {string|null}
         */
        extract_youtube_id: function(url) {
            if (!url) return null;

            var patterns = [
                /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube-nocookie\.com\/embed\/)([^&\n?#]+)/,
                /youtube\.com\/.*[?&]v=([^&\n?#]+)/,
            ];

            for (var i = 0; i < patterns.length; i++) {
                var match = url.match(patterns[i]);
                if (match && match[1]) {
                    return match[1];
                }
            }

            return null;
        },

        /**
         * Extract video ID from Vimeo URL
         * @param {string} url
         * @returns {string|null}
         */
        extract_vimeo_id: function(url) {
            if (!url) return null;

            var patterns = [
                /vimeo\.com\/(\d+)/,
                /vimeo\.com\/.*\/(\d+)/,
                /player\.vimeo\.com\/video\/(\d+)/,
            ];

            for (var i = 0; i < patterns.length; i++) {
                var match = url.match(patterns[i]);
                if (match && match[1]) {
                    return match[1];
                }
            }

            return null;
        },

        /**
         * Extract video ID from Dailymotion URL
         * @param {string} url
         * @returns {string|null}
         */
        extract_dailymotion_id: function(url) {
            if (!url) return null;

            var patterns = [
                /dailymotion\.com\/video\/([^/?]+)/,
                /dai\.ly\/([^/?]+)/,
                /dailymotion\.com\/embed\/video\/([^/?]+)/,
            ];

            for (var i = 0; i < patterns.length; i++) {
                var match = url.match(patterns[i]);
                if (match && match[1]) {
                    return match[1];
                }
            }

            return null;
        },

        /**
         * Extract video ID from Twitch URL
         * @param {string} url
         * @returns {Object|null} Object with videoId and type (video/clip)
         */
        extract_twitch_id: function(url) {
            if (!url) return null;

            // Twitch video pattern: twitch.tv/videos/VIDEO_ID
            var videoMatch = url.match(/twitch\.tv\/videos\/(\d+)/);
            if (videoMatch && videoMatch[1]) {
                return { videoId: videoMatch[1], type: 'video' };
            }

            // Twitch clip pattern: twitch.tv/CLIP_ID or clips.twitch.tv/CLIP_ID
            var clipMatch = url.match(/(?:twitch\.tv\/|clips\.twitch\.tv\/)([^/?]+)/);
            if (clipMatch && clipMatch[1]) {
                return { videoId: clipMatch[1], type: 'clip' };
            }

            return null;
        },

        /**
         * Extract video ID from VideoPress URL
         * @param {string} url
         * @returns {string|null}
         */
        extract_videopress_id: function(url) {
            if (!url) return null;

            var patterns = [
                /videopress\.com\/v\/([^/?]+)/,
                /video\.wordpress\.com\/v\/([^/?]+)/,
            ];

            for (var i = 0; i < patterns.length; i++) {
                var match = url.match(patterns[i]);
                if (match && match[1]) {
                    return match[1];
                }
            }

            return null;
        },

        /**
         * Extract video ID from Wistia URL
         * @param {string} url
         * @returns {string|null}
         */
        extract_wistia_id: function(url) {
            if (!url) return null;

            var patterns = [
                /wistia\.(?:com|net)\/medias\/([^/?]+)/,
                /wistia\.(?:com|net)\/embed\/([^/?]+)/,
            ];

            for (var i = 0; i < patterns.length; i++) {
                var match = url.match(patterns[i]);
                if (match && match[1]) {
                    return match[1];
                }
            }

            return null;
        },

        /**
         * Get video embed URL for a platform
         * @param {string} platform
         * @param {string|Object} videoId
         * @param {Object} settings Video settings (showVideoControls, autoplayVideos)
         * @returns {string|null}
         */
        get_embed_url: function(platform, videoId, settings) {
            if (!platform || !videoId) return null;

            settings = settings || {};
            var autoplay = settings.autoplay_videos ? 1 : 0;
            var controls = settings.show_video_controls !== false ? 1 : 0;

            switch (platform) {
                case 'youtube':
                    var youtubeId = typeof videoId === 'string' ? videoId : videoId.videoId;
                    return 'https://www.youtube.com/embed/' + youtubeId + 
                           '?autoplay=' + autoplay + 
                           '&controls=' + controls + 
                           '&rel=0&modestbranding=1';

                case 'vimeo':
                    var vimeoId = typeof videoId === 'string' ? videoId : videoId.videoId;
                    return 'https://player.vimeo.com/video/' + vimeoId + 
                           '?autoplay=' + autoplay + 
                           '&controls=' + controls;

                case 'dailymotion':
                    var dmId = typeof videoId === 'string' ? videoId : videoId.videoId;
                    return 'https://www.dailymotion.com/embed/video/' + dmId + 
                           '?autoplay=' + autoplay + 
                           '&controls=' + controls;

                case 'twitch':
                    var twitchData = typeof videoId === 'object' ? videoId : { videoId: videoId, type: 'video' };
                    if (twitchData.type === 'clip') {
                        return 'https://clips.twitch.tv/embed?clip=' + twitchData.videoId + 
                               '&autoplay=' + autoplay + 
                               '&parent=' + window.location.hostname;
                    } else {
                        return 'https://player.twitch.tv/?video=v' + twitchData.videoId + 
                               '&autoplay=' + autoplay + 
                               '&parent=' + window.location.hostname;
                    }

                case 'videopress':
                    var vpId = typeof videoId === 'string' ? videoId : videoId.videoId;
                    return 'https://videopress.com/embed/' + vpId + 
                           '?autoplay=' + autoplay + 
                           '&controls=' + controls;

                case 'wistia':
                    var wistiaId = typeof videoId === 'string' ? videoId : videoId.videoId;
                    return 'https://fast.wistia.net/embed/iframe/' + wistiaId + 
                           '?autoplay=' + autoplay + 
                           '&controlsVisibleOnLoad=' + controls;

                case 'local':
                    return typeof videoId === 'string' ? videoId : null;

                default:
                    return null;
            }
        },

        /**
         * Create HTML5 video player for local videos
         * @param {string} videoUrl
         * @param {Object} settings Video settings
         * @param {string} containerClass
         * @param {string} videoClass
         * @returns {HTMLElement}
         */
        create_local_player: function(videoUrl, settings, containerClass, videoClass) {
            var container = document.createElement("div");
            container.className = containerClass || "ngg-video-container";

            var video = document.createElement("video");
            video.className = videoClass || "ngg-video-player";
            video.controls = settings.show_video_controls !== false;
            video.autoplay = settings.autoplay_videos === true;
            video.playsInline = true;
            video.preload = "auto";
            video.setAttribute("playsinline", "");
            video.setAttribute("webkit-playsinline", "");
            video.src = videoUrl;

            // Global error handler for video loading failures (CORS, network, unsupported formats)
            video.addEventListener("error", function(e) {
                console.error("Video player error:", {
                    error: e,
                    videoUrl: videoUrl,
                    errorCode: video.error ? video.error.code : "unknown",
                    errorMessage: video.error ? video.error.message : "Unknown error"
                });
            });

            // Size video to match lightbox image sizing behavior
            video.addEventListener("loadedmetadata", function () {
                var naturalWidth = video.videoWidth;
                var naturalHeight = video.videoHeight;

                if (naturalWidth && naturalHeight) {
                    var container = video.closest('.ngg-video-container');
                    var displayWidth = naturalWidth;
                    var displayHeight = naturalHeight;

                    // Detect lightbox type and apply appropriate sizing logic
                    if (container) {
                        var fancyboxContent = container.closest('#fancybox-content');
                        var tbWindow = container.closest('#TB_window');
                        var slImage = container.closest('.sl-image');
                        var shWrap = container.closest('#shWrap');

                        if (shWrap) {
                            // Shutter/Shutter Reloaded
                            var wiH = window.innerHeight || 0;
                            var dbH = document.body.clientHeight || 0;
                            var deH = document.documentElement ? document.documentElement.clientHeight : 0;
                            var wHeight;

                            if (wiH > 0) {
                                wHeight = ((wiH - dbH) > 1 && (wiH - dbH) < 30) ? dbH : wiH;
                                wHeight = ((wHeight - deH) > 1 && (wHeight - deH) < 30) ? deH : wHeight;
                            } else {
                                wHeight = (deH > 0) ? deH : dbH;
                            }

                            if (document.getElementsByTagName("body")[0].className.match(/admin-bar/)
                                && document.getElementById('wpadminbar') !== null) {
                                wHeight = wHeight - document.getElementById('wpadminbar').offsetHeight;
                            }

                            var shHeight = wHeight - 50;
                            var deW = document.documentElement ? document.documentElement.clientWidth : 0;
                            var dbW = window.innerWidth || document.body.clientWidth;
                            var wWidth = (deW > 1) ? deW : dbW;

                            if (displayHeight > shHeight) {
                                displayWidth = displayWidth * (shHeight / displayHeight);
                                displayHeight = shHeight;
                            }
                            if (displayWidth > (wWidth - 16)) {
                                displayHeight = displayHeight * ((wWidth - 16) / displayWidth);
                                displayWidth = wWidth - 16;
                            }

                            video.style.width = displayWidth + "px";
                            video.style.height = displayHeight + "px";
                            video.style.maxWidth = "none";
                            video.style.maxHeight = "none";
                            video.setAttribute("width", displayWidth);
                            video.setAttribute("height", displayHeight);
                        } else if (fancyboxContent) {
                            // Fancybox
                            setTimeout(function() {
                                var contentRect = fancyboxContent.getBoundingClientRect();
                                if (contentRect.width > 10 && contentRect.height > 10) {
                                    var maxW = contentRect.width;
                                    var maxH = contentRect.height;

                                    if (displayWidth > maxW || displayHeight > maxH) {
                                        var ratio = displayWidth / displayHeight > maxW / maxH
                                            ? displayWidth / maxW
                                            : displayHeight / maxH;
                                        displayWidth = displayWidth / ratio;
                                        displayHeight = displayHeight / ratio;
                                    }

                                    video.style.width = displayWidth + "px";
                                    video.style.height = displayHeight + "px";
                                    video.setAttribute("width", displayWidth);
                                    video.setAttribute("height", displayHeight);
                                }
                            }, 50);
                            return;
                        } else if (tbWindow) {
                            // Thickbox
                            var pageWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
                            var pageHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
                            var x = pageWidth - 150;
                            var y = pageHeight - 150;

                            if (displayWidth > x) {
                                displayHeight = displayHeight * (x / displayWidth);
                                displayWidth = x;
                                if (displayHeight > y) {
                                    displayWidth = displayWidth * (y / displayHeight);
                                    displayHeight = y;
                                }
                            } else if (displayHeight > y) {
                                displayWidth = displayWidth * (y / displayHeight);
                                displayHeight = y;
                                if (displayWidth > x) {
                                    displayHeight = displayHeight * (x / displayWidth);
                                    displayWidth = x;
                                }
                            }

                            video.style.width = displayWidth + "px";
                            video.style.height = displayHeight + "px";
                            video.setAttribute("width", displayWidth);
                            video.setAttribute("height", displayHeight);
                        } else if (slImage) {
                            // SimpleLightbox
                            var widthRatio = 0.8;
                            var heightRatio = 0.9;
                            var windowWidth = window.innerWidth;
                            var windowHeight = window.innerHeight;

                            var maxWidth = windowWidth * widthRatio;
                            var maxHeight = windowHeight * heightRatio;

                            if (displayWidth > maxWidth || displayHeight > maxHeight) {
                                var ratio = displayWidth / displayHeight > maxWidth / maxHeight
                                    ? displayWidth / maxWidth
                                    : displayHeight / maxHeight;
                                displayWidth /= ratio;
                                displayHeight /= ratio;
                            }

                            video.style.width = displayWidth + "px";
                            video.style.height = displayHeight + "px";
                            video.style.maxWidth = maxWidth + "px";
                            video.style.maxHeight = maxHeight + "px";
                        }
                    }
                }
            });

            // Attempt autoplay when ready
            if (settings.autoplay_videos) {
                video.addEventListener("canplay", function () {
                    video.play().catch(function (error) {
                        console.error("Video autoplay failed:", error);
                    });
                });
            }

            container.appendChild(video);
            return container;
        },

        /**
         * Create iframe embed for platform videos
         * @param {string} embedUrl
         * @param {Object} settings Video settings
         * @param {string} containerClass
         * @returns {HTMLElement}
         */
        create_embed_player: function(embedUrl, settings, containerClass) {
            var container = document.createElement("div");
            container.className = containerClass || "ngg-video-container";

            var iframe = document.createElement("iframe");
            iframe.src = embedUrl;
            iframe.frameBorder = "0";
            iframe.allowFullscreen = true;
            iframe.setAttribute("allow", "autoplay; encrypted-media");
            iframe.style.width = "100%";
            iframe.style.height = "100%";
            iframe.style.border = "none";

            // Global error handler for iframe loading failures (CORS, network, etc.)
            iframe.addEventListener("error", function(e) {
                console.error("Video iframe error:", {
                    error: e,
                    embedUrl: embedUrl
                });
            });

            // Handle iframe load errors (some browsers don't fire error event on iframe)
            iframe.addEventListener("load", function() {
                // Check if iframe loaded successfully by trying to access content
                try {
                    // This will throw if cross-origin restrictions prevent access
                    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                } catch (e) {
                    // Cross-origin restriction is normal, not an error
                    // Only log actual errors
                    if (e.name !== "SecurityError") {
                        console.error("Video iframe load error:", e);
                    }
                }
            });

            // Size iframe to match lightbox image sizing behavior
            // Use responsive aspect ratio (16:9 default for most platforms)
            var aspectRatio = 16 / 9;
            var maxWidth = window.innerWidth * 0.9;
            var maxHeight = window.innerHeight * 0.9;
            var width = Math.min(maxWidth, 1080);
            var height = width / aspectRatio;

            if (height > maxHeight) {
                height = maxHeight;
                width = height * aspectRatio;
            }

            container.style.width = width + "px";
            container.style.height = height + "px";
            container.style.maxWidth = "100%";
            container.style.maxHeight = "90vh";

            container.appendChild(iframe);
            return container;
        },

        /**
         * Generic content handler to inject video into a container
         * @param {Object} options
         * @param {string} options.videoUrl - Video URL
         * @param {HTMLElement|jQuery} options.container - Container to append content to
         * @param {Object} options.settings - Video settings (showVideoControls, showPlayPauseControls, autoplayVideos)
         * @param {string} [options.containerClass] - CSS class for player container
         * @param {string} [options.videoClass] - CSS class for video element
         * @param {Function} [options.onBeforeAppend] - Callback before appending
         * @returns {HTMLElement|null}
         */
        handle_content: function(options) {
            var self = this;
            var videoUrl = options.videoUrl;
            var $targetContainer = $(options.container);
            var settings = options.settings || {};

            if (!videoUrl) {
                console.error("Video URL is required");
                return null;
            }

            try {
                var platform = self.detect_platform(videoUrl);
                if (!platform) {
                    // Not a recognized video URL
                    console.warn("Unrecognized video URL:", videoUrl);
                    return null;
                }
            } catch (error) {
                console.error("Error detecting video platform:", error);
                return null;
            }

            var videoContent = null;
            var videoId = null;

            // Extract video ID based on platform
            switch (platform) {
                case 'youtube':
                    videoId = self.extract_youtube_id(videoUrl);
                    break;
                case 'vimeo':
                    videoId = self.extract_vimeo_id(videoUrl);
                    break;
                case 'dailymotion':
                    videoId = self.extract_dailymotion_id(videoUrl);
                    break;
                case 'twitch':
                    videoId = self.extract_twitch_id(videoUrl);
                    break;
                case 'videopress':
                    videoId = self.extract_videopress_id(videoUrl);
                    break;
                case 'wistia':
                    videoId = self.extract_wistia_id(videoUrl);
                    break;
                case 'local':
                    videoId = videoUrl; // For local videos, use the URL directly
                    break;
            }

            if (!videoId) {
                var errorMsg = self.create_error("Could not extract video ID from URL", options.errorClass);
                if (typeof options.onBeforeAppend === "function") options.onBeforeAppend(errorMsg);
                $targetContainer.append(errorMsg);
                return errorMsg;
            }

            // Create player based on platform
            try {
                if (platform === 'local') {
                    videoContent = self.create_local_player(videoId, settings, options.containerClass, options.videoClass);
                } else {
                    var embedUrl = self.get_embed_url(platform, videoId, settings);
                    if (embedUrl) {
                        videoContent = self.create_embed_player(embedUrl, settings, options.containerClass);
                    } else {
                        var errorMsg = self.create_error("Could not generate embed URL", options.errorClass);
                        if (typeof options.onBeforeAppend === "function") options.onBeforeAppend(errorMsg);
                        $targetContainer.append(errorMsg);
                        return errorMsg;
                    }
                }

                if (videoContent) {
                    // Handle errors for local videos
                    if (platform === 'local') {
                        var video = videoContent.querySelector("video");
                        if (video) {
                            video.onerror = function () {
                                $(videoContent).remove();
                                var errorMsg = self.create_error("Video failed to load", options.errorClass);
                                if (typeof options.onBeforeAppend === "function") options.onBeforeAppend(errorMsg);
                                $targetContainer.append(errorMsg);
                            };
                        }
                    }

                    if (typeof options.onBeforeAppend === "function") options.onBeforeAppend(videoContent);
                    $targetContainer.append(videoContent);
                }
            } catch (error) {
                console.error("Error creating video player:", error);
                var errorMsg = self.create_error("Video player creation failed", options.errorClass);
                if (typeof options.onBeforeAppend === "function") options.onBeforeAppend(errorMsg);
                $targetContainer.append(errorMsg);
                return errorMsg;
            }

            return videoContent;
        },

        /**
         * Create error message element
         * @param {string} message
         * @param {string} containerClass
         * @returns {HTMLElement}
         */
        create_error: function(message, containerClass) {
            var container = document.createElement("div");
            container.className = containerClass || "ngg-video-error";
            container.innerHTML =
                '<div class="ngg-video-error-content">' +
                '<span class="ngg-video-error-icon">&#9888;</span>' +
                '<span class="ngg-video-error-text">' +
                (message || "Video failed to load") +
                "</span>" +
                "</div>";
            return container;
        }
    };
})(jQuery);
// source --> https://www.rennsteig-bike-tour.de/wp-includes/js/comment-reply.min.js?ver=6.9.4 
/*! This file is auto-generated */
window.addComment=function(v){var I,C,h,E=v.document,b={commentReplyClass:"comment-reply-link",commentReplyTitleId:"reply-title",cancelReplyId:"cancel-comment-reply-link",commentFormId:"commentform",temporaryFormId:"wp-temp-form-div",parentIdFieldId:"comment_parent",postIdFieldId:"comment_post_ID"},e=v.MutationObserver||v.WebKitMutationObserver||v.MozMutationObserver,r="querySelector"in E&&"addEventListener"in v,n=!!E.documentElement.dataset;function t(){d(),e&&new e(o).observe(E.body,{childList:!0,subtree:!0})}function d(e){if(r&&(I=g(b.cancelReplyId),C=g(b.commentFormId),I)){I.addEventListener("touchstart",l),I.addEventListener("click",l);function t(e){if((e.metaKey||e.ctrlKey)&&13===e.keyCode&&"a"!==E.activeElement.tagName.toLowerCase())return C.removeEventListener("keydown",t),e.preventDefault(),C.submit.click(),!1}C&&C.addEventListener("keydown",t);for(var n,d=function(e){var t=b.commentReplyClass;e&&e.childNodes||(e=E);e=E.getElementsByClassName?e.getElementsByClassName(t):e.querySelectorAll("."+t);return e}(e),o=0,i=d.length;o<i;o++)(n=d[o]).addEventListener("touchstart",a),n.addEventListener("click",a)}}function l(e){var t,n,d=g(b.temporaryFormId);d&&h&&(g(b.parentIdFieldId).value="0",t=d.textContent,d.parentNode.replaceChild(h,d),this.style.display="none",n=(d=(d=g(b.commentReplyTitleId))&&d.firstChild)&&d.nextSibling,d&&d.nodeType===Node.TEXT_NODE&&t&&(n&&"A"===n.nodeName&&n.id!==b.cancelReplyId&&(n.style.display=""),d.textContent=t),e.preventDefault())}function a(e){var t=g(b.commentReplyTitleId),t=t&&t.firstChild.textContent,n=this,d=m(n,"belowelement"),o=m(n,"commentid"),i=m(n,"respondelement"),r=m(n,"postid"),n=m(n,"replyto")||t;d&&o&&i&&r&&!1===v.addComment.moveForm(d,o,i,r,n)&&e.preventDefault()}function o(e){for(var t=e.length;t--;)if(e[t].addedNodes.length)return void d()}function m(e,t){return n?e.dataset[t]:e.getAttribute("data-"+t)}function g(e){return E.getElementById(e)}return r&&"loading"!==E.readyState?t():r&&v.addEventListener("DOMContentLoaded",t,!1),{init:d,moveForm:function(e,t,n,d,o){var i,r,l,a,m,c,s,e=g(e),n=(h=g(n),g(b.parentIdFieldId)),y=g(b.postIdFieldId),p=g(b.commentReplyTitleId),u=(p=p&&p.firstChild)&&p.nextSibling;if(e&&h&&n){void 0===o&&(o=p&&p.textContent),a=h,m=b.temporaryFormId,c=g(m),s=(s=g(b.commentReplyTitleId))?s.firstChild.textContent:"",c||((c=E.createElement("div")).id=m,c.style.display="none",c.textContent=s,a.parentNode.insertBefore(c,a)),d&&y&&(y.value=d),n.value=t,I.style.display="",e.parentNode.insertBefore(h,e.nextSibling),p&&p.nodeType===Node.TEXT_NODE&&(u&&"A"===u.nodeName&&u.id!==b.cancelReplyId&&(u.style.display="none"),p.textContent=o),I.onclick=function(){return!1};try{for(var f=0;f<C.elements.length;f++)if(i=C.elements[f],r=!1,"getComputedStyle"in v?l=v.getComputedStyle(i):E.documentElement.currentStyle&&(l=i.currentStyle),(i.offsetWidth<=0&&i.offsetHeight<=0||"hidden"===l.visibility)&&(r=!0),"hidden"!==i.type&&!i.disabled&&!r){i.focus();break}}catch(e){}return!1}}}}(window);
// source --> https://www.rennsteig-bike-tour.de/wp-content/themes/spacious/js/navigation.js?ver=6.9.4 
/**
 * navigation.js
 *
 * Handles toggling the navigation menu for small screens.
 */
( function () {
	var container, button, menu, links, i, len;

	container = document.getElementById( 'site-navigation' );
	if ( ! container ) {
		return;
	}

	button = container.getElementsByClassName( 'menu-toggle' )[0];
	if ( 'undefined' === typeof button ) {
		return;
	}

	menu = container.getElementsByTagName( 'ul' )[0];

	// Hide menu toggle button if menu is empty and return early.
	if ( 'undefined' === typeof menu ) {
		button.style.display = 'none';
		return;
	}

	if ( - 1 === menu.className.indexOf( 'nav-menu' ) ) {
		menu.className += ' nav-menu';
	}

	button.onclick = function () {
		if ( - 1 !== container.className.indexOf( 'main-small-navigation' ) ) {
			container.className = container.className.replace( 'main-small-navigation', 'main-navigation' );
		} else {
			container.className = container.className.replace( 'main-navigation', 'main-small-navigation' );
		}
	};

	// Get all the link elements within the menu.
	links = menu.getElementsByTagName( 'a' );

	// Each time a menu link is focused or blurred, toggle focus.
	for ( i = 0, len = links.length; i < len; i++ ) {
		links[i].addEventListener( 'focus', toggleFocus, true );
		links[i].addEventListener( 'blur', toggleFocus, true );
	}

	/**
	 * Sets or removes .focus class on an element.
	 */
	function toggleFocus() {
		var self = this;

		// Move up through the ancestors of the current link until we hit .nav-menu.
		while ( -1 === self.className.indexOf( 'nav-menu' ) ) {
			// On li elements toggle the class .focus.
			if ( 'li' === self.tagName.toLowerCase() ) {
				if ( -1 !== self.className.indexOf( 'focus' ) ) {
					self.className = self.className.replace( ' focus', '' );
				} else {
					self.className += ' focus';
				}
			}

			self = self.parentElement;
		}
	}
} )();

// Show Submenu on click on touch enabled deviced
( function () {
	var container;
	container = document.getElementById( 'site-navigation' );

	/**
	 * Toggles `focus` class to allow submenu access on tablets.
	 */
	( function ( container ) {
		var touchStartFn, i,
		    parentLink = container.querySelectorAll( '.menu-item-has-children > a, .page_item_has_children > a' );

		if ( ( 'ontouchstart' in window ) && ( window.matchMedia( "( min-width: 768px ) " ).matches ) ) {
			touchStartFn = function ( e ) {
				var menuItem = this.parentNode, i;

				if ( ! menuItem.classList.contains( 'focus' ) ) {
					e.preventDefault();
					for ( i = 0; i < menuItem.parentNode.children.length; ++ i ) {
						if ( menuItem === menuItem.parentNode.children[i] ) {
							continue;
						}
						menuItem.parentNode.children[i].classList.remove( 'focus' );
					}
					menuItem.classList.add( 'focus' );
				} else {
					menuItem.classList.remove( 'focus' );
				}
			};

			for ( i = 0; i < parentLink.length; ++ i ) {
				parentLink[i].addEventListener( 'touchstart', touchStartFn, false );
			}
		}
	}( container ) );
} )();

/**
 * Fix: Menu out of view port
 */
( function () {

	var subMenu;

	jQuery( '.main-navigation ul li.menu-item-has-children a, .main-navigation ul li.page_item_has_children a' ).on( {

		'mouseover touchstart' : function () {

			function isElementInViewport( subMenu ) {

				if ( 'function' === typeof jQuery && subMenu instanceof jQuery ) {
					subMenu = subMenu[0];
				}

				// In case browser doesn't support getBoundingClientRect function.
				if ( 'function' === typeof subMenu.getBoundingClientRect ) {

					var rect = subMenu.getBoundingClientRect();

					if ( rect.right + 2 > ( window.innerWidth || document.documentElement.clientWidth ) ) {
						return 'spacious-menu--left'; // menu goes out of viewport from right.
					} else if ( rect.left < 0 ) {
						return 'spacious-menu--right'; // menu goes out of viewport from left.
					} else {
						return false;
					}
				}
			}

			subMenu = jQuery( this ).next( '.sub-menu, .children' );

			// If menu item has submenu
			if ( subMenu.length > 0 ) {

				var viewportClass = isElementInViewport( subMenu );

				if ( false !== viewportClass ) {
					subMenu.addClass( viewportClass );
				}
			}

		}

	} );

} )();

/**
 * Keep menu items on one line.
 */
(
	function () {

		jQuery( document ).ready( function () {
			// Get required elements.
			var mainWrapper           = document.querySelector( '#header-text-nav-container .inner-wrap' ),
			    branding              = document.getElementById( 'header-left-section' ),
			    headerAction          = document.querySelector( '.header-action' ),
			    navigation            = document.getElementById( 'site-navigation' ),
			    mainWidth             = mainWrapper ? mainWrapper.offsetWidth : 0,
			    brandWidth            = branding ? branding.offsetWidth : 0,
			    navWidth              = navigation ? navigation.offsetWidth : 0,
			    headerActionWidth     = headerAction ? headerAction.offsetWidth: 0,
			    isExtra               = ( brandWidth + navWidth + headerActionWidth ) > mainWidth,
			    more                  = navigation ? navigation.getElementsByClassName( 'tg-menu-extras-wrap' )[0] : '',
			    headerDisplayTypeFour = document.getElementsByClassName( 'spacious-header-display-four' )[0];

			// Check for header style 4.
			if ( headerDisplayTypeFour ) {
				isExtra = ( navWidth + headerActionWidth ) >= mainWidth;
			}

			// Return if no excess menu items.
			if ( ! navigation.classList.contains( 'tg-extra-menus' ) ) {
				return;
			}

			function Dimension( el ) {
				var elWidth;
				if ( document.all ) {// IE.
					elWidth = el.currentStyle.width + parseInt( el.currentStyle.marginLeft, 10 ) + parseInt( el.currentStyle.marginRight, 10 ) + parseInt( el.currentStyle.paddingLeft, 10 ) + parseInt( el.currentStyle.paddingRight, 10 );
				} else {
					elWidth = parseInt( document.defaultView.getComputedStyle( el, '' ).getPropertyValue( 'width' ) ) + parseInt( document.defaultView.getComputedStyle( el, '' ).getPropertyValue( 'margin-left' ) ) + parseInt( document.defaultView.getComputedStyle( el, '' ).getPropertyValue( 'margin-right' ) );
				}

				return elWidth;
			}

			// If menu excesses.
			if ( ! isExtra ) {
				more.parentNode.removeChild( more );
			} else {
				var widthToBe, buttons, buttonWidth, moreWidth;

				widthToBe = mainWidth - headerActionWidth;

				if ( ! headerDisplayTypeFour ) {
					widthToBe = widthToBe - brandWidth;
				}

				buttons      = navigation.getElementsByClassName( 'tg-header-button-wrap' )[0];
				buttonWidth  = buttons ? Dimension( buttons ) : 0;
				moreWidth    = more ? Dimension( more ) : 0;
				newNavWidth  = widthToBe - ( buttonWidth + moreWidth );

				navigation.style.visibility = 'none';
				navigation.style.width      = newNavWidth + 'px';

				// Returns first children of a node.
				function getChildNodes( node ) {
					var children = [];

					for ( var child in node.childNodes ) {
						if ( typeof node !== 'undefined' ) {
							if ( 1 === node.childNodes[child].nodeType ) {
								children.push( node.childNodes[child] );
							}
						}
					}

					return children;
				}

				var navUl = navigation.getElementsByClassName( 'nav-menu' )[0],
				    navLi = getChildNodes( navUl ); // Get lis.

				function offset( el ) {
					var rect       = el.getBoundingClientRect(),
					    scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
					    scrollTop  = window.pageYOffset || document.documentElement.scrollTop;

					return { top : rect.top + scrollTop, left : rect.left + scrollLeft }
				}

				var extraLi = [];

				for ( var liCount = 0; liCount < navLi.length; liCount ++ ) {
					var initialPos, li, posTop;

					li     = navLi[liCount];
					posTop = offset( li ).top;

					if ( 0 === liCount ) {
						initialPos = posTop;
					}

					if ( posTop > initialPos ) {
						if ( ! li.classList.contains( 'header-action' ) && ! li.classList.contains( 'tg-menu-extras-wrap' ) && ! li.classList.contains( 'tg-header-button-wrap' ) ) {
							extraLi.push( li );
						}
					}
				}

				var newNavWidth = newNavWidth + ( buttonWidth + moreWidth ),
				    extraWrap   = document.getElementById( 'tg-menu-extras' );

				if ( ! headerDisplayTypeFour ) {
					newNavWidth = newNavWidth - 30;
				}

				navigation.style.width = newNavWidth + 'px';

				if ( null !== extraWrap ) {
					extraLi.forEach( function ( item, index, arr ) {
						extraWrap.appendChild( item );
					} );
				}

			}
		} );

	}()
);
// source --> https://www.rennsteig-bike-tour.de/wp-content/themes/spacious/js/skip-link-focus-fix.js?ver=6.9.4 
/**
 * File skip-link-focus-fix.js.
 *
 * Helps with accessibility for keyboard only users.
 *
 * Learn more: https://git.io/vWdr2
 */
( function() {
	var isIe = /(trident|msie)/i.test( navigator.userAgent );

	if ( isIe && document.getElementById && window.addEventListener ) {
		window.addEventListener( 'hashchange', function() {
			var id = location.hash.substring( 1 ),
			    element;

			if ( ! ( /^[A-z0-9_-]+$/.test( id ) ) ) {
				return;
			}

			element = document.getElementById( id );

			if ( element ) {
				if ( ! ( /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) ) {
					element.tabIndex = -1;
				}

				element.focus();
			}
		}, false );
	}
} )();
// source --> https://www.rennsteig-bike-tour.de/wp-includes/js/hoverIntent.min.js?ver=1.10.2 
/*! This file is auto-generated */
!function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof module&&module.exports?module.exports=e(require("jquery")):jQuery&&!jQuery.fn.hoverIntent&&e(jQuery)}(function(f){"use strict";function u(e){return"function"==typeof e}var i,r,v={interval:100,sensitivity:6,timeout:0},s=0,a=function(e){i=e.pageX,r=e.pageY},p=function(e,t,n,o){if(Math.sqrt((n.pX-i)*(n.pX-i)+(n.pY-r)*(n.pY-r))<o.sensitivity)return t.off(n.event,a),delete n.timeoutId,n.isActive=!0,e.pageX=i,e.pageY=r,delete n.pX,delete n.pY,o.over.apply(t[0],[e]);n.pX=i,n.pY=r,n.timeoutId=setTimeout(function(){p(e,t,n,o)},o.interval)};f.fn.hoverIntent=function(e,t,n){function o(e){var u=f.extend({},e),r=f(this),v=((t=r.data("hoverIntent"))||r.data("hoverIntent",t={}),t[i]),t=(v||(t[i]=v={id:i}),v.timeoutId&&(v.timeoutId=clearTimeout(v.timeoutId)),v.event="mousemove.hoverIntent.hoverIntent"+i);"mouseenter"===e.type?v.isActive||(v.pX=u.pageX,v.pY=u.pageY,r.off(t,a).on(t,a),v.timeoutId=setTimeout(function(){p(u,r,v,d)},d.interval)):v.isActive&&(r.off(t,a),v.timeoutId=setTimeout(function(){var e,t,n,o,i;e=u,t=r,n=v,o=d.out,(i=t.data("hoverIntent"))&&delete i[n.id],o.apply(t[0],[e])},d.timeout))}var i=s++,d=f.extend({},v);f.isPlainObject(e)?(d=f.extend(d,e),u(d.out)||(d.out=d.over)):d=u(t)?f.extend(d,{over:e,out:t,selector:n}):f.extend(d,{over:e,out:e,selector:t});return this.on({"mouseenter.hoverIntent":o,"mouseleave.hoverIntent":o},d.selector)}});
// source --> https://www.rennsteig-bike-tour.de/wp-content/plugins/megamenu/js/maxmegamenu.js?ver=3.8.1 
/*jslint browser: true, white: true, this: true, long: true */
/*global console,jQuery,megamenu,window,navigator*/

/*! Max Mega Menu jQuery Plugin */
(function ( $ ) {
    "use strict";

    $.maxmegamenu = function(menu, options) {
        var plugin = this;
        var $menu = $(menu);
        var $wrap = $(menu).parent();
        var $toggle_bar = $menu.siblings(".mega-menu-toggle");
        var html_body_class_timeout;

        var defaults = {
            event: $menu.attr("data-event"),
            effect: $menu.attr("data-effect"),
            effect_speed: parseInt($menu.attr("data-effect-speed")),
            effect_mobile: $menu.attr("data-effect-mobile"),
            effect_speed_mobile: parseInt($menu.attr("data-effect-speed-mobile")),
            panel_width: $menu.attr("data-panel-width"),
            panel_inner_width: $menu.attr("data-panel-inner-width"),
            mobile_force_width: $menu.attr("data-mobile-force-width"),
            mobile_overlay: $menu.attr("data-mobile-overlay"),
            mobile_state: $menu.attr("data-mobile-state"),
            mobile_direction: $menu.attr("data-mobile-direction"),
            second_click: $menu.attr("data-second-click"),
            vertical_behaviour: $menu.attr("data-vertical-behaviour"),
            document_click: $menu.attr("data-document-click"),
            breakpoint: $menu.attr("data-breakpoint"),
            unbind_events: $menu.attr("data-unbind"),
            hover_intent_timeout: $menu.attr("data-hover-intent-timeout"),
            hover_intent_interval: $menu.attr("data-hover-intent-interval")
        };

        plugin.settings = {};

        var items_with_submenus = $("li.mega-menu-megamenu.mega-menu-item-has-children," +
                                    "li.mega-menu-flyout.mega-menu-item-has-children," +
                                    "li.mega-menu-tabbed > ul.mega-sub-menu > li.mega-menu-item-has-children," +
                                    "li.mega-menu-flyout li.mega-menu-item-has-children", $menu);

        var collapse_children_parents = $("li.mega-menu-megamenu li.mega-menu-item-has-children.mega-collapse-children > a.mega-menu-link", $menu);

        plugin.addAnimatingClass = function(element) {
            if (plugin.settings.effect === "disabled") {
                return;
            }

            $(".mega-animating").removeClass("mega-animating");

            var timeout = plugin.settings.effect_speed + parseInt(plugin.settings.hover_intent_timeout, 10);

            element.addClass("mega-animating");

            setTimeout(function() {
               element.removeClass("mega-animating");
            }, timeout );
        };

        plugin.hideAllPanels = function() {
            $(".mega-toggle-on > a.mega-menu-link", $menu).each(function() {
                plugin.hidePanel($(this), false);
            });
        };

        plugin.expandMobileSubMenus = function() {
            if (plugin.settings.mobile_direction !== 'vertical') {
                return;
            }
            
            $(".mega-menu-item-has-children.mega-expand-on-mobile > a.mega-menu-link", $menu).each(function() {
                plugin.showPanel($(this), true);
            });

            if ( plugin.settings.mobile_state == 'expand_all' ) {
                $(".mega-menu-item-has-children:not(.mega-toggle-on) > a.mega-menu-link", $menu).each(function() {
                    plugin.showPanel($(this), true);
                });
            }

            if ( plugin.settings.mobile_state == 'expand_active' ) {
                const activeItemSelectors = [
                    "li.mega-current-menu-ancestor.mega-menu-item-has-children > a.mega-menu-link",
                    "li.mega-current-menu-item.mega-menu-item-has-children > a.mega-menu-link",
                    "li.mega-current-menu-parent.mega-menu-item-has-children > a.mega-menu-link",
                    "li.mega-current_page_ancestor.mega-menu-item-has-children > a.mega-menu-link",
                    "li.mega-current_page_item.mega-menu-item-has-children > a.mega-menu-link"
                ];

                $menu.find(activeItemSelectors.join(', ')).each(function() {
                    plugin.showPanel($(this), true);
                });
            }
        }

        plugin.hideSiblingPanels = function(anchor, immediate) {
            anchor.parent().parent().find(".mega-toggle-on").children("a.mega-menu-link").each(function() { // all open children of open siblings
                plugin.hidePanel($(this), immediate);
            });
        };

        plugin.isDesktopView = function() {
            var width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
            return width > plugin.settings.breakpoint;
        };

        plugin.isMobileView = function() {
            return !plugin.isDesktopView();
        };

        plugin.showPanel = function(anchor, immediate) {
            if ( $.isNumeric(anchor) ) {
                anchor = $("li.mega-menu-item-" + anchor, $menu).find("a.mega-menu-link").first();
            } else if ( anchor.is("li.mega-menu-item") ) {
                anchor = anchor.find("a.mega-menu-link").first();
            }

            anchor.parent().triggerHandler("before_open_panel");

            anchor.parent().find("[aria-expanded]").first().attr("aria-expanded", "true");

            $(".mega-animating").removeClass("mega-animating");

            if (plugin.isMobileView() && anchor.parent().hasClass("mega-hide-sub-menu-on-mobile")) {
                return;
            }

            if (plugin.isDesktopView() && ( $menu.hasClass("mega-menu-horizontal") || $menu.hasClass("mega-menu-vertical") ) && !anchor.parent().hasClass("mega-collapse-children")) {
                plugin.hideSiblingPanels(anchor, true);
            }

            if ((plugin.isMobileView() && $wrap.hasClass("mega-keyboard-navigation")) || plugin.settings.vertical_behaviour === "accordion") {
                plugin.hideSiblingPanels(anchor, false);
            }

            plugin.calculateDynamicSubmenuWidths(anchor);

            // apply jQuery transition (only if the effect is set to "slide", other transitions are CSS based)
            if ( plugin.shouldUseSlideAnimation(anchor, immediate) ) {
                var speed = plugin.isMobileView() ? plugin.settings.effect_speed_mobile : plugin.settings.effect_speed;

                anchor.siblings(".mega-sub-menu").css("display", "none").animate({"height":"show", "paddingTop":"show", "paddingBottom":"show", "minHeight":"show"}, speed, function() {
                    $(this).css("display", "");
                });
            }

            anchor.parent().addClass("mega-toggle-on").triggerHandler("open_panel");
        };
        

        plugin.shouldUseSlideAnimation = function(anchor, immediate) {

            if (immediate == true) {
                return false;
            }

            if (anchor.parent().hasClass("mega-collapse-children")) {
                return true;
            }

            if (plugin.isDesktopView() && plugin.settings.effect === "slide") {
                return true;
            }

            if (plugin.isMobileView()) {
                if (plugin.settings.effect_mobile === "slide") {
                    return true;
                }

                if ( plugin.isMobileOffCanvas() ) {
                    return plugin.settings.mobile_direction !== "horizontal";
                }
            }

            return false;
        };


        plugin.hidePanel = function(anchor, immediate) {
            if ( $.isNumeric(anchor) ) {
                anchor = $("li.mega-menu-item-" + anchor, $menu).find("a.mega-menu-link").first();
            } else if ( anchor.is("li.mega-menu-item") ) {
                anchor = anchor.find("a.mega-menu-link").first();
            }

            anchor.parent().triggerHandler("before_close_panel");

            anchor.parent().find("[aria-expanded]").first().attr("aria-expanded", "false");

            if ( plugin.shouldUseSlideAnimation(anchor) ) {
                var speed = plugin.isMobileView() ? plugin.settings.effect_speed_mobile : plugin.settings.effect_speed;

                anchor.siblings(".mega-sub-menu").animate({"height":"hide", "paddingTop":"hide", "paddingBottom":"hide", "minHeight":"hide"}, speed, function() {
                    anchor.siblings(".mega-sub-menu").css("display", "");
                    anchor.parent().removeClass("mega-toggle-on").triggerHandler("close_panel");
                });

                return;
            }

            if (immediate) {
                anchor.siblings(".mega-sub-menu").css("display", "none").delay(plugin.settings.effect_speed).queue(function(){
                    $(this).css("display", "").dequeue();
                });
            }

            // pause video widget videos
            anchor.siblings(".mega-sub-menu").find(".widget_media_video video").each(function() {
                this.player.pause();
            });

            anchor.parent().removeClass("mega-toggle-on").triggerHandler("close_panel");
            plugin.addAnimatingClass(anchor.parent());
        };

        plugin.calculateDynamicSubmenuWidths = function(anchor) {
            // apply dynamic width and sub menu position (only to top level mega menus)
            if (anchor.parent().hasClass("mega-menu-megamenu") && anchor.parent().parent().hasClass("max-mega-menu") && plugin.settings.panel_width ) {
                if (plugin.isDesktopView()) {
                    var submenu_offset = $menu.offset();
                    var target_offset = $(plugin.settings.panel_width).offset();

                    if ( plugin.settings.panel_width == '100vw' ) {
                        target_offset = $('body').offset();

                        anchor.siblings(".mega-sub-menu").css({
                            left: (target_offset.left - submenu_offset.left) + "px"
                        });
                    } else if ( $(plugin.settings.panel_width).length > 0 ) {
                        anchor.siblings(".mega-sub-menu").css({
                            width: $(plugin.settings.panel_width).outerWidth(),
                            left: (target_offset.left - submenu_offset.left) + "px"
                        });
                    }
                } else {
                    anchor.siblings(".mega-sub-menu").css({
                        width: "",
                        left: ""
                    });
                }
            }

            // apply inner width to sub menu by adding padding to the left and right of the mega menu
            if (anchor.parent().hasClass("mega-menu-megamenu") && anchor.parent().parent().hasClass("max-mega-menu") && plugin.settings.panel_inner_width && $(plugin.settings.panel_inner_width).length > 0) {
                var target_width = 0;

                if ($(plugin.settings.panel_inner_width).length) {
                    // jQuery selector
                    target_width = parseInt($(plugin.settings.panel_inner_width).width(), 10);
                } else {
                    // we"re using a pixel width
                    target_width = parseInt(plugin.settings.panel_inner_width, 10);
                }

                anchor.siblings(".mega-sub-menu").css({
                    "paddingLeft": "",
                    "paddingRight": ""
                });

                var submenu_width = parseInt(anchor.siblings(".mega-sub-menu").innerWidth(), 10);

                if (plugin.isDesktopView() && target_width > 0 && target_width < submenu_width) {
                    anchor.siblings(".mega-sub-menu").css({
                        "paddingLeft": (submenu_width - target_width) / 2 + "px",
                        "paddingRight": (submenu_width - target_width) / 2 + "px"
                    });
                }
            }
        };

        plugin.bindClickEvents = function() {

            if ( $wrap.data('has-click-events') === true ) {
                return;
            }

            $wrap.data('has-click-events', true);

            var dragging = false;

            $(document).on({
                "touchmove": function(e) { dragging = true; },
                "touchstart": function(e) { dragging = false; }
            });

            $(document).on("click touchend", function(e) { // hide menu when clicked away from
                if (!dragging && plugin.settings.document_click === "collapse" && ! $(e.target).closest(".mega-menu-wrap").length ) {
                    plugin.hideAllPanels();
                    plugin.hideMobileMenu();
                }
                dragging = false;
            });

            var clickable_parents = $("> a.mega-menu-link", items_with_submenus).add(collapse_children_parents);

            clickable_parents.on("touchend.megamenu", function(e) {
                if (plugin.settings.event === "hover_intent") {
                    plugin.unbindHoverIntentEvents();
                }

                if (plugin.settings.event === "hover") {
                    plugin.unbindHoverEvents();
                }
            });

            clickable_parents.on("click.megamenu", function(e) {
                if ( $(e.target).hasClass('mega-indicator') ) {
                    return;
                }

                if (plugin.isDesktopView() && $(this).parent().hasClass("mega-toggle-on") && $(this).closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed") ) {
                    if (plugin.settings.second_click === "go") {
                        return;
                    } else {
                        e.preventDefault();
                        return;
                    }
                }
                if (dragging) {
                    return;
                }
                if (plugin.isMobileView() && $(this).parent().hasClass("mega-hide-sub-menu-on-mobile")) {
                    return; // allow all clicks on parent items when sub menu is hidden on mobile
                }
                if ((plugin.settings.second_click === "go" || $(this).parent().hasClass("mega-click-click-go")) && $(this).attr("href") !== undefined) { // check for second click
                    if (!$(this).parent().hasClass("mega-toggle-on")) {
                        e.preventDefault();
                        plugin.showPanel($(this));
                    }
                } else {
                    e.preventDefault();

                    if ($(this).parent().hasClass("mega-toggle-on")) {
                        plugin.hidePanel($(this), false);
                    } else {
                        plugin.showPanel($(this));
                    }
                }
            });

            if ( plugin.settings.second_click === "disabled" ) {
                clickable_parents.off("click.megamenu");
            }

            $(".mega-close-after-click:not(.mega-menu-item-has-children) > a.mega-menu-link", $menu).on("click", function() {
                plugin.hideAllPanels();
                plugin.hideMobileMenu();
            });

            $("button.mega-close", $wrap).on("click", function(e) {
                plugin.hideMobileMenu();
            });
        };

        plugin.bindHoverEvents = function() {
            items_with_submenus.on({
                "mouseenter.megamenu" : function() {
                    plugin.unbindClickEvents();
                    if (! $(this).hasClass("mega-toggle-on")) {
                        plugin.showPanel($(this).children("a.mega-menu-link"));
                    }
                },
                "mouseleave.megamenu" : function() {
                    if ($(this).hasClass("mega-toggle-on") && ! $(this).hasClass("mega-disable-collapse") && ! $(this).parent().parent().hasClass("mega-menu-tabbed")) {
                        plugin.hidePanel($(this).children("a.mega-menu-link"), false);
                    }
                }
            });
        };

        plugin.bindHoverIntentEvents = function() {
            items_with_submenus.hoverIntent({
                over: function () {
                    plugin.unbindClickEvents();
                    if (! $(this).hasClass("mega-toggle-on")) {
                        plugin.showPanel($(this).children("a.mega-menu-link"));
                    }
                },
                out: function () {
                    if ($(this).hasClass("mega-toggle-on") && ! $(this).hasClass("mega-disable-collapse") && ! $(this).parent().parent().hasClass("mega-menu-tabbed")) {
                        plugin.hidePanel($(this).children("a.mega-menu-link"), false);
                    }
                },
                timeout: plugin.settings.hover_intent_timeout,
                interval: plugin.settings.hover_intent_interval
            });
        };

        plugin.isMobileOffCanvas = function() {
            return plugin.settings.effect_mobile === 'slide_left' || plugin.settings.effect_mobile === 'slide_right';
        }

        plugin.bindKeyboardEvents = function() {
            const tab_key = 9;
            const escape_key = 27;
            const enter_key = 13;
            const left_arrow_key = 37;
            const up_arrow_key = 38;
            const right_arrow_key = 39;
            const down_arrow_key = 40;
            const space_key = 32;
            const $firstFocusable = $menu.find("a.mega-menu-link").first();
            const $lastFocusable = $wrap.find("button.mega-close").first();

            var isMobileOffCanvasHorizontal = function() {
                return plugin.isMobileOffCanvas() && plugin.settings.mobile_direction === 'horizontal';
            }

            var shouldTrapFocusInCurrentSubMenu = function() {
                return isMobileOffCanvasHorizontal() && ( keyCode === up_arrow_key || keyCode === down_arrow_key || keyCode === tab_key );
            }

            $lastFocusable.on('keydown.megamenu', function(e) {
                var keyCode = e.keyCode || e.which;

                if ( plugin.isMobileView() && plugin.isMobileOffCanvas() && keyCode === tab_key && ! e.shiftKey ) {
                    e.preventDefault();
                    $firstFocusable.trigger('focus');
                }
            });

            $firstFocusable.on('keydown.megamenu', function(e) {
                var keyCode = e.keyCode || e.which;

                if ( plugin.isMobileView() && plugin.isMobileOffCanvas() && keyCode === tab_key && e.shiftKey) {
                    e.preventDefault();
                    $lastFocusable.trigger('focus');
                }
            });

            $wrap.on("keyup.megamenu", ".max-mega-menu, .mega-menu-toggle", function(e) {
                var keyCode = e.keyCode || e.which;
                var active_link = $(e.target);

                if (keyCode === tab_key) {
                    $wrap.addClass("mega-keyboard-navigation");
                    plugin.bindClickEvents(); // Windows Narrator ignores the Enter keypress, so ensure click events are available when pressing tab

                    if ( plugin.isDesktopView() && keyCode === tab_key && active_link.is(".mega-menu-link") && active_link.parent().parent().hasClass('max-mega-menu') ) {
                        plugin.hideAllPanels();
                    }
                }
            });

            $wrap.on("keydown.megamenu", "a.mega-menu-link, .mega-indicator, .mega-menu-toggle-block, .mega-menu-toggle-animated-block button, button.mega-close", function(e) {

                if ( ! $wrap.hasClass("mega-keyboard-navigation") ) {
                    return;
                }

                var keyCode = e.keyCode || e.which;
                var active_link = $(e.target);

                if ( keyCode === space_key && active_link.is(".mega-menu-link") ) {
                    e.preventDefault();

                    // pressing space on a parent item will always toggle the sub menu
                    if ( active_link.parent().is(items_with_submenus) ) {
                        if ( active_link.parent().hasClass("mega-toggle-on") && ! active_link.closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed") ) {
                            plugin.hidePanel(active_link);
                        } else {
                            plugin.showPanel(active_link);
                        }
                    }
                }

                if ( keyCode === space_key && active_link.is("mega-indicator") ) {
                    e.preventDefault();

                    if ( active_link.parent().parent().hasClass("mega-toggle-on") && ! active_link.closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed") ) {
                        plugin.hidePanel(active_link.parent());
                    } else {
                        plugin.showPanel(active_link.parent());
                    }
                }

                if ( keyCode === escape_key ) {
                    var submenu_open = $(".mega-toggle-on", $menu).length !== 0;

                    if ( submenu_open ) {
                        var focused_menu_item = $menu.find(":focus");

                        if ( focused_menu_item.closest('.mega-menu-flyout.mega-toggle-on').length !== 0 ) {
                            var nearest_parent_of_focused_item_li = focused_menu_item.closest('.mega-toggle-on');
                            var nearest_parent_of_focused_item_a = $("> a.mega-menu-link", nearest_parent_of_focused_item_li);
                            plugin.hidePanel(nearest_parent_of_focused_item_a);
                            nearest_parent_of_focused_item_a.trigger('focus');
                        }

                        if ( focused_menu_item.closest('.mega-menu-megamenu.mega-toggle-on').length !== 0 ) {
                            var nearest_parent_of_focused_item_li = focused_menu_item.closest('.mega-menu-megamenu.mega-toggle-on');
                            var nearest_parent_of_focused_item_a = $("> a.mega-menu-link", nearest_parent_of_focused_item_li);
                            plugin.hidePanel(nearest_parent_of_focused_item_a);
                            nearest_parent_of_focused_item_a.trigger('focus');
                        }
                    }

                    if ( plugin.isMobileView() && ! submenu_open ) {
                        plugin.hideMobileMenu();
                    }
                }

                if ( keyCode === space_key || keyCode === enter_key ) {
                    if ( active_link.is(".mega-menu-toggle-block button, .mega-menu-toggle-animated-block button") ) {
                        e.preventDefault();
                        
                        if ( $toggle_bar.hasClass("mega-menu-open") ) {
                            plugin.hideMobileMenu();
                        } else {
                            plugin.showMobileMenu();

                            html_body_class_timeout = setTimeout(function() {
                                $menu.find("a.mega-menu-link").first().trigger('focus');
                            }, plugin.settings.effect_speed_mobile);
                        }
                    }
                }

                if ( keyCode === enter_key ) { // ignored by windows narrator

                    // pressing enter on an arrow will toggle the sub menu
                    if ( active_link.is(".mega-indicator") ) {
                        if ( active_link.closest("li.mega-menu-item").hasClass("mega-toggle-on") && ! active_link.closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed") ) {
                            plugin.hidePanel(active_link.parent());
                        } else {
                            plugin.showPanel(active_link.parent());
                        }

                        return;
                    }
                    // pressing enter on a parent link
                    if ( active_link.parent().is(items_with_submenus) ) {

                        // when clicking on the parent of a hidden submenu, follow the link
                        if ( plugin.isMobileView() && active_link.parent().is(".mega-hide-sub-menu-on-mobile") ) {
                            return;
                        }

                        // pressing enter on a parent item without a link will toggle the sub menu
                        if ( active_link.is("[href]") === false ) {
                            if ( active_link.parent().hasClass("mega-toggle-on") && ! active_link.closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed") ) {
                                plugin.hidePanel(active_link);
                            } else {
                                plugin.showPanel(active_link);
                            }

                            return;
                        }

                        // pressing enter on a parent item will first open the sub menu, then follow the link
                        if ( active_link.parent().hasClass("mega-toggle-on") && ! active_link.closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed") ) {
                            return;
                        } else {
                            e.preventDefault();
                            plugin.showPanel(active_link);
                        }
                    }
                }

                if ( shouldTrapFocusInCurrentSubMenu() ) {
                    var focused_item = $(":focus", $menu);

                    // if the menu doesn't have focus, focus the first menu item
                    if ( focused_item.length === 0) {
                        e.preventDefault();
                        $("> li.mega-menu-item:visible", $menu).find("> a.mega-menu-link, .mega-search span[role=button]").first().trigger('focus');
                        return;
                    }

                    // try to find the next item at the same level
                    var next_item_to_focus = focused_item.parent().nextAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").first();

                    // can't find another item in the same level, attempt to skip back to the top
                    if ( next_item_to_focus.length === 0 && focused_item.closest(".mega-menu-megamenu").length !== 0 ) {
                        // are we inside a megamenu? find the 'back' button and focus on that
                        var all_li_parents = focused_item.parentsUntil(".mega-menu-megamenu");

                        if ( focused_item.is(all_li_parents.find("a.mega-menu-link").last()) ) {
                            next_item_to_focus = all_li_parents.find(".mega-back-button:visible > a.mega-menu-link").first();
                        }
                    }

                    // skip back to the top of non-megamenu menus
                    if ( next_item_to_focus.length === 0 ) {
                        next_item_to_focus = focused_item.parent().prevAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").first();
                    }

                    if ( next_item_to_focus.length !== 0 ) {
                        e.preventDefault();
                        next_item_to_focus.trigger('focus');
                    }
                    
                }

                var shouldGoToNextTopLevelItem = function() {
                    return ( ( keyCode === right_arrow_key && plugin.isDesktopView() ) || ( keyCode === down_arrow_key && plugin.isMobileView() ) ) && $menu.hasClass("mega-menu-horizontal");
                }

                var shouldGoToPreviousTopLevelItem = function() {
                    return ( ( keyCode === left_arrow_key && plugin.isDesktopView() ) || ( keyCode === up_arrow_key && plugin.isMobileView() ) ) && $menu.hasClass("mega-menu-horizontal");
                }

                if ( shouldGoToNextTopLevelItem() ) {
                    e.preventDefault();

                    var next_top_level_item = $("> .mega-toggle-on", $menu).nextAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").first();

                    if (next_top_level_item.length === 0) {
                        next_top_level_item = $(":focus", $menu).parent().nextAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").first();
                    }

                    if (next_top_level_item.length === 0) {
                        next_top_level_item = $(":focus", $menu).parent().parent().parent().nextAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").first();
                    }

                    plugin.hideAllPanels();
                    next_top_level_item.trigger('focus');
                }

                if ( shouldGoToPreviousTopLevelItem() ) {
                    e.preventDefault();

                    var prev_top_level_item = $("> .mega-toggle-on", $menu).prevAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").last();

                    if (prev_top_level_item.length === 0) {
                        prev_top_level_item = $(":focus", $menu).parent().prevAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").last();
                    }

                    if (prev_top_level_item.length === 0) {
                        prev_top_level_item = $(":focus", $menu).parent().parent().parent().prevAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").last();
                    }

                    plugin.hideAllPanels();
                    prev_top_level_item.trigger('focus');
                }
            });

            $wrap.on("focusout.megamenu", function(e) {
                if ( $wrap.hasClass("mega-keyboard-navigation") ) {
                    setTimeout(function() {
                        var menu_has_focus = $wrap.find(":focus").length > 0;
                        if (! menu_has_focus) {
                            $wrap.removeClass("mega-keyboard-navigation");
                            plugin.hideAllPanels();
                            plugin.hideMobileMenu();
                        }
                    }, 10);
                }
            });
        };

        plugin.unbindAllEvents = function() {
            $("ul.mega-sub-menu, li.mega-menu-item, li.mega-menu-row, li.mega-menu-column, a.mega-menu-link, .mega-indicator", $menu).off().unbind();
        };

        plugin.unbindClickEvents = function() {
            if ( $wrap.hasClass('mega-keyboard-navigation') ) {
                return;
            }

            // collapsable parents always have a click event
            $("> a.mega-menu-link", items_with_submenus).not(collapse_children_parents).off("click.megamenu touchend.megamenu");

            $wrap.data('has-click-events', false);
        };

        plugin.unbindHoverEvents = function() {
            items_with_submenus.off("mouseenter.megamenu mouseleave.megamenu");
        };

        plugin.unbindHoverIntentEvents = function() {
            items_with_submenus.off("mouseenter mouseleave").removeProp("hoverIntent_t").removeProp("hoverIntent_s"); // hoverintent does not allow namespaced events
        };

        plugin.unbindKeyboardEvents = function() {
            $wrap.off("keyup.megamenu keydown.megamenu focusout.megamenu");
        };

        plugin.unbindMegaMenuEvents = function() {
            if (plugin.settings.event === "hover_intent") {
                plugin.unbindHoverIntentEvents();
            }

            if (plugin.settings.event === "hover") {
                plugin.unbindHoverEvents();
            }

            plugin.unbindClickEvents();
            plugin.unbindKeyboardEvents();
        };

        plugin.bindMegaMenuEvents = function() {
            plugin.unbindMegaMenuEvents();

            if (plugin.isDesktopView() && plugin.settings.event === "hover_intent") {
                plugin.bindHoverIntentEvents();
            }

            if (plugin.isDesktopView() && plugin.settings.event === "hover") {
                plugin.bindHoverEvents();
            }

            plugin.bindClickEvents(); // always bind click events for touch screen devices
            plugin.bindKeyboardEvents();
        };

        plugin.checkWidth = function() {
            if ( plugin.isMobileView() && $menu.data("view") === "desktop" ) {
                plugin.switchToMobile();
            }

            if ( plugin.isDesktopView() && $menu.data("view") === "mobile" ) {
                plugin.switchToDesktop();
            }

            plugin.calculateDynamicSubmenuWidths($("> li.mega-menu-megamenu > a.mega-menu-link", $menu));
        };

        plugin.reverseRightAlignedItems = function() {
            if ( ! $("body").hasClass("rtl") && $menu.hasClass("mega-menu-horizontal") && $menu.css("display") !== 'flex' ) {
                $menu.append($menu.children("li.mega-item-align-right").get().reverse());
            }
        };

        plugin.addClearClassesToMobileItems = function() {
            $(".mega-menu-row", $menu).each(function() {
                $("> .mega-sub-menu > .mega-menu-column:not(.mega-hide-on-mobile)", $(this)).filter(":even").addClass("mega-menu-clear"); // :even is 0 based
            });
        };

        plugin.initDesktop = function() {
            $menu.data("view", "desktop");
            plugin.bindMegaMenuEvents();
            plugin.initIndicators();
        };

        plugin.initMobile = function() {
            plugin.switchToMobile();
        };

        plugin.switchToDesktop = function() {
            $menu.data("view", "desktop");
            plugin.bindMegaMenuEvents();
            plugin.reverseRightAlignedItems();
            plugin.hideAllPanels();
            plugin.hideMobileMenu(true);
            $menu.removeAttr('role');
            $menu.removeAttr('aria-modal');
            $menu.removeAttr('aria-hidden');
        };

        plugin.switchToMobile = function() {
            $menu.data("view", "mobile");

            if (plugin.isMobileOffCanvas() && $toggle_bar.is(":visible") ) {
                $menu.attr('role', 'dialog');
                $menu.attr('aria-modal', 'true');
                $menu.attr('aria-hidden', 'true');
            }

            plugin.bindMegaMenuEvents();
            plugin.initIndicators();
            plugin.reverseRightAlignedItems();
            plugin.addClearClassesToMobileItems();
            plugin.hideAllPanels();
            plugin.expandMobileSubMenus();

        };

        plugin.initToggleBar = function() {
            $toggle_bar.on("click", function(e) {
                if ( $(e.target).is(".mega-menu-toggle, .mega-menu-toggle-custom-block *, .mega-menu-toggle-block, .mega-menu-toggle-animated-block, .mega-menu-toggle-animated-block *, .mega-toggle-blocks-left, .mega-toggle-blocks-center, .mega-toggle-blocks-right, .mega-toggle-label, .mega-toggle-label span") ) {
                    e.preventDefault();
                    
                    if ($(this).hasClass("mega-menu-open")) {
                        plugin.hideMobileMenu();
                    } else {
                        plugin.showMobileMenu();
                    }
                }
            });
        };

        plugin.initIndicators = function() {
             $menu.off('click.megamenu', '.mega-indicator');

             $menu.on('click.megamenu', '.mega-indicator', function(e) {
                e.preventDefault();
                e.stopPropagation();

                if ( $(this).closest(".mega-menu-item").hasClass("mega-toggle-on") ) {
                    if ( ! $(this).closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed") || plugin.isMobileView() ) {
                        plugin.hidePanel($(this).parent(), false);
                    }
                } else {
                    plugin.showPanel($(this).parent(), false);
                }
             });
        };

        plugin.hideMobileMenu = function(force) {
            force = force || false;

            if ( ! $toggle_bar.is(":visible") && ! force ) {
                return;
            }

            $menu.attr("aria-hidden", "true");

            html_body_class_timeout = setTimeout(function() {
                $("body").removeClass($menu.attr("id") + "-mobile-open");
                $("html").removeClass($menu.attr("id") + "-off-canvas-open");
            }, plugin.settings.effect_speed_mobile);

            if ($wrap.hasClass("mega-keyboard-navigation")) {
                $(".mega-menu-toggle-block button, button.mega-toggle-animated", $toggle_bar).first().trigger('focus');
            }

            $(".mega-toggle-label, .mega-toggle-animated", $toggle_bar).attr("aria-expanded", "false");

            if (plugin.settings.effect_mobile === "slide" && ! force ) {
                $menu.animate({"height":"hide"}, plugin.settings.effect_speed_mobile, function() {
                    $menu.css({
                        width: "",
                        left: "",
                        display: ""
                    });

                    $toggle_bar.removeClass("mega-menu-open");
                });
            } else {
                $menu.css({
                    width: "",
                    left: "",
                    display: ""
                });
                    
                $toggle_bar.removeClass("mega-menu-open");
            }

            
            $menu.triggerHandler("mmm:hideMobileMenu");
        };

        plugin.showMobileMenu = function() {
            if ( ! $toggle_bar.is(":visible") ) {
                return;
            }

            clearTimeout(html_body_class_timeout);

            $("body").addClass($menu.attr("id") + "-mobile-open");

            plugin.expandMobileSubMenus();

            if ( plugin.isMobileOffCanvas() ) {
                $("html").addClass($menu.attr("id") + "-off-canvas-open");
            }

            if (plugin.settings.effect_mobile === "slide") {
                $menu.animate({"height":"show"}, plugin.settings.effect_speed_mobile, function() {
                    $(this).css("display", "");
                });
            }

            $(".mega-toggle-label, .mega-toggle-animated", $toggle_bar).attr("aria-expanded", "true");

            $toggle_bar.addClass("mega-menu-open");

            plugin.toggleBarForceWidth();

            $menu.attr("aria-hidden", "false");
            $menu.triggerHandler("mmm:showMobileMenu");
        };

        plugin.toggleBarForceWidth = function() {
            if ($(plugin.settings.mobile_force_width).length && ( plugin.settings.effect_mobile === "slide" || plugin.settings.effect_mobile === "disabled" ) ) {
                var submenu_offset = $toggle_bar.offset();
                var target_offset = $(plugin.settings.mobile_force_width).offset();

                $menu.css({
                    width: $(plugin.settings.mobile_force_width).outerWidth(),
                    left: (target_offset.left - submenu_offset.left) + "px"
                });
            }
        };

        plugin.doConsoleChecks = function() {
            if (plugin.settings.mobile_force_width != "false" && ! $(plugin.settings.mobile_force_width).length && ( plugin.settings.effect_mobile === "slide" || plugin.settings.effect_mobile === "disabled" ) ) {
                console.warn('Max Mega Menu #' + $wrap.attr('id') + ': Mobile Force Width element (' + plugin.settings.mobile_force_width + ') not found');
            }

            const cssWidthRegex = /^((\d+(\.\d+)?(px|%|em|rem|vw|vh|ch|ex|cm|mm|in|pt|pc))|auto)$/i;

            if (plugin.settings.panel_width !== undefined && ! cssWidthRegex.test(plugin.settings.panel_width) && ! $(plugin.settings.panel_width).length ) {
                console.warn('Max Mega Menu #' + $wrap.attr('id') + ': Panel Width (Outer) element (' + plugin.settings.panel_width + ') not found');
            }

            if (plugin.settings.panel_inner_width !== undefined && ! cssWidthRegex.test(plugin.settings.panel_inner_width) && ! $(plugin.settings.panel_inner_width).length ) {
                console.warn('Max Mega Menu #' + $wrap.attr('id') + ': Panel Width (Inner) element (' + plugin.settings.panel_inner_width + ') not found');
            }
        }

        plugin.init = function() {
            $menu.triggerHandler("before_mega_menu_init");
            plugin.settings = $.extend({}, defaults, options);

            if (window.console) {
                plugin.doConsoleChecks();
            }

            $menu.removeClass("mega-no-js");

            plugin.initToggleBar();
            
            if (plugin.settings.unbind_events === "true") {
                plugin.unbindAllEvents();
            }

            $(window).on("load", function() {
                plugin.calculateDynamicSubmenuWidths($("> li.mega-menu-megamenu > a.mega-menu-link", $menu));
            });

            if ( plugin.isDesktopView() ) {
                plugin.initDesktop();
            } else {
                plugin.initMobile();
            }

            $(window).on("resize", function() {
                plugin.checkWidth();
            });

            $menu.triggerHandler("after_mega_menu_init");
        };

        plugin.init();
    };

    $.fn.maxmegamenu = function(options) {
        return this.each(function() {
            if (undefined === $(this).data("maxmegamenu")) {
                var plugin = new $.maxmegamenu(this, options);
                $(this).data("maxmegamenu", plugin);
            }
        });
    };

    $(function() {
        $(".max-mega-menu").maxmegamenu();
    });
}( jQuery ));