$(document).ready(function() {
    /*LAZY LOADING Image + Video (PLUGIN NS_LAZY_LOADING)*/
    (function() {
        ll = new LazyLoad({
            elements_selector: ".lazy",
            effect : "fadeIn",
            effectTime: 200,
            load_delay: 30,
            threshold: 200
        });
        lv = new LazyLoad({
            elements_selector: ".lazyVideo",
        });
    })();

    /* Für Pagespeed links ohne href im mm-menu fixen */
    $('a[class*="mm-"]').each(function () {
        let href = $(this).attr('href');
        if (href === undefined || href === '') {
            $(this).attr('href', '#');
        }
    });

    /*FANCYBOX*/
    $('.fancybox').fancybox();
    /* Datepicker bei Anreise und Abreise Felder - einfach Variablen austauschen*/
    $('.arrival:not(.arrivalEvent)').each(function(){
        let $arrivalinput = $(this);
        let $departureinput = $(this).parent().parent().parent().find('.departure');

        if($arrivalinput.length){
            if($arrivalinput.data('mindate')){var $mindate = new Date($arrivalinput.data('mindate'));}else{var $mindate = 0;}
            if($arrivalinput.data('maxdate')){var $maxdate =  new Date($arrivalinput.data('maxdate'));}else{var $maxdate = '';}
            $arrivalinput.datepicker({
                minDate: $mindate,
                maxDate: $maxdate,
                onSelect: function(selected) {
                    $departureinput.datepicker("option","minDate", selected);
                    this.dispatchEvent(new Event('change'));
                    if(document.querySelector('.departure')) {
                        document.querySelector('.departure').dispatchEvent(new Event('change'))
                    }
                }
            }).attr('autocomplete', 'off');
            $departureinput.datepicker({
                minDate: $mindate,
                maxDate: $maxdate,
                onSelect: function(selected) {
                    $arrivalinput.datepicker("option","maxDate", selected);
                    this.dispatchEvent(new Event('change'));
                }
            }).attr('autocomplete', 'off');
        };
    });
    /* Datepicker für Events - einfach Variablen austauschen*/
    $('.arrivalEvent').each(function(){
        let $arrivalinput = $(this);
        let $departureinput = $(this).parent().parent().parent().find('.departureEvent');

        if($arrivalinput.length){
            if($arrivalinput.data('mindate')){var $mindate = new Date($arrivalinput.data('mindate'));}else{var $mindate = 0;}
            if($arrivalinput.data('maxdate')){var $maxdate =  new Date($arrivalinput.data('maxdate'));}else{var $maxdate = '';}
            $arrivalinput.datepicker({
                minDate: $mindate,
                /*maxDate: $maxdate,*/
                onSelect: function(selected) {
                    $departureinput.datepicker("option","minDate", selected);
                    this.dispatchEvent(new Event('change'));
                    if(document.querySelector('.departure')) {
                        document.querySelector('.departure').dispatchEvent(new Event('change'))
                    }
                }
            });
            $departureinput.datepicker({
                minDate: $mindate,
                /*maxDate: $maxdate,*/
                onSelect: function(selected) {
                   /* $arrivalinput.datepicker("option","maxDate", selected);*/
                    this.dispatchEvent(new Event('change'));
                }
            });
        };
    });

    var $arrivaldatetimeinput = $('#powermail_field_arrivaldatetime');
    var $departuredatetimeinput = $('#powermail_field_departuredatetime');
    if($arrivaldatetimeinput.length){
        $arrivaldatetimeinput.datetimepicker({
            controlType: 'select',
            oneLine: true,
            minDate: 0,
            onSelect: function(selected) {
                $departuredatetimeinput.datetimepicker("option","minDate", selected);
                this.dispatchEvent(new Event('change'));
                if(document.querySelector('.departure')) {
                    document.querySelector('.departure').dispatchEvent(new Event('change'))
                }
            }
        }).attr('autocomplete', 'off');
        $departuredatetimeinput.datetimepicker({
            minDate: 0,
            controlType: 'select',
            oneLine: true,
            onSelect: function(selected) {
                $arrivaldatetimeinput.datetimepicker("option","maxDate", selected);
                this.dispatchEvent(new Event('change'));
            }
        }).attr('autocomplete', 'off');
    };

    /* Anker Navi */
    $('.jsBtnAnchor').on('click', function (e){
        e.preventDefault();
        let anchor_id = $(this).attr('href').split('#').pop();
        scrollToAnchor(anchor_id);
        if($('#'+anchor_id+' .accordion__item-content').length){
            $('#'+anchor_id+' .accordion__item-content').collapse('show');
        }
    });

    /*hide, show lage text*/
    readMore();
    $('.btnReadMore').on('click', function (){
        $(this).parents('.jsReadMore').toggleClass('showAll');
    });

    $('.jsbtnOpenAccMobile').on('click', function (){
        $(this).parents('.jsAccMobileContainer').toggleClass('hide-content');
    });
    $('.accordion__item-header').on('click', function (){
        window.setTimeout( scrollTable, 500 );
    });

    /* Selectboxen */
    $('select:not(.multipleSelectric):not(.noSelectric)').selectric({
        onInit: function() {
            if ($(this).find('option:first-child').val() =='') {
                $(this).parents('.selectric-wrapper').addClass('hideFirstOption');
            }
            $(this).parents('.selectric-wrapper').find('.selectric-input').attr('aria-label',$(this).parents('form').find('label[for='+$(this).attr("id")+']').text());
        },
        onClose: function () {
            var selectricWrap = $(this).parents('.selectric-wrapper');
            if (selectricWrap.find('select').val() != '') {
                if (selectricWrap.find('.removeSelect').length <= 0) {
                    selectricWrap.append('<div class="removeSelect"><i class="icon icon-close"></i></div>');
                    selectricWrap.find('.removeSelect').on('click',function() {
                        $(this).parents('.selectric-wrapper').find('select').val('').selectric('refresh');
                        $(this).remove();
                    })
                }
            }
            if($('#billingAddress-country').length){
                /*Quickfix Warenkorb: Länderauswahl Versand...*/
                var index = selectricWrap.find('.selectric-scroll ul li.selected').data('index')
                selectricWrap.find('select').prop('selectedIndex', index).selectric('refresh');
                selectricWrap.find('select').trigger('change');
            }
        },
    });
    $('select.multipleSelectric:not(.noSelectric)').selectric({
        onInit: function() {
            if ($(this).find('option:first-child').val() =='') {
                $(this).parents('.selectric-wrapper').addClass('hideFirstOption');
            }
            $(this).parents('.selectric-wrapper').find('.selectric-input').attr('aria-label',$(this).parents('form').find('label[for='+$(this).attr("id")+']').text());
        },
        onClose: function() {
            var selectricWrap = $(this).parents('.selectric-wrapper');
            if (selectricWrap.find('select').val() != '') {
                if(selectricWrap.find('.removeSelect').length <= 0){
                    selectricWrap.append('<div class="removeSelect"><i class="icon icon-close"></i></div>');
                    selectricWrap.find('.removeSelect').on('click',function() {
                        $(this).parents('.selectric-wrapper').find('select').val('').selectric('refresh');
                        $(this).remove();
                    })
                }
            }
        },
        multiple: {
            separator: ', ',
            keepMenuOpen: true,
            maxLabelEntries: false
        }
    });

    /*LangNavi mmenu*/
    $('.btnOpenLangNavi').on('click', function (){
        $('.jsLangNaviContainer').slideToggle();
    });
    $('.btnCloseLangNavi').on('click', function (){
        $('.jsLangNaviContainer').slideToggle();
    });
    /* MainNavi dropdown-menu open if focus Form */
    $('.dropdown-menu input, .dropdown-menu select').on('focus', function () {
        $('.dropdown-menu-inner').addClass('show');
    });

    /*** Barriere Freiheit start ***/
    /*aria-expanded bei Submenu ändern*/
    $('.navbar .dropdown').on('mouseenter', function () {
        $(this).find('.dropdown-menu-level-1').attr('aria-expanded','true');
    });
    $('.navbar .dropdown').on('mouseleave', function () {
        $(this).find('.dropdown-menu-level-1').attr('aria-expanded','false');
    });
    if($('.om-cookie-panel.active').length) {
        $('.cookie-panel__button--color--green').trigger("focus");
    }
    /*Formulare Autocomplete*/
    $('.tx-powermail input[type="text"]').each(function(){
        if($(this).attr('id')){
            $(this).attr('autocomplete',$(this).attr('id').replace('powermail_field_',''));
        }
    });
    /*
    $('a, .btn, button').each(function(){
        $(this).attr('tabindex','0');
    });*/
    /*Kontrast-Button im Top-Header*/
    if($('#btnContrast').length){
        toggleContrast();
        $('#btnContrast').on('click', function (e){
            e.preventDefault();
            if ($(this).hasClass('active')){
                Cookies.set('contrast','default',{path:'/'});
            } else {
                Cookies.set('contrast','high',{path:'/'});
            }
            toggleContrast();
        });
    }
    /*** Barriere Freiheit end ***/


    /* Booking EMO start */
    $('.btnOpenFilterContent').on('click', function (){
        $(this).next().slideToggle('fast');
    });
    $('.btnViewOption').on('click', function (){
        $('.btnViewOption').toggleClass('active');
        $(this).parents('.viewOptionContainer').next().removeClass('list-view-option-tile').removeClass('list-view-option-list').addClass($(this).data('view'));
    });
    $('.btnShowMoreDays').on('click', function (){
        $(this).toggleClass('isOpen').parent().children('.daysHiddenElement').toggleClass('hidden');
    });
    $('.btnToggleFilterbox').on('click', function (){
        $(this).parent().toggleClass('show');
        $(this).children().toggleClass('d-none').toggleClass('d-flex');
    });
    $('.btnToggleInnerFilter').on('click', function (){
        $(this).toggleClass('show');
        $(this).next().toggleClass('d-none').toggleClass('d-block');
    });
    /* Booking EMO end */



});

