// source --> https://www.rennsteig-bike-tour.de/wp-content/plugins/nextgen-gallery/static/GalleryDisplay/common.js?ver=4.1.3 
(function($) {
    window.NggPaginatedGallery = function(displayed_gallery_id, container) {
        this.displayed_gallery_id = displayed_gallery_id;
        this.container            = $(container);
        this.container_name       = container;

        this.get_displayed_gallery_obj = function() {
            var index = 'gallery_' + this.displayed_gallery_id;
            if (typeof(window.galleries[index]) == 'undefined') {
                return false;
            } else {
                return window.galleries[index];
            }
        };

        this.enable_ajax_pagination = function() {
            var self = this;
            // Attach a click event handler for each pagination link to adjust the request to be sent via XHR
            $('body').on('click', 'a.ngg-browser-prev, a.ngg-browser-next', function (event) {

                var skip = true;
                $(this).parents(container).each(function() {
                    if ($(this).data('nextgen-gallery-id') != self.displayed_gallery_id) {
                        return true;
                    }
                    skip = false;
                });

                if (!skip) {
                    event.preventDefault();
                } else {
                    return;
                }

                // Adjust the user notification
                window['ngg_ajax_operaton_count']++;
                $('body, a').css('cursor', 'wait');

                // Send the AJAX request
                $.get({
                    url: $(this).attr('href'),
                    headers: { 'X-NGG-Pagination-Request': true },
                    success: function (response) {
                        window['ngg_ajax_operaton_count']--;
                        if (window['ngg_ajax_operaton_count'] <= 0) {
                            window['ngg_ajax_operaton_count'] = 0;
                            $('body, a').css('cursor', 'auto');
                        }

                        if (response) {
                            var html = $(response);
                            var replacement = false;
                            html.find(self.container_name).each(function() {
                                if (replacement) {
                                    return true;
                                }
                                if ($(this).data('nextgen-gallery-id') != self.displayed_gallery_id) {
                                    return true;
                                }
                                replacement = $(this);
                            });
                            if (replacement) {
                                self.container.each(function () {
                                    var $this = $(this);

                                    if ($this.data('nextgen-gallery-id') != self.displayed_gallery_id) {
                                        return true;
                                    }

                                    // If the image gallery makes up the bulk of the post/page content the .html() call
                                    // below will empty the contents causing the browser's scroll position to be reset to
                                    // zero as the browser believes it has been pushed back to the top of the page. Here
                                    // we give the parent container a min-height equal to the gallery's height to prevent
                                    // this flicker and resetting of the scroll position.
                                    var $new_element = $(replacement.html());
                                    var promises = $new_element.find('img').toArray().map(function(img){
                                        return new Promise(function(resolve, reject){
                                            var i = new Image();
                                            i.src = img.src;
                                            $(i).on('load', resolve);
                                        });
                                    });

                                    Promise.all(promises).then(function(){
                                        $this.html($new_element);

                                        // Let the user know that we've refreshed the content
                                        $(document).trigger('refreshed');

                                        // Emit an event that doesn't require jQuery
                                        const event = new Event("nextgen_page_refreshed");
                                        document.dispatchEvent(event);
                                    });

                                    return true;
                                });
                            }
                        }
                    }
                });
            });
        };

        // Initialize
        var displayed_gallery = this.get_displayed_gallery_obj();
        if (displayed_gallery) {
            if (typeof(displayed_gallery.display_settings['ajax_pagination']) != 'undefined') {
                if (parseInt(displayed_gallery.display_settings['ajax_pagination'])) {
                    this.enable_ajax_pagination();
                }
            }
        }

        // We maintain a count of all the current AJAX actions initiated
        if (typeof(window['ngg_ajax_operation_count']) == 'undefined') {
            window['ngg_ajax_operaton_count'] = 0;
        }
    };

    // Polyfill for older browsers
    Object.setPrototypeOf = Object.setPrototypeOf || function(obj, proto) {
        obj.__proto__ = proto;
        return obj;
    };

    if (typeof window.galleries !== 'undefined') {
    Object.setPrototypeOf(
        window.galleries,
        {
            get_api_version: function() {
                return '0.1';
            },

            get_from_id: function (gallery_id) {
                var self   = this;
                var retval = null;
                var keys   = Object.keys(this);

                for (var i = 1; i <= keys.length; i++) {
                    var gallery = self[keys[i - 1]];
                    if (gallery.ID === gallery_id || gallery.ID === 'gallery_' + gallery_id || gallery.ID === parseInt(gallery_id)) {
                        retval = gallery;
                        break;
                    }
                }

                return retval;
            },

            get_from_slug: function (slug) {
                var self   = this;
                var retval = null;
                var keys   = Object.keys(this);

                for (var i = 1; i <= keys.length; i++) {
                    var gallery = self[keys[i - 1]];
                    if (gallery.slug === slug) {
                        retval = gallery;
                        break;
                    }
                }

                return retval;
            },

            get_setting: function(gallery_id, name, def) {
                var tmp = '';
                var gallery = this.get_from_id(gallery_id);
                if (gallery && typeof gallery[name] !== 'undefined') {
                    tmp = gallery[name];
                } else {
                    tmp = def;
                }

                if (tmp === 1)       tmp = true;
                if (tmp === 0)       tmp = false;
                if (tmp === '1')     tmp = true;
                if (tmp === '0')     tmp = false;
                if (tmp === 'false') tmp = false;
                if (tmp === 'true')  tmp = true;

                return tmp;
            },

            get_display_setting: function(gallery_id, name, def) {
                var tmp = '';
                var gallery = this.get_from_id(gallery_id);
                if (gallery && typeof gallery.display_settings[name] !== 'undefined') {
                    tmp = gallery.display_settings[name];
                } else {
                    tmp = def;
                }

                if (tmp === 1)       tmp = true;
                if (tmp === 0)       tmp = false;
                if (tmp === '1')     tmp = true;
                if (tmp === '0')     tmp = false;
                if (tmp === 'false') tmp = false;
                if (tmp === 'true')  tmp = true;

                return tmp;
            },

            is_widget: function(gallery_id) {
                var retval  = false;
                var gallery = this.get_from_id(gallery_id);
                var slug    = gallery.slug;

                if (slug) {
                    return slug.indexOf('widget-ngg-images') !== -1;
                }

                return retval;
            }
        }
    ); }

})(jQuery);
// source --> https://www.rennsteig-bike-tour.de/wp-content/plugins/nextgen-gallery/static/Lightbox/lightbox_context.js?ver=4.1.3 
function nextgen_lightbox_filter_selector($, selector)
{
		if (nextgen_lightbox_settings && nextgen_lightbox_settings.context) {
			var context = nextgen_lightbox_settings.context;
			
			if (context == 'all_images') {
				 selector = selector.add($('a > img').parent());
			}
			else if (context == 'all_images_direct') {
				selector = selector.add($('a[href] > img').parent()
				 		.filter(function() {
							var href = $(this).attr('href').toLowerCase();
							var ext = href.substring(href.length - 3);
							var ext2 = href.substring(href.length - 4);
							
							return (ext == 'jpg' || ext == 'gif' || ext == 'png' || ext2 == 'tiff' || ext2 == 'jpeg' || ext2 == 'webp');
						}));
			}
			else if (context == 'nextgen_and_wp_images') {
				 selector = selector.add($('a > img[class*="wp-image-"]').parent());
			}
			
			selector = selector.not('.gallery_link');
            selector = selector.not('.use_imagebrowser_effect');
		}
		
		return selector;
};
// source --> https://www.rennsteig-bike-tour.de/wp-content/plugins/nextgen-gallery/static/Lightbox/fancybox/jquery.easing-1.3.pack.js?ver=4.1.3 
/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('h.i[\'1a\']=h.i[\'z\'];h.O(h.i,{y:\'D\',z:9(x,t,b,c,d){6 h.i[h.i.y](x,t,b,c,d)},17:9(x,t,b,c,d){6 c*(t/=d)*t+b},D:9(x,t,b,c,d){6-c*(t/=d)*(t-2)+b},13:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t+b;6-c/2*((--t)*(t-2)-1)+b},X:9(x,t,b,c,d){6 c*(t/=d)*t*t+b},U:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t+1)+b},R:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t+b;6 c/2*((t-=2)*t*t+2)+b},N:9(x,t,b,c,d){6 c*(t/=d)*t*t*t+b},M:9(x,t,b,c,d){6-c*((t=t/d-1)*t*t*t-1)+b},L:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t+b;6-c/2*((t-=2)*t*t*t-2)+b},K:9(x,t,b,c,d){6 c*(t/=d)*t*t*t*t+b},J:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t*t*t+1)+b},I:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t*t+b;6 c/2*((t-=2)*t*t*t*t+2)+b},G:9(x,t,b,c,d){6-c*8.C(t/d*(8.g/2))+c+b},15:9(x,t,b,c,d){6 c*8.n(t/d*(8.g/2))+b},12:9(x,t,b,c,d){6-c/2*(8.C(8.g*t/d)-1)+b},Z:9(x,t,b,c,d){6(t==0)?b:c*8.j(2,10*(t/d-1))+b},Y:9(x,t,b,c,d){6(t==d)?b+c:c*(-8.j(2,-10*t/d)+1)+b},W:9(x,t,b,c,d){e(t==0)6 b;e(t==d)6 b+c;e((t/=d/2)<1)6 c/2*8.j(2,10*(t-1))+b;6 c/2*(-8.j(2,-10*--t)+2)+b},V:9(x,t,b,c,d){6-c*(8.o(1-(t/=d)*t)-1)+b},S:9(x,t,b,c,d){6 c*8.o(1-(t=t/d-1)*t)+b},Q:9(x,t,b,c,d){e((t/=d/2)<1)6-c/2*(8.o(1-t*t)-1)+b;6 c/2*(8.o(1-(t-=2)*t)+1)+b},P:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6-(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b},H:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6 a*8.j(2,-10*t)*8.n((t*d-s)*(2*8.g)/p)+c+b},T:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d/2)==2)6 b+c;e(!p)p=d*(.3*1.5);e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);e(t<1)6-.5*(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b;6 a*8.j(2,-10*(t-=1))*8.n((t*d-s)*(2*8.g)/p)*.5+c+b},F:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*(t/=d)*t*((s+1)*t-s)+b},E:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*((t=t/d-1)*t*((s+1)*t+s)+1)+b},16:9(x,t,b,c,d,s){e(s==u)s=1.l;e((t/=d/2)<1)6 c/2*(t*t*(((s*=(1.B))+1)*t-s))+b;6 c/2*((t-=2)*t*(((s*=(1.B))+1)*t+s)+2)+b},A:9(x,t,b,c,d){6 c-h.i.v(x,d-t,0,c,d)+b},v:9(x,t,b,c,d){e((t/=d)<(1/2.k)){6 c*(7.q*t*t)+b}m e(t<(2/2.k)){6 c*(7.q*(t-=(1.5/2.k))*t+.k)+b}m e(t<(2.5/2.k)){6 c*(7.q*(t-=(2.14/2.k))*t+.11)+b}m{6 c*(7.q*(t-=(2.18/2.k))*t+.19)+b}},1b:9(x,t,b,c,d){e(t<d/2)6 h.i.A(x,t*2,0,c,d)*.5+b;6 h.i.v(x,t*2-d,0,c,d)*.5+c*.5+b}});',62,74,'||||||return||Math|function|||||if|var|PI|jQuery|easing|pow|75|70158|else|sin|sqrt||5625|asin|||undefined|easeOutBounce|abs||def|swing|easeInBounce|525|cos|easeOutQuad|easeOutBack|easeInBack|easeInSine|easeOutElastic|easeInOutQuint|easeOutQuint|easeInQuint|easeInOutQuart|easeOutQuart|easeInQuart|extend|easeInElastic|easeInOutCirc|easeInOutCubic|easeOutCirc|easeInOutElastic|easeOutCubic|easeInCirc|easeInOutExpo|easeInCubic|easeOutExpo|easeInExpo||9375|easeInOutSine|easeInOutQuad|25|easeOutSine|easeInOutBack|easeInQuad|625|984375|jswing|easeInOutBounce'.split('|'),0,{}))

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */;
// source --> https://www.rennsteig-bike-tour.de/wp-content/plugins/nextgen-gallery/static/Lightbox/fancybox/jquery.fancybox-1.3.4.pack.js?ver=4.1.3 
(s=>{function i(){f.hide(),k.onerror=k.onload=null,C&&C.abort(),l.empty()}function h(){!1===w.onError(m,u,w)?(f.hide(),A=!1):(w.titleShow=!1,w.width="auto",w.height="auto",l.html('<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>'),E())}function a(){var n,t,e,a,o,d,c,r=m[u];if(i(),w=s.extend({},s.fn.fancybox.defaults,void 0===s(r).data("fancybox")?w:s(r).data("fancybox")),!1===(d=w.onStart(m,u,w)))A=!1;else{e=(w="object"==typeof d?s.extend(w,d):w).title||(r.nodeName?s(r).attr("title"):r.title)||"",r.nodeName&&!w.orig&&(w.orig=s(r).children("img:first").length?s(r).children("img:first"):s(r)),""===e&&w.orig&&w.titleFromAlt&&(e=w.orig.attr("alt"));let i={A:["href","class","title"],BR:[],EM:[],I:[],STRONG:[],B:[],U:[],P:["class"],DIV:["class","id"],SPAN:["class","id"]};if(c=e,(c=(new DOMParser).parseFromString(c,"text/html")).body.querySelectorAll("*").forEach(e=>{i[e.tagName]?[...e.attributes].forEach(t=>{i[e.tagName].includes(t.name)||e.removeAttribute(t.name)}):e.remove()}),e=c.body.innerHTML,n=w.href||(r.nodeName?s(r).attr("href"):r.href)||null,!/^(?:javascript)/i.test(n)&&"#"!=n||(n=null),w.type?(t=w.type,n=n||w.content):w.content?t="html":n&&(t=n.match(O)?"image":n.match(z)?"swf":s(r).hasClass("iframe")?"iframe":0===n.indexOf("#")?"inline":"ajax"),t)switch("inline"==t&&(r=n.substr(n.indexOf("#")),t=0<s(r).length?"inline":"ajax"),w.type=t,w.href=n,w.title=e,w.autoDimensions&&("html"==w.type||"inline"==w.type||"ajax"==w.type?(w.width="auto",w.height="auto"):w.autoDimensions=!1),w.modal&&(w.overlayShow=!0,w.hideOnOverlayClick=!1,w.hideOnContentClick=!1,w.enableEscapeButton=!1,w.showCloseButton=!1),w.padding=parseInt(w.padding,10),w.margin=parseInt(w.margin,10),l.css("padding",w.padding+w.margin),s(".fancybox-inline-tmp").off("fancybox-cancel").on("fancybox-change",function(){s(this).replaceWith(p.children())}),t){case"html":l.html(w.content),E();break;case"inline":!0===s(r).parent().is("#fancybox-content")?A=!1:(s('<div class="fancybox-inline-tmp" />').hide().insertBefore(s(r)).on("fancybox-cleanup",function(){s(this).replaceWith(p.children())}).on("fancybox-cancel",function(){s(this).replaceWith(l.children())}),s(r).appendTo(l),E());break;case"image":A=!1,s.fancybox.showActivity(),(k=new Image).onerror=function(){h()},k.onload=function(){A=!0,k.onerror=k.onload=null,w.width=k.width,w.height=k.height,s("<img />").attr({id:"fancybox-img",src:k.src,alt:w.title}).appendTo(l),P()},k.src=n;break;case"swf":w.scrolling="no",a='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+w.width+'" height="'+w.height+'"><param name="movie" value="'+n+'"></param>',o="",s.each(w.swf,function(t,e){a+='<param name="'+t+'" value="'+e+'"></param>',o+=" "+t+'="'+e+'"'}),a+='<embed src="'+n+'" type="application/x-shockwave-flash" width="'+w.width+'" height="'+w.height+'"'+o+"></embed></object>",l.html(a),E();break;case"ajax":A=!1,s.fancybox.showActivity(),w.ajax.win=w.ajax.success,C=s.ajax(s.extend({},w.ajax,{url:n,data:w.ajax.data||{},error:function(t,e,i){0<t.status&&h()},success:function(t,e,i){if(200==("object"==typeof i?i:C).status){if("function"==typeof w.ajax.win){if(!1===(d=w.ajax.win(n,t,e,i)))return void f.hide();"string"!=typeof d&&"object"!=typeof d||(t=d)}l.html(t),E()}}}));break;case"iframe":P()}else h()}}function M(t){var e=t.offset();return e.top+=parseInt(t.css("paddingTop"),10)||0,e.left+=parseInt(t.css("paddingLeft"),10)||0,e.top+=parseInt(t.css("border-top-width"),10)||0,e.left+=parseInt(t.css("border-left-width"),10)||0,e.width=t.width(),e.height=t.height(),e}function L(){f.is(":visible")?(s("div",f).css("top",-40*j+"px"),j=(j+1)%12):clearInterval(e)}var l,f,n,o,t,p,d,c,r,g,e,b,y,u=0,w={},m=[],x=0,v={},I=[],C=null,k=new Image,O=/\.(jpg|gif|png|bmp|jpeg|webp)(.*)?$/i,z=/[^\.]\.(swf)\s*$/i,j=1,S=0,T="",A=!1,D=s.extend(s("<div/>")[0],{prop:0}),N=!1,E=function(){var t=w.width,e=w.height,t=-1<t.toString().indexOf("%")?parseInt((s(window).width()-2*w.margin)*parseFloat(t)/100,10)+"px":"auto"==t?"auto":t+"px",e=-1<e.toString().indexOf("%")?parseInt((s(window).height()-2*w.margin)*parseFloat(e)/100,10)+"px":"auto"==e?"auto":e+"px";l.wrapInner('<div style="width:'+t+";height:"+e+";overflow: "+("auto"==w.scrolling?"auto":"yes"==w.scrolling?"scroll":"hidden")+';position:relative;"></div>'),w.width=l.width(),w.height=l.height(),P()},P=function(){var t,e;f.hide(),o.is(":visible")&&!1===v.onCleanup(I,x,v)?(s.event.trigger("fancybox-cancel"),A=!1):(A=!0,s(p.add(n)).off(),s(window).off("resize.fb scroll.fb"),s(document).off("keydown.fb"),o.is(":visible")&&"outside"!==v.titlePosition&&o.css("height",o.height()),I=m,x=u,(v=w).overlayShow?(n.css({"background-color":v.overlayColor,opacity:v.overlayOpacity,cursor:v.hideOnOverlayClick?"pointer":"auto",height:s(document).height()}),n.is(":visible")||(N&&s("select:not(#fancybox-tmp select)").filter(function(){return"hidden"!==this.style.visibility}).css({visibility:"hidden"}).one("fancybox-cleanup",function(){this.style.visibility="inherit"}),n.show())):n.hide(),y=q(),R(),o.is(":visible")?(s(d.add(r).add(g)).hide(),t=o.position(),b={top:t.top,left:t.left,width:o.width(),height:o.height()},e=b.width==y.width&&b.height==y.height,p.fadeTo(v.changeFade,.3,function(){function t(){p.html(l.contents()).fadeTo(v.changeFade,1,F)}s.event.trigger("fancybox-change"),p.empty().removeAttr("filter").css({"border-width":v.padding,width:y.width-2*v.padding,height:w.autoDimensions?"auto":y.height-S-2*v.padding}),e?t():(D.prop=0,s(D).animate({prop:1},{duration:v.changeSpeed,easing:v.easingChange,step:B,complete:t}))})):(o.removeAttr("style"),p.css("border-width",v.padding),"elastic"==v.transitionIn?(b=U(),p.html(l.contents()),o.show(),v.opacity&&(y.opacity=0),D.prop=0,s(D).animate({prop:1},{duration:v.speedIn,easing:v.easingIn,step:B,complete:F})):("inside"==v.titlePosition&&0<S&&c.show(),p.css({width:y.width-2*v.padding,height:w.autoDimensions?"auto":y.height-S-2*v.padding}).html(l.contents()),o.css(y).fadeIn("none"==v.transitionIn?0:v.speedIn,F))))},H=function(t){return!(!t||!t.length)&&("float"==v.titlePosition?'<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">'+t+'</td><td id="fancybox-title-float-right"></td></tr></table>':'<div id="fancybox-title-'+v.titlePosition+'">'+t+"</div>")},R=function(){if((T=v.title||"",S=0,c.empty().removeAttr("style").removeClass(),!1!==v.titleShow)&&((T="function"==typeof v.titleFormat?v.titleFormat(T,I,x,v):H(T))&&""!==T))switch(c.addClass("fancybox-title-"+v.titlePosition).html(T).appendTo("body").show(),v.titlePosition){case"inside":c.css({width:y.width-2*v.padding,marginLeft:v.padding,marginRight:v.padding}),S=c.outerHeight(!0),c.appendTo(t),y.height+=S;break;case"over":c.css({marginLeft:v.padding,width:y.width-2*v.padding,bottom:v.padding}).appendTo(t);break;case"float":c.css("left",-1*parseInt((c.width()-y.width-40)/2,10)).appendTo(o);break;default:c.css({width:y.width-2*v.padding,paddingLeft:v.padding,paddingRight:v.padding}).appendTo(o)}c.hide()},K=function(){(v.enableEscapeButton||v.enableKeyboardNav)&&s(document).on("keydown.fb",function(t){27==t.keyCode&&v.enableEscapeButton?(t.preventDefault(),s.fancybox.close()):37!=t.keyCode&&39!=t.keyCode||!v.enableKeyboardNav||"INPUT"===t.target.tagName||"TEXTAREA"===t.target.tagName||"SELECT"===t.target.tagName||(t.preventDefault(),s.fancybox[37==t.keyCode?"prev":"next"]())}),v.showNavArrows?((v.cyclic&&1<I.length||0!==x)&&r.show(),(v.cyclic&&1<I.length||x!=I.length-1)&&g.show()):(r.hide(),g.hide())},F=function(){s.support.opacity||(p.get(0).style.removeProperty("filter"),o.get(0).style.removeProperty("filter")),w.autoDimensions&&p.css("height","auto"),o.css("height","auto"),T&&T.length&&c.show(),v.showCloseButton&&d.show(),K(),v.hideOnContentClick&&p.on("click",s.fancybox.close),v.hideOnOverlayClick&&n.on("click",s.fancybox.close),s(window).on("resize.fb",s.fancybox.resize),v.centerOnScroll&&s(window).on("scroll.fb",s.fancybox.center),"iframe"==v.type&&s('<iframe id="fancybox-frame" name="fancybox-frame'+(new Date).getTime()+'" frameborder="0" hspace="0"  scrolling="'+w.scrolling+'" src="'+v.href+'"></iframe>').appendTo(p),o.show(),A=!1,s.fancybox.center(),v.onComplete(I,x,v),Q()},Q=function(){var t;I.length-1>x&&void 0!==(t=I[x+1].href)&&t.match(O)&&((new Image).src=t),0<x&&void 0!==(t=I[x-1].href)&&t.match(O)&&((new Image).src=t)},B=function(t){var e={width:parseInt(b.width+(y.width-b.width)*t,10),height:parseInt(b.height+(y.height-b.height)*t,10),top:parseInt(b.top+(y.top-b.top)*t,10),left:parseInt(b.left+(y.left-b.left)*t,10)};void 0!==y.opacity&&(e.opacity=t<.5?.5:t),o.css(e),p.css({width:e.width-2*v.padding,height:e.height-S*t-2*v.padding})},W=function(){return[s(window).width()-2*v.margin,s(window).height()-2*v.margin,s(document).scrollLeft()+v.margin,s(document).scrollTop()+v.margin]},q=function(){var t=W(),e={},i=v.autoScale,n=2*v.padding;return-1<v.width.toString().indexOf("%")?e.width=parseInt(t[0]*parseFloat(v.width)/100,10):e.width=v.width+n,-1<v.height.toString().indexOf("%")?e.height=parseInt(t[1]*parseFloat(v.height)/100,10):e.height=v.height+n,i&&(e.width>t[0]||e.height>t[1])&&("image"==w.type||"swf"==w.type?(i=v.width/v.height,e.width>t[0]&&(e.width=t[0],e.height=parseInt((e.width-n)/i+n,10)),e.height>t[1]&&(e.height=t[1],e.width=parseInt((e.height-n)*i+n,10))):(e.width=Math.min(e.width,t[0]),e.height=Math.min(e.height,t[1]))),e.top=parseInt(Math.max(t[3]-20,t[3]+.5*(t[1]-e.height-40)),10),e.left=parseInt(Math.max(t[2]-20,t[2]+.5*(t[0]-e.width-40)),10),e},U=function(){var t=!!w.orig&&s(w.orig);return t&&t.length?{width:(t=M(t)).width+2*v.padding,height:t.height+2*v.padding,top:t.top-v.padding-20,left:t.left-v.padding-20}:(t=W(),{width:2*v.padding,height:2*v.padding,top:parseInt(t[3]+.5*t[1],10),left:parseInt(t[2]+.5*t[0],10)})};s.fn.fancybox=function(t){return s(this).length&&s(this).data("fancybox",s.extend({},t,s.metadata?s(this).metadata():{})).off("click.fb").on("click.fb",function(t){t.preventDefault(),A||(A=!0,s(this).trigger("blur"),m=[],u=0,(t=s(this).attr("rel")||"")&&""!=t&&"nofollow"!==t?(m=s("a[rel="+t+"], area[rel="+t+"]"),u=m.index(this)):m.push(this),a())}),this},s.fancybox=function(t){var e;if(!A){if(A=!0,e=void 0!==arguments[1]?arguments[1]:{},m=[],u=parseInt(e.index,10)||0,Array.isArray(t)){for(var i=0,n=t.length;i<n;i++)"object"==typeof t[i]?s(t[i]).data("fancybox",s.extend({},e,t[i])):t[i]=s({}).data("fancybox",s.extend({content:t[i]},e));m=jQuery.merge(m,t)}else"object"==typeof t?s(t).data("fancybox",s.extend({},e,t)):t=s({}).data("fancybox",s.extend({content:t},e)),m.push(t);(u>m.length||u<0)&&(u=0),a()}},s.fancybox.showActivity=function(){clearInterval(e),f.show(),e=setInterval(L,66)},s.fancybox.hideActivity=function(){f.hide()},s.fancybox.next=function(){return s.fancybox.pos(x+1)},s.fancybox.prev=function(){return s.fancybox.pos(x-1)},s.fancybox.pos=function(t){A||(t=parseInt(t),m=I,-1<t&&t<I.length?(u=t,a()):v.cyclic&&1<I.length&&(u=t>=I.length?0:I.length-1,a()))},s.fancybox.cancel=function(){A||(A=!0,s.event.trigger("fancybox-cancel"),i(),w.onCancel(m,u,w),A=!1)},s.fancybox.close=function(){var t;function e(){n.fadeOut("fast"),c.empty().hide(),o.hide(),s.event.trigger("fancybox-cleanup"),p.empty(),v.onClosed(I,x,v),I=w=[],x=u=0,v=w={},A=!1}A||o.is(":hidden")||(A=!0,v&&!1===v.onCleanup(I,x,v)?A=!1:(i(),s(d.add(r).add(g)).hide(),s(p.add(n)).off(),s(window).off("resize.fb scroll.fb"),s(document).off("keydown.fb"),p.find("iframe").attr("src",N&&/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank"),"inside"!==v.titlePosition&&c.empty(),o.stop(),"elastic"==v.transitionOut?(b=U(),t=o.position(),y={top:t.top,left:t.left,width:o.width(),height:o.height()},v.opacity&&(y.opacity=1),c.empty().hide(),D.prop=1,s(D).animate({prop:0},{duration:v.speedOut,easing:v.easingOut,step:B,complete:e})):o.fadeOut("none"==v.transitionOut?0:v.speedOut,e)))},s.fancybox.resize=function(){n.is(":visible")&&n.css("height",s(document).height()),s.fancybox.center(!0)},s.fancybox.center=function(){var t,e;A||(e=!0===arguments[0]?1:0,t=W(),!e&&(o.width()>t[0]||o.height()>t[1]))||o.stop().animate({top:parseInt(Math.max(t[3]-20,t[3]+.5*(t[1]-p.height()-40)-v.padding)),left:parseInt(Math.max(t[2]-20,t[2]+.5*(t[0]-p.width()-40)-v.padding))},"number"==typeof arguments[0]?arguments[0]:200)},s.fancybox.init=function(){s("#fancybox-wrap").length||(s("body").append(l=s('<div id="fancybox-tmp"></div>'),f=s('<div id="fancybox-loading"><div></div></div>'),n=s('<div id="fancybox-overlay"></div>'),o=s('<div id="fancybox-wrap"></div>')),(t=s('<div id="fancybox-outer"></div>').append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>').appendTo(o)).append(p=s('<div id="fancybox-content"></div>'),d=s('<a id="fancybox-close"></a>'),c=s('<div id="fancybox-title"></div>'),r=s('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),g=s('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>')),d.on("click",s.fancybox.close),f.on("click",s.fancybox.cancel),r.on("click",function(t){t.preventDefault(),s.fancybox.prev()}),g.on("click",function(t){t.preventDefault(),s.fancybox.next()}),s.fn.mousewheel&&o.on("mousewheel.fb",function(t,e){A?t.preventDefault():0!=s(t.target).get(0).clientHeight&&s(t.target).get(0).scrollHeight!==s(t.target).get(0).clientHeight||(t.preventDefault(),s.fancybox[0<e?"prev":"next"]())}),s.support.opacity||o.addClass("fancybox-ie"),N&&(f.addClass("fancybox-ie6"),o.addClass("fancybox-ie6"),s('<iframe id="fancybox-hide-sel-frame" src="'+(/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank")+'" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(t)))},s.fn.fancybox.defaults={padding:10,margin:40,opacity:!1,modal:!1,cyclic:!1,scrolling:"auto",width:560,height:340,autoScale:!0,autoDimensions:!0,centerOnScroll:!1,ajax:{},swf:{wmode:"transparent"},hideOnOverlayClick:!0,hideOnContentClick:!1,overlayShow:!0,overlayOpacity:.7,overlayColor:"#777",titleShow:!0,titlePosition:"float",titleFormat:null,titleFromAlt:!1,transitionIn:"fade",transitionOut:"fade",speedIn:300,speedOut:300,changeSpeed:300,changeFade:"fast",easingIn:"swing",easingOut:"swing",showCloseButton:!0,showNavArrows:!0,enableEscapeButton:!0,enableKeyboardNav:!0,onStart:function(){},onCancel:function(){},onComplete:function(){},onCleanup:function(){},onClosed:function(){},onError:function(){}},jQuery(function(t){t.fancybox.init()})})(jQuery);
// source --> https://www.rennsteig-bike-tour.de/wp-content/plugins/nextgen-gallery/static/Lightbox/nextgen_tiktok_helper.js?ver=4.1.3 
(function($) {
    "use strict";

    window.NextGEN_TikTok = {
        extract_id: function(url) {
            if (!url) return null;
            url = url.trim();

            var patterns = [
                /tiktok\.com\/@[^\/]+\/video\/(\d+)/i,
                /tiktok\.com\/v\/(\d+)/i,
                /tiktok\.com\/embed\/v2\/(\d+)/i,
                /tiktok\.com\/.*[?&]v=(\d+)/i,
                /\/video\/(\d+)/i,
                /^(\d{15,25})$/,
            ];

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

            if (url.match(/vm\.tiktok\.com|tiktok\.com\/t\//i)) {
                var idMatch = url.match(/(\d{15,25})/);
                if (idMatch) {
                    return idMatch[1];
                }
                return null;
            }

            return null;
        },

        create_player: function(videoUrl, containerClass, videoClass) {
            var container = document.createElement("div");
            container.className = containerClass || "ngg-tiktok-container";

            var video = document.createElement("video");
            video.className = videoClass || "ngg-tiktok-video";
            video.controls = true;
            video.autoplay = true;
            video.playsInline = true;
            video.muted = true;
            video.loop = true;
            video.preload = "auto";
            video.setAttribute("playsinline", "");
            video.setAttribute("webkit-playsinline", "");
            video.src = videoUrl;

            video.addEventListener("loadedmetadata", function () {
                var naturalWidth = video.videoWidth;
                var naturalHeight = video.videoHeight;

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

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

                            // Apply EXACT same scaling logic as Shutter images (lines 239-249)
                            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) {
                            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: replicate EXACT same image sizing logic from thickbox.js lines 204-224
                            var pageWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
                            var pageHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
                            var x = pageWidth - 150;  // Same as Thickbox: pagesize[0] - 150
                            var y = pageHeight - 150; // Same as Thickbox: pagesize[1] - 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) {
                            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";
                        }
                    }
                }
            });

            video.addEventListener("canplay", function () {
                video.play().catch(function () {});
            });

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

        handle_content: function(options) {
            var self = this;
            var playUrl = options.playUrl;
            var $targetContainer = $(options.container);

            if (!playUrl) return null;

            var tiktokContent = null;

            var applyDimensions = function (el) {
                if (options.width) {
                    var w = typeof options.width === "number" ? options.width + "px" : options.width;
                    el.style.width = w;
                    var inner = el.querySelector("video, iframe, .ngg-tiktok-error-content");
                    if (inner) inner.style.width = "100%";
                }
                if (options.height) {
                    var h = typeof options.height === "number" ? options.height + "px" : options.height;
                    el.style.height = h;
                    var inner = el.querySelector("video, iframe, .ngg-tiktok-error-content");
                    if (inner) inner.style.height = "100%";
                }
            };

            if (playUrl) {
                var decodedUrl = playUrl;
                try {
                    decodedUrl = decodeURIComponent(playUrl);
                } catch (e) {}

                tiktokContent = self.create_player(decodedUrl, options.containerClass, options.videoClass);
                if (tiktokContent) {
                    applyDimensions(tiktokContent);
                    var video = tiktokContent.querySelector("video");
                    if (video) {
                        video.onerror = function () {
                            $(tiktokContent).remove();
                            var errorMsg = self.create_error("Video failed to load", options.errorClass);
                            applyDimensions(errorMsg);
                            if (typeof options.onBeforeAppend === "function") options.onBeforeAppend(errorMsg);
                            $targetContainer.append(errorMsg);
                        };
                    }
                    if (typeof options.onBeforeAppend === "function") options.onBeforeAppend(tiktokContent);
                    $targetContainer.append(tiktokContent);
                }
            } else {
                var errorMsg = self.create_error("Video not available", options.errorClass);
                applyDimensions(errorMsg);
                if (typeof options.onBeforeAppend === "function") options.onBeforeAppend(errorMsg);
                $targetContainer.append(errorMsg);
                tiktokContent = errorMsg;
            }

            return tiktokContent;
        },

        create_error: function(message, containerClass) {
            var container = document.createElement("div");
            container.className = containerClass || "ngg-tiktok-error";
            container.innerHTML =
                '<div class="ngg-tiktok-error-content">' +
                '<span class="ngg-tiktok-error-icon">&#9888;</span>' +
                '<span class="ngg-tiktok-error-text">' +
                (message || "Video failed to load") +
                "</span>" +
                "</div>";
            return container;
        }
    };
})(jQuery);
// source --> https://www.rennsteig-bike-tour.de/wp-content/plugins/nextgen-gallery/static/Lightbox/fancybox/nextgen_fancybox_init.js?ver=4.1.3 
jQuery(function($) {
    var nextgen_fancybox_init = function() {
        var selector = nextgen_lightbox_filter_selector($, $(".ngg-fancybox"));

        window.addEventListener(
            "click",
            e => {
                let $target = $(e.target);
                var $anchor = $target.is('a') ? $target : $target.parents('a').first();
                
                if (!$anchor.is(selector) && !$target.is(selector)) {
                    return;
                }

                // Skip Dribbble direct links - they should navigate to external URL, not open lightbox.
                if ($anchor.attr('data-dribbble-direct') === 'true') {
                    return;
                }

                var imageId = $anchor.attr('data-image-id');
                var isTikTokImage = false;
                var tiktokData = null;

                if (imageId && window.ngg_tiktok_images && window.ngg_tiktok_images[imageId]) {
                    isTikTokImage = true;
                    tiktokData = window.ngg_tiktok_images[imageId];
                } else if ($anchor.attr('data-tiktok-play-url') || $anchor.attr('data-tiktok-share-url')) {
                    isTikTokImage = true;
                    tiktokData = {
                        playUrl: $anchor.attr('data-tiktok-play-url') || '',
                        shareUrl: $anchor.attr('data-tiktok-share-url') || '',
                        embedUrl: $anchor.attr('data-tiktok-embed-url') || ''
                    };
                }

                if (isTikTokImage && tiktokData) {
                    var $galleryContainer = $anchor.closest('[data-gallery-id]');
                    var galleryId = null;
                    
                    if ($galleryContainer.length) {
                        galleryId = $galleryContainer.attr('data-gallery-id') || $galleryContainer.data('gallery-id');
                    } else {
                        $galleryContainer = $anchor.closest('.ngg-galleryoverview, .ngg-imagebrowser, .ngg-slideshow');
                        if ($galleryContainer.length) {
                            galleryId = $galleryContainer.attr('data-gallery-id') || 
                                       $galleryContainer.data('gallery-id') ||
                                       $galleryContainer.attr('data-nextgen-gallery-id') ||
                                       $galleryContainer.data('nextgen-gallery-id');
                        }
                    }
                    
                    if (galleryId) {
                        galleryId = String(galleryId);
                    }

                    var tiktokSettings = {};
                    if (window.NggTikTokVideo && typeof window.NggTikTokVideo.getTikTokSettings === 'function') {
                        tiktokSettings = window.NggTikTokVideo.getTikTokSettings(galleryId);
                    } else {
                        if (window.ngg_tiktok_gallery_settings) {
                            if (galleryId && window.ngg_tiktok_gallery_settings['gallery_' + galleryId]) {
                                tiktokSettings = window.ngg_tiktok_gallery_settings['gallery_' + galleryId];
                            } else if (window.ngg_tiktok_gallery_settings.global) {
                                tiktokSettings = window.ngg_tiktok_gallery_settings.global;
                            }
                        }
                    }
                    
                    var linkSetting = String(tiktokSettings.link || '0');

                    if (linkSetting === '1' || linkSetting === '2') {
                        return;
                    }
                }

                e.preventDefault();
                $(selector).fancybox({
                    titlePosition: 'inside',
                    // Needed for twenty eleven
                    onComplete: function(selectedArray, selectedIndex, selectedOpts) {
                        $("#fancybox-wrap").css("z-index", 10000);

                        var element = selectedArray[selectedIndex];
                        var $element = $(element);
                        var playUrl = $element.data("tiktok-play-url");
                        var shareUrl = $element.data("tiktok-share-url");
                        var videoUrl = $element.attr("data-video-url");

                        // Handle TikTok
                        if (playUrl || shareUrl) {
                            $("#fancybox-wrap").addClass("ngg-tiktok-mode");
                            NextGEN_TikTok.handle_content({
                                playUrl: playUrl,
                                shareUrl: shareUrl,
                                container: $("#fancybox-content"),
                                onBeforeAppend: function () {
                                    $("#fancybox-img").hide();
                                },
                            });
                        }
                        // Handle video links
                        else if (videoUrl && window.NextGEN_Video && window.NextGEN_Video.detect_platform(videoUrl)) {
                            $("#fancybox-wrap").addClass("ngg-video-mode");
                            
                            // Remove existing video containers
                            $("#fancybox-content .ngg-video-container, #fancybox-content .ngg-video-error").remove();
                            
                            // Get gallery ID for settings
                            var galleryId = null;
                            var $galleryContainer = $element.closest('[data-gallery-id]');
                            if ($galleryContainer.length) {
                                galleryId = $galleryContainer.attr('data-gallery-id') || $galleryContainer.data('gallery-id');
                            }
                            
                            // Get video settings
                            var videoSettings = {};
                            if (window.ngg_video_gallery_settings) {
                                if (galleryId && window.ngg_video_gallery_settings['gallery_' + galleryId]) {
                                    videoSettings = window.ngg_video_gallery_settings['gallery_' + galleryId];
                                }
                            }
                            
                            window.NextGEN_Video.handle_content({
                                videoUrl: videoUrl,
                                container: $("#fancybox-content")[0],
                                settings: videoSettings,
                                containerClass: "ngg-video-container",
                                videoClass: "ngg-video-player",
                                errorClass: "ngg-video-error",
                                onBeforeAppend: function () {
                                    $("#fancybox-img").hide();
                                },
                            });
                        }
                    },
                    onCleanup: function () {
                        $("#fancybox-wrap").removeClass("ngg-tiktok-mode ngg-video-mode");
                        $("#fancybox-content .ngg-tiktok-container, #fancybox-content .ngg-tiktok-error").remove();
                        $("#fancybox-content .ngg-video-container, #fancybox-content .ngg-video-error").remove();
                    },
                });
                $target.trigger('click.fb');
                
                e.stopPropagation();
            },
            true
        )
    };
    $(window).on('refreshed', nextgen_fancybox_init);
    nextgen_fancybox_init();
});
// 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 ));