function toggleContrast(){
    if (Cookies.get("contrast") == "high") {
        let css = $("link[href*='main_contrast_0']");
        if (css.length > 0) {
            let oldhref = $("link[href*='main_contrast_0']").attr("href");
            $('body').data('oldhref', oldhref);
            css.attr("href", '/fileadmin/scss/highcontrast.css');
        }else{
            css.attr("href", '/fileadmin/scss/highcontrast.css');
        }
        $('#btnContrast').addClass('active');
    } else {
        $('#btnContrast').removeClass('active');
        let oldhref = $('body').data('oldhref');
        let css = $("link[href*='highcontrast']");
        css.attr("href", oldhref);
    }
}


jQuery(window).bind('load', function(){
    $(".contenttable, .ce-table").each(function () {
        $(this).wrap("<div class='table-container-outer'><div class='table-container'>");
    });
    if($('.infrastructures-tabs').length > 0) {
        let anchor = getUrlParameter('anchor');
        if(anchor != '') {
            $('.btnTab[data-type="'+anchor+'"]').trigger('click');
            scrollToAnchor('infrastructures-tabs');
        }
    }
    scrollTable();

    /*Autoplay on Header*/
    if($('.swiper-slide-video > video').length > 0){
        let videoElement = $('.swiper-slide-video > video');
        if (videoElement.playing) {} else {
            videoElement[0].play();
        }
    }

});


$('.btnClose').on('click', function(){
    $(this).parent().fadeOut('200');
});

$(window).on('scroll load', function() {
    if ($(this).scrollTop() > 50) {
        $('body').addClass('top-fixed');
    } else {
        $('body').removeClass('top-fixed');
    }
    scrollToTop = $(this).scrollTop();
});

var lastScroll = 0;
var $window = $(window);
var wertebox = $('.infobar');
$window.on('scroll', function(){
    var scrollTop = $window.scrollTop();
    wertebox.toggleClass('hide-bottom', scrollTop > lastScroll);
    lastScroll = scrollTop;
    if ($(this).scrollTop() <= 100) {
        wertebox.removeClass('hide-bottom');
    }
});

var resizeId;
$(window).resize(function() {
    scrollTable();
    clearTimeout(resizeId);
    resizeId = setTimeout(doneResizing, 500);
});

function doneResizing(){
    readMore();
}

function scrollTable(){
    $(".table-container").each(function () {
        let wrap = $(this).outerWidth();
        let table = $(this).find('table').outerWidth();
        if (table > wrap){
            $(this).parents('.table-container-outer').addClass('scroll');
        }else {
            $(this).parents('.table-container-outer').removeClass('scroll');
        }
    });
}

function scrollToAnchor(anchor_id){
    if(anchor_id == "infrastructures-tabs"){
        var $target = $("."+anchor_id+"");
    }else{
        var $target = $("#"+anchor_id+"");
    }
    let speed = ($target.offset().top - $('html').offset().top) * 0.2;

    $('html, body').css('scroll-behavior','auto').animate(
        {
            scrollTop: $target.offset().top
        }, {
            duration: speed,
            step: function( now, fx ) {
                var newOffset = $target.offset().top;
                if(fx.end !== newOffset)
                    fx.end = newOffset;
            }
        }
    );


}

function readMore(){
    /*hide, show lage text*/
    $('.jsReadMore').each(function(){
        let boxHeight = $(this).height();
        let boxHeightInner = $(this).children(":first").height();
        /*console.log(boxHeight +', ' + boxHeightInner);*/
        if(boxHeight < boxHeightInner){
            $(this).addClass('hideLageText');
        }
    });
}

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;
    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
};

// SWIPER INITIALIZATION @GU.UR 2023-03-02
document.addEventListener('DOMContentLoaded', function () {
    let initializeSwipers = () => {
        if (!document.querySelector("[data-slider]")) {
          return;
        }
        document.querySelectorAll("[data-slider]").forEach((node) => {
          console.log(node);
          const config = Object.assign({}, node.dataset);
          for (const i in config) {
            try {
              // sanitize then parse
              config[i] = JSON.parse(
                config[i].replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"$2": ')
              );
            } catch (_) {
              config[i] = isNaN(config[i]) ? config[i] : Number(config[i]);
            }
          }
          if (!config.slider) {
            return;
          }
          if (typeof node.dataset.initialized !== "undefined") {
            return;
          }
          const swiper = new Swiper(node, {
            spaceBetween: config.slidesBetween ?? 0,
            slidesPerView: config.slidesPerView ?? "auto",
            loop: true,

            observer: true,
            observeParents: true,
            observeSlideChildren: true,
            watchOverflow: true,
            effect: "slide",
            wrapperClass:
                typeof config.sliderWrapper !== "undefined" && config.sliderWrapper
                ? config.sliderWrapper
                : "swiper-wrapper",
            pagination: {
              el:
                "." +
                (typeof config.pagination !== "undefined" && config.pagination
                  ? config.pagination
                  : "swiper-pagination"),
            },
            navigation: {
              nextEl:
                "." +
                (typeof config.sliderNext !== "undefined" && config.sliderNext
                  ? config.sliderNext
                  : "swiper-button-next"),
              prevEl:
                "." +
                (typeof config.sliderPrev !== "undefined" && config.sliderPrev
                  ? config.sliderPrev
                  : "swiper-button-prev"),
            },
            breakpoints: config.sliderBreakpoints ?? {},
          });
        });
        // console.log(document.querySelector("[data-slider]"))
    };
    initializeSwipers();
})