
//
// Title: jpFaq.js
// Author: Jacco van der Post - www.id-webdesign.nl
// Date: feb 2018
//

var jpFaq = jpFaq || {};

(function ($) {

    var txJpfaq = '.tx-jpfaq';
    var jpFaqToggleTrigger = 'ul.jpfaqList .toggleTrigger';
    var jpFaqListItem = 'ul.jpfaqList li';
    var jpfaqShow = '.jpfaqShowAll';
    var jpfaqHide = '.jpfaqHideAll';
    var jpFaqToggleTriggerContainer = '.toggleTriggerContainer';
    var thisPlugin = '';
    var jpFaqSearch = '#jpfaqSearch';
    var jpFaqSearchForm = '#jpfaqSearch input';
    var jpFaqFilterCount = '#jpfaq-filter-count';
    var jpfaqQuestionCommentContainer = '.jpfaqQuestionCommentContainer';
    var jpfaqAddCommentForm = '.jpfaqAddCommentForm';
    var jpfaqQuestionHelpfulText = '.jpfaqQuestionHelpfulText';
    var jpfaqQuestionNotHelpful = '.jpfaqQuestionNotHelpful';
    var jpfaqQuestionHelpful = '.jpfaqQuestionHelpful';
    var jpfaqCommentFormClose = '.jpfaqCommentFormClose';
    var jpfaqQuestionCommentForm = '#jpfaqQuestionCommentForm';
    var jpfaqEmailField = '.jpfaqEmailField';
    var jpfaqRequiredField = '.jpfaqRequired';
    var jpfaqCommentFieldWarning = 'jpfaqCommentFieldWarning';
    var jpfaqSubmitComment = '.jpfaqSubmitComment';
    var jpfaqCommentPageType = '&type=88188';
    var jpfaqSpinner = '.jpfaqSpinner';
    var jpfaqSpinnerHtml = '<div class="jpfaqSpinner"></div>';
    var jpfaqCatCommentContainerLink = '.jpfaqCatCommentContainerLink';
    var jpfaqCatCommentContainerIntro = '.jpfaqCatCommentContainerIntro';
    var jpfaqCatCommentContainer = '.jpfaqCatCommentContainer';
    var jpfaqCatCommentFormClose = '.jpfaqCatCommentFormClose';
    var jpfaqSubmitCatComment = '.jpfaqSubmitCatComment';
    var jpfaqCatCommentForm = '#jpfaqCatCommentForm';

    /**
     * Plugins
     *
     * @type object
     */
    jpFaq.Main = {

        /**
         * Initialize plugins
         *
         * @return void
         */
        initialize: function () {
            jpFaq.Main.openClose();
            jpFaq.Main.search();
            jpFaq.Main.preventSubmit();

            jpFaq.Main.questionIsHelpful();
            jpFaq.Main.questionIsNotHelpful();
            jpFaq.Main.closeQuestionCommentForm();
            jpFaq.Main.addQuestionComment();
            jpFaq.Main.closeThanks4QuestionComment();

            jpFaq.Main.addCategoryCommentForm();
            jpFaq.Main.closeCategoryCommentForm();
            jpFaq.Main.addCategoryComment();
            jpFaq.Main.closeThanks4CategoryComment();

            // For testing
            //$(jpfaqShow).click();
        },

        /**
         * Open and close questions with js
         *
         * @return void
         */
        openClose: function () {
            $(jpFaqToggleTrigger).click(function () {
                thisPlugin = $(this).closest(txJpfaq);
                $(this).next().toggleClass('active').slideToggle('fast');
                $(this).toggleClass('questionUnfolded');
                if ($(thisPlugin).find(jpFaqListItem).children(':first-child').length == $(thisPlugin).find(jpFaqListItem).children(':first-child.questionUnfolded').length) {
                    $(thisPlugin).find(jpfaqShow).hide();
                    $(thisPlugin).find(jpfaqHide).show();
                } else {
                    $(thisPlugin).find(jpfaqHide).hide();
                    $(thisPlugin).find(jpfaqShow).show();
                }
            });
            $(jpfaqShow).click(function () {
                thisPlugin = $(this).closest(txJpfaq);
                $(thisPlugin).find(jpFaqToggleTriggerContainer).removeClass('active');
                $(thisPlugin).find(jpFaqToggleTriggerContainer).addClass('active').slideDown('fast');
                $(thisPlugin).find(jpFaqToggleTrigger).removeClass('questionUnfolded');
                $(thisPlugin).find(jpFaqToggleTrigger).addClass('questionUnfolded');
                $(thisPlugin).find(jpfaqShow).hide();
                $(thisPlugin).find(jpfaqHide).show();
            });
            $(jpfaqHide).click(function () {
                thisPlugin = $(this).closest(txJpfaq);
                $(thisPlugin).find(jpFaqToggleTriggerContainer).removeClass('active').slideUp('fast');
                $(thisPlugin).find(jpFaqToggleTrigger).removeClass('questionUnfolded');
                $(thisPlugin).find(jpfaqHide).hide();
                $(thisPlugin).find(jpfaqShow).show();
            });
        },

        /**
         * Quick search faq's
         *
         * @return void
         */
        search: function () {
            $(jpFaqSearchForm).keyup(function () {
                var searchFilter = $(this).val(), count = 0;

                $(txJpfaq + ' .jpfaqList > li').each(function () {
                    if ($(this).text().search(new RegExp(searchFilter, 'i')) < 0) {
                        $(this).css('display', 'none');
                    } else {
                        $(this).show();
                        count++;
                    }
                    let i = 0;
                    $('#' + this.className + ' > ul > li').each(function () {
                        if (this.style['display'] != 'none') {
                            i++;
                        }
                    });
                    if (i == 0) {
                        $('#' + this.className + ' > h2').css('display', 'none');
                    } else {
                        $('#' + this.className + ' > h2').show();
                    }
                });

                if (searchFilter.length > 0 && count == 0) {
                    $('.jpfaq-no-results').first().removeClass('d-none');
                } else {
                    $('.jpfaq-no-results').addClass('d-none');
                }

                $(jpFaqFilterCount + ' span').text(count);
            })
        },

        /**
         * Prevent reload page on submit search
         *
         * @return void
         */
        preventSubmit: function () {
            $(jpFaqSearch).submit(function (e) {
                e.preventDefault();
            });
        },

        /**
         * A question is found helpful
         *
         * Update 'helpful' in database
         * Send to Google event tracking
         *
         * Action: helpfulness
         *
         * @return void
         */
        questionIsHelpful: function () {
            $(jpfaqQuestionHelpful).click(function (event) {
                event.preventDefault();
                $(this).closest(jpfaqQuestionHelpfulText).hide();

                var loadUri = $(this).attr('href') + jpfaqCommentPageType;
                var contentContainer = $(this).closest(jpfaqQuestionCommentContainer);
                jpFaq.Main.ajaxPost(loadUri, contentContainer);

                var gtagData = $(this).data();
                if (gtagData['gtagevent']) {
                    jpFaq.Main.sendGtag(gtagData);
                }
            });
        },

        /**
         * A question is not found helpful
         *
         * Via Ajax, load comment form and update property 'nothelpful' in database
         * Send to Google event tracking
         *
         * Action: helpfulness
         *
         * @return void
         */
        questionIsNotHelpful: function () {
            $(jpfaqQuestionNotHelpful).click(function (event) {
                event.preventDefault();
                $(this).closest(jpfaqQuestionHelpfulText).hide();

                var loadUri = $(this).attr('href') + jpfaqCommentPageType;
                var contentContainer = $(this).closest(jpfaqQuestionCommentContainer).find(jpfaqAddCommentForm);

                jpFaq.Main.ajaxPost(loadUri, contentContainer);

                var gtagData = $(this).data();
                if (gtagData['gtagevent']) {
                    jpFaq.Main.sendGtag(gtagData);
                }
            })
        },

        /**
         * Send gtag to Google analytics events
         * Must be enabled in typoscript settings and gtag.js global tracking snippet must be present
         *
         * @param {array} gtagData
         *
         * @return void
         */
        sendGtag: function (gtagData) {
            gtag('event', gtagData['gtagevent'], {
                'event_category': gtagData['gtagcategory'],
                'event_label': gtagData['gtaglabel'],
                'value': gtagData['gtagvalue']
            });
        },

        /**
         * Close question comment form when clicked on close
         *
         * @return void
         */
        closeQuestionCommentForm: function () {
            $(txJpfaq).on('click', jpfaqCommentFormClose, function () {
                $(this).closest(jpfaqQuestionCommentContainer).find(jpfaqQuestionHelpfulText).show();

                var formContainer = $(this).closest(jpfaqQuestionCommentContainer).find(jpfaqAddCommentForm);
                formContainer.slideUp('fast', function () {
                    formContainer.empty();
                });
            })
        },

        /**
         * Add question comment after submit
         * validate, then send it to postComment
         *
         * @return void
         */
        addQuestionComment: function () {
            $(txJpfaq).on('click', jpfaqSubmitComment, function (event) {
                event.preventDefault();

                var submitButtonId = this.id;
                var questionNumber = submitButtonId.replace('jpfaqSubmitComment', '');
                // Get the correct plugin when multiple plugins with same questions on a page
                var pluginUid = $(this).closest(txJpfaq).attr('id');
                var commentContainer = '#' + pluginUid + ' ' + jpfaqQuestionCommentContainer + questionNumber;
                var form = $(jpfaqQuestionCommentForm + questionNumber);
                var formValidated = jpFaq.Main.validateForm(form);

                if (formValidated) {
                   jpFaq.Main.postComment(event, commentContainer, form);
                }
            });
        },

        /**
         * Close thank you message after posting a question comment
         *
         * @return void
         */
        closeThanks4QuestionComment: function () {
            $(jpfaqQuestionCommentContainer).on('click', '.jpfaqCommentClose', function () {
                $(this).closest('.jpfaqThanks').slideUp('fast', function () {
                    $(this).remove();
                });
            });
        },

        /**
         * Add Category comment form after click link
         *
         * @return void
         */
        addCategoryCommentForm: function () {
            $(jpfaqCatCommentContainerLink).click(function (event) {
                event.preventDefault();
                $(this).closest(jpfaqCatCommentContainerIntro).hide();

                var loadUri = $(this).attr('href') + jpfaqCommentPageType;
                var contentContainer = $(this).closest(jpfaqCatCommentContainer).find(jpfaqAddCommentForm);
                jpFaq.Main.ajaxPost(loadUri, contentContainer);
            })
        },

        /**
         * Close category comment form when clicked on close
         *
         * @return void
         */
        closeCategoryCommentForm: function () {
            $(txJpfaq).on('click', jpfaqCatCommentFormClose, function () {
                $(this).closest(jpfaqCatCommentContainer).find(jpfaqCatCommentContainerIntro).show();

                var formContainer = $(this).closest(jpfaqCatCommentContainer).find(jpfaqAddCommentForm);
                formContainer.slideUp('fast', function () {
                    formContainer.empty();
                });
            })
        },

        /**
         * Add category comment after submit
         * validate, then send it to postComment
         *
         * @return void
         */
        addCategoryComment: function () {
            $(txJpfaq).on('click', jpfaqSubmitCatComment, function (event) {
                event.preventDefault();

                var submitButtonId = this.id;
                var questionNumber = submitButtonId.replace('jpfaqSubmitCatComment', '');
                // Get the correct plugin when multiple plugins with same questions on a page
                var pluginId = $(this).closest(txJpfaq).attr('id');
                var commentContainer = '#' + pluginId + ' ' + jpfaqCatCommentContainer + questionNumber;
                var pluginUid = pluginId.replace('tx-jpfaq','');
                var form = $(jpfaqCatCommentForm + pluginUid);
                var formValidated = jpFaq.Main.validateForm(form);

                if (formValidated) {
                    jpFaq.Main.postComment(event, commentContainer, form);
                }
            });
        },

        /**
         * Close thank you message after posting a category comment
         *
         * @return void
         */
        closeThanks4CategoryComment: function () {
            $(jpfaqCatCommentContainer).on('click', '.jpfaqCommentClose', function () {
                $(this).closest('.jpfaqThanks').slideUp('fast', function () {
                    $(this).remove();
                });
            });
        },

        /**
         * Validate form on requiredfields and valid email
         *
         *
         * @param {object} form
         * @return {boolean}
         */
        validateForm: function (form) {
            var noFieldErrors = true;

            // Validate form required fields filled, add warning class
            $(form).find(jpfaqRequiredField).each(function () {
                if ($(this).val() === '') {
                    $(this).addClass(jpfaqCommentFieldWarning);
                    noFieldErrors = false;
                }
            });

            // Validate email if filled in, else add warning class
            $(form).find(jpfaqEmailField).each(function () {
                var email = $(this).val();
                if (email) {
                    if (!jpFaq.Main.validateEmail(email)) {
                        $(this).addClass(jpfaqCommentFieldWarning);
                        noFieldErrors = false;
                    }
                }
            });

            // Remove warning class (e.g. red border) on fields with errors
            $('.' + jpfaqCommentFieldWarning).focus(function () {
                $(this).removeClass(jpfaqCommentFieldWarning);
            });

            return noFieldErrors;
        },

        /**
         * Ajax POST
         * Used for helpful / not helpful
         *
         * @param {string} loadUri
         * @param {string} contentContainer
         *
         * @return void
         */
        ajaxPost: function (loadUri, contentContainer) {
            $.ajax({
                type: 'POST',
                url: loadUri,
                data: {},

                success: function (response) {
                    $(contentContainer).append(response);
                    contentContainer.slideDown('fast');
                },

                error: function (xhr, thrownError) {
                    $(contentContainer).append('fail');
                    //console.log(xhr.status + ' ' + xhr.responseText + ' ' + thrownError);
                }
            });
        },

        /**
         * Post comment with Ajax
         * show thank you text with the comment content
         *
         * Action: addComment
         *
         * @param {object} event
         * @param {string} commentContainer
         * @param {string} form
         *
         * @return void
         */
        postComment: function (event, commentContainer, form) {
            var loadUri = $(form).attr('action') + jpfaqCommentPageType;
            $(commentContainer + ' ' + jpfaqAddCommentForm).fadeOut();
            $(commentContainer).append(jpfaqSpinnerHtml);

            $.ajax({
                type: 'POST',
                url: loadUri,
                data: form.serialize(),

                success: function (response) {
                    $(commentContainer + ' ' + jpfaqAddCommentForm).empty();
                    $(jpfaqSpinner).remove();

                    $(commentContainer).append(response);
                },

                error: function (xhr, thrownError) {
                    $(jpfaqSpinner).remove();
                    $(commentContainer + ' ' + jpfaqAddCommentForm).fadeIn('fast');
                    //console.log(xhr.status + ' ' + xhr.responseText + ' ' + thrownError);
                }
            });
        },

        /**
         * Regex email validation
         *
         * @param email
         *
         * @return boolean
         */
        validateEmail: function (email) {
            var expr = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
            return expr.test(email);
        }
    }
})(jQuery);

/**
 * On ready event
 */
jQuery(document).ready(function () {
    jpFaq.Main.initialize();
});
(function ($) {

    $(document).ready(function () {

        $('body').addClass('loaded');

        $().deployChat();

        const header = $('#header'),
            headspacer = $('#headspacer'),
            timebar = $('#timebar');
        let headheight = header.height(),
            winheight = $(window).height(),
            wintotop = $(window).scrollTop(),
            timebaroffset = timebar.height() - 30,
            lasttotop = 0,
            stoff = 0,
            delta = 5,
            scrolled = false;

        if (window.matchMedia("(min-width: 992px)").matches) {
            stoff = 95;
            $('.ticket-detail-view .feature-item').removeClass(['collapsable', 'collapsed']).removeAttr('data-bs-toggle').removeAttr('role');
            $('.ticket-detail-view .feature-item .feature-description').removeClass('collapse');
        } else {
            stoff = 72;
        }

        if ($('.jobfair__filter').length) {
            $().initializeFilterJobs();
        }

        if ($('.news-startpage').length) {
            $().deployNewsStartpage(function () {
                $('.news-slider').slick({
                    infinite: false,
                    slidesToShow: 3,
                    slidesToScroll: 1,
                    arrows: true,
                    prevArrow: '<div class="slick-prev"><i class="fa-light fa-chevron-left"></i></div>',
                    nextArrow: '<div class="slick-next"><i class="fa-light fa-chevron-right"></i></div>',
                    responsive: [
                        {
                            breakpoint: 1024,
                            settings: {
                                infinite: true,
                                slidesToShow: 2,
                            }
                        },
                        {
                            breakpoint: 640,
                            settings: {
                                infinite: true,
                                slidesToShow: 1,
                            }
                        }
                    ]
                });
            });
        }

        if ($('.news-aktuelles').length) {
            $().deployNewsAktuelles();
        }

        if ($('.price-container').length) {
            $(document).on('change', '#payScaleLevelSelect', function () {
                $('.price-container .price').each(function () {
                    if ($(this).hasClass($('#payScaleLevelSelect').val())) {
                        $(this).addClass('show');
                        $(this).css('display', 'block');
                    } else {
                        $(this).css('display', 'none');
                        if (!$(this).hasClass('hide')) {
                            $(this).addClass('hide');
                        }
                        if ($(this).hasClass('show')) {
                            $(this).removeClass('show');
                        }
                    }
                });
            });
        }

        if (window.location.hash) {
            let hash = window.location.hash;
            if ($(hash).length) {
                $('html,body').animate({scrollTop: $(hash).offset().top - stoff}, 600);
            }
        }
        $('a.scroll-link').on('click', function (e) {
            e.preventDefault(e);
            let hash = this.hash;
            let linkid = $(hash);
            let idtotop = 0;
            if ($(linkid).length) {
                idtotop = parseInt($(linkid).offset().top);
            }
            $('html,body').animate({scrollTop: idtotop - 90}, 600);
        });

        function navCalc() {
            if (wintotop > stoff) {
                header.addClass('sticky');
                headspacer.addClass('sticked');
                headheight = headspacer.height();
            } else {
                headspacer.removeClass('sticked');
                header.removeClass('sticky');
                headheight = header.height();
            }
            if (Math.abs(lasttotop - wintotop) <= delta) {
                return;
            }
            if (wintotop > lasttotop && wintotop > headheight) {
                header.addClass('goup');
            } else {
                if (wintotop + winheight < $(document).height()) {
                    header.removeClass('goup');
                }
            }
            lasttotop = wintotop;
        }

        navCalc();

        $(window).resize(function () {
            winheight = $(window).height();
            // timebaroffset = timebar.height() - 30;
            navCalc();
        });
        $(window).on('load', function () {
            // timebaroffset = timebar.height() - 30;
            // if(!$('body').hasClass('start')) {
            //     timebar.css({ 'margin-top' : '-'+timebaroffset+'px' });
            //     console.log(timebaroffset);
            // }
        });

        $(window).scroll(function () {
            wintotop = $(window).scrollTop();
            if (wintotop > (winheight - 80)) {
                $('#scrollup').addClass('show');
            } else {
                $('#scrollup').removeClass('show');
            }
            navCalc();

            if ($('.timeline').length) {
                $('.timeline__item').each(function () {
                    let listItem = $(this);
                    if (listItem.offset().top < $(window).scrollTop() + $(window).height() && !listItem.hasClass('fade-in')) {
                        setTimeout(function () {
                            listItem.addClass('fade-in');
                        }, 600);
                    }
                });
            }
        });

        // Navigation
        $('#navbar').on('show.bs.collapse hide.bs.collapse', function (e) {
            if (e.type == 'show') {
                $('html').addClass('overflow');
                $('.navbar-toggler').addClass('is-active');
            } else {
                $('html').removeClass('overflow');
                $('.navbar-toggler').removeClass('is-active');
            }
        });


        if (window.matchMedia("(max-width: 991px)").matches) {

            $('.submenu-toggle').click(function (e) {
                e.preventDefault(e);
                e.stopPropagation(e);
                $(this).parent('.dropdown-toggle').next('.dropdown-menu').toggle();
                if ($(this).parent('.dropdown-toggle').hasClass('open')) {
                    $(this).parent('.dropdown-toggle').removeClass('open');
                } else {
                    $(this).parent('.dropdown-toggle').addClass('open');
                }
            });

            $('.navbar .dropdown-toggle').click(function (e) {
                e.preventDefault(e);
                if ($(this).hasClass('open')) {
                    window.location.href = $(this).attr('href');
                } else {
                    if ($(this).next('.dropdown-menu').length) {
                        $(this).next('.dropdown-menu').toggle();
                    }
                    $(this).addClass('open');
                }
            });

            $('.navbar .search-toggle').click(function (e) {
                e.preventDefault(e);
                $('.navbar-toggler').click();
                $('.header__search').addClass('open');
                $('#search').focus();
            });

        } else {

            $('.navbar .search-toggle').click(function (e) {
                e.preventDefault(e);
                if ($(this).hasClass('active')) {
                    $('.header__search').removeClass('open');
                    $(this).removeClass('active');
                } else {
                    $('.header__search').addClass('open');
                    $(this).addClass('active');
                    $('#search').focus();
                }
            });

        }

        $('.toggle-bar').click(function (e) {
            e.preventDefault(e);

            if (timebar.hasClass('open')) {
                timebar.removeClass('open');
            } else {
                timebar.addClass('open');
            }
            if (timebar.hasClass('start')) {
                timebar.removeClass('start');
                timebar.addClass('open');
            }
        });

        if ($('#timebar').height > 0) {
            $('.timebar-toggle > svg').css('transition', 'color 0.5s')
            $('.timebar-toggle > svg').css('color', 'var(--bs-primary)')
        }

        $(".pswp-img").jqPhotoSwipe({
            bgOpacity: 0.5,
            galleryOpen: function (gallery) {

            }, shareEl: false,
        });
        $(".gallery .pswp-img").jqPhotoSwipe({
            bgOpacity: 0.5,
            forceSingleGallery: true
        });

        // FireFox autofocus fix
        if (!("autofocus" in $('#from'))) {
            $('#from').focus();
        }

        $('#to').keyup((event) => {
            if (event.keyCode === 13) {
                $('.efa-submit-button').click();
            }
        });

        // set default current time and date as value
        let time = new Date();
        $('#timepicker').attr('value', time.toTimeString().split(' ', 1)[0]);
        $('#datepicker').attr('value', time.getDate() + '.' + (time.getMonth() + 1) + '.' + time.getFullYear());

        $("#timepicker").mobiscroll().datepicker({
            theme: 'mobiscroll',
            themeVariant: 'light',
            locale: 'de',
            controls: ['time'],
            timeFormat: 'HH:mm',
            setText: 'Weiter',
            clearText: 'Löschen',
            cancelText: 'Abbrechen',
            nowText: 'Jetzt',
        });

        $("#datepicker").mobiscroll().datepicker({
            theme: 'auto',
            themeVariant: 'light',
            locale: 'de',
            dayNAmes: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
            dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
            dayNamesShort: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
            monthNames: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
            dateFormat: 'DD.MM.YYYY',
            setText: 'Weiter',
            clearText: 'Löschen',
            cancelText: 'Abbrechen',
            nowText: 'Jetzt',
        });

        $('.form-floating > .btn-select').click(function () {
            $(this).parent().find('input').click();
        });

        function resizeTimetableSearchBar(id) {
            let newWidth = $('#timetable-input-' + id).outerWidth();
            $('.mbsc-popup.mbsc-ios.mbsc-popup-anchored').css('max-width', 'unset');
            $('.mbsc-scroller-wheel-wrapper.mbsc-scroller-wheel-wrapper-0.mbsc-ios.mbsc-ltr').width(newWidth);
        }

        let timetableItemActive = {"1": false, "2": false, "3": false, "4": false, "5": false, "6": false}

        function timetableItemsShow(event, inst) {
            activePill = $(".nav.nav-pills").find(".nav-link.active").attr("id").split('-')[1];
            resizeTimetableSearchBar(activePill);
            let timetableValue = event.value;
            if (timetableItemActive[activePill]) {
                $('#timetables__download-item-' + timetableItemActive[activePill]).addClass('d-none');
            }
            $('#timetables__download-item-' + timetableValue).removeClass('d-none');
            timetableItemActive[activePill] = timetableValue;
        }

        mobiscroll.setOptions({
            locale: mobiscroll.localeDe,
            theme: 'ios',
            themeVariant: 'light',
            filter: true
        });


        // restyle eezy-tariff
        if ($('#eezy-tariff-calculator').length) {
            setTimeout(function () {
                el = $('.tariff-form .submit-btn-container').children().last();
                el.addClass('submit-btn-wraper');
                let sbmtBtn = el.children();
                sbmtBtn.removeClass().addClass('btn btn-primary btn-lg');
                elHtml = el.children().html();
                el.children().html('');
                text = elHtml.split('<span')[0];
                el.children().html(elHtml.split(text)[1].split('</span>')[0] + text + '</span>');
                $('.tariff-form .submit-btn-container').children().last().remove();
                $('.tariff-form .datepicker-container').append(el);
                sbmtBtn.on('focusin', function () {
                    setTimeout(function () {
                        sbmtBtn.removeClass().addClass('btn btn-primary btn-lg');
                        sbmtBtn.css('color', 'var(--bs-white)')
                    }, 30);
                });
                sbmtBtn.on('focusout', function () {
                    setTimeout(function () {
                        sbmtBtn.removeClass().addClass('btn btn-primary btn-lg');
                        sbmtBtn.css('color', 'var(--bs-white)')
                    }, 30);
                });
            }, 50);

        }

        if ($('.timetables__nav').length) {
            $('#timetable-select-1').mobiscroll().select({
                inputElement: document.getElementById('timetable-input-1'),
                touchUi: false,
                onChange: timetableItemsShow
            });

            $('#timetable-input-1').click(function () {
                setTimeout(function () {
                    resizeTimetableSearchBar(1)
                }, 50);
            });

            $('#timetable-select-2').mobiscroll().select({
                inputElement: document.getElementById('timetable-input-2'),
                touchUi: false,
                onChange: timetableItemsShow
            });

            $('#timetable-input-2').click(function () {
                setTimeout(function () {
                    resizeTimetableSearchBar(2)
                }, 50);
            });

            $('#timetable-select-3').mobiscroll().select({
                inputElement: document.getElementById('timetable-input-3'),
                touchUi: false,
                onChange: timetableItemsShow
            });

            $('#timetable-input-3').click(function () {
                setTimeout(function () {
                    resizeTimetableSearchBar(3)
                }, 50);
            });

            $('#timetable-select-4').mobiscroll().select({
                inputElement: document.getElementById('timetable-input-4'),
                touchUi: false,
                onChange: timetableItemsShow
            });

            $('#timetable-input-4').click(function () {
                setTimeout(function () {
                    resizeTimetableSearchBar(4)
                }, 50);
            });

            $('#timetable-select-5').mobiscroll().select({
                inputElement: document.getElementById('timetable-input-5'),
                touchUi: false,
                onChange: timetableItemsShow
            });

            $('#timetable-input-5').click(function () {
                setTimeout(function () {
                    resizeTimetableSearchBar(5)
                }, 50);
            });

            $('#timetable-select-6').mobiscroll().select({
                inputElement: document.getElementById('timetable-input-6'),
                touchUi: false,
                onChange: timetableItemsShow
            });

            $('#timetable-input-6').click(function () {
                setTimeout(function () {
                    resizeTimetableSearchBar(6)
                }, 50);
            });
        }


        $('.switch-mode > .btn').click(function (e) {
            e.preventDefault(e);
            if (!$(this).hasClass('active')) {
                $('.switch-mode > .btn').removeClass('active');
                $(this).addClass('active');
            }
        });

        $(document).on('click', '.link-line > a', function (e) {
            e.preventDefault(e);
            if (!$(this).hasClass('active')) {
                $('.link-line > a').removeClass('active');
                $(this).addClass('active');
                $('.list-group-item').hide();
                $('.list-group-item[data-char="' + $(this).text() + '"]').show();
            }
        });

        function setFontSize(size) {
            $('html').css('font-size', size + 'px');
        }

        let fontSize = sessionStorage.getItem('fontSize');
        if (fontSize == null && fontSize == undefined) {
            fontSize = parseInt(16);
        }
        if (fontSize != 16) {
            setFontSize(fontSize);
        }
        $(document).on('click', '.nav--font .nav-link', function (e) {
            e.preventDefault(e);
            if ($(this).hasClass('minus')) {
                fontSize--;
            }
            if ($(this).hasClass('reset')) {
                fontSize = 16;
            }
            if ($(this).hasClass('plus')) {
                fontSize++;
            }
            sessionStorage.setItem('fontSize', fontSize);
            setFontSize(fontSize);
        });

        let contrast = sessionStorage.getItem('contrast');
        if (contrast == 'true') {
            $(document.documentElement).attr('data-theme', 'contrast');
            if ($('.card-psl-tag').length) {
                $('.card-psl-tag').each(function () {
                    $(this).attr('color', $(this).css('background-color'))
                    $(this).css('background-color', 'black')
                });
            }
        }
        $(document).on('click', '.nav--contrast .nav-link', function (e) {
            e.preventDefault(e);
            contrast = sessionStorage.getItem('contrast');
            if (contrast == 'true') {
                sessionStorage.setItem('contrast', false);
                $(document.documentElement).attr('data-theme', '');
                if ($('.card-psl-tag').length) {
                    $('.card-psl-tag').each(function () {
                        $(this).css('background-color', $(this).attr('color'))
                    });
                }
            } else {
                sessionStorage.setItem('contrast', true);
                $(document.documentElement).attr('data-theme', 'contrast');
                if ($('.card-psl-tag').length) {
                    $('.card-psl-tag').each(function () {
                        $(this).attr('color', $(this).css('background-color'))
                        $(this).css('background-color', 'black')
                    });
                }
            }
        });


        $(document).on('click', '.timeline .timeline-more', function (e) {
            e.preventDefault(e);
            $(this).parents('.timeline').children('.timeline__item').addClass('show');
            $(this).remove();
        });

        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;
        };

        if (getUrlParameter('tx_solr%5Bq%5D') !== false) {
            $('#search').val(getUrlParameter('tx_solr%5Bq%5D'));
            $('.search-toggle').addClass('active');
            $('.header__search').addClass('open');
        }


        if ($('.ticket-list-view').length) {

            let qsRegex;
            let buttonFilter;

            let $grid = $('.ticket-container').isotope({
                itemSelector: '.ticket',
                layoutMode: 'fitRows',
                filter: function () {
                    let $this = $(this);
                    let searchResult = qsRegex ? $this.text().match(qsRegex) : true;
                    let buttonResult = buttonFilter ? $this.is(buttonFilter) : true;
                    return searchResult && buttonResult;
                }
            });

            let $quicksearch = $('#quicksearch').keyup(debounce(function () {
                qsRegex = new RegExp($quicksearch.val(), 'gi');
                $grid.isotope();

                setTimeout(function () {
                    noResultsCheck();
                }, 400);
            }));

            $(document).on('click', '.btn-filter', function (e) {
                e.preventDefault();

                $(this).toggleClass('active');

                let filterValue = '';

                $('.btn-filter.active').each(function () {
                    let filter = $(this).attr('data-filter');
                    filterValue += '[data-filter*="' + filter + '"]';
                });

                buttonFilter = filterValue;
                $grid.isotope();

                setTimeout(function () {
                    noResultsCheck();
                }, 600);
            });

            $(document).on('click', '.btn-reset-filter', function () {
                $('.btn-filter.active').removeClass(['active', 'btn-secondary']).addClass(['btn-primary', 'outlined']);
                $('.no-ticket').fadeOut();
                buttonFilter = '*';
                $grid.isotope();
            });

            $(document).on('click', '.clearsearch', function () {
                $('#quicksearch').val('');
                qsRegex = new RegExp($quicksearch.val(), 'gi');
                $grid.isotope();

                setTimeout(function () {
                    noResultsCheck();
                }, 400);
            });

            setTimeout(function () {
                $grid.isotope();
            }, 1200);

        }

        function debounce(fn, threshold) {
            let timeout;
            threshold = threshold || 100;
            return function debounced() {
                clearTimeout(timeout);
                let args = arguments;
                let _this = this;

                function delayed() {
                    fn.apply(_this, args);
                }

                timeout = setTimeout(delayed, threshold);
            };
        }

        function noResultsCheck() {
            let ticket = document.querySelectorAll('.ticket')
            ticket_show = false
            ticket.forEach(function (el) {
                if (window.getComputedStyle(el).display !== "none") {
                    ticket_show = true;
                    return ticket_show;
                }
            });
            if (ticket_show) {
                $('.no-ticket').fadeOut();
            } else {
                $('.no-ticket').fadeIn();
            }
            if ($('#quicksearch').val().length > 0) {
                $('.clearsearch').show();
            } else {
                $('.clearsearch').hide();
            }
        }

        if ($('.district-filter').length) {
            function filterDistricts() {
                $('.district').parent().hide();
                let i = 0;
                $('.district-filter .btn-filter.active').each(function () {
                    let filter = $(this).data('filter');
                    $('.district-' + filter).parent().show();
                    i++;

                });
                if (i > 0) {
                    $('.district-reset').removeClass('d-none');
                } else {
                    $('.district').parent().show();
                    $('.district-reset').addClass('d-none');
                }
            }

            $(document).on('click', '.district-filter .btn-filter', function (e) {
                e.preventDefault(e);
                $(this).toggleClass('active');
                filterDistricts();
            });
            $(document).on('click', '.district-reset .btn-reset-filter', function (e) {
                e.preventDefault(e);
                $('.district-filter .btn-filter.active').removeClass('active');
                $('.district').parent().show();
                $('.district-reset').addClass('d-none');
            });
        }

        if ($('.ticket-filter').length) {
            function filterTickets() {
                $('.ticket').parent().hide();
                let i = 0;
                $('.ticket-filter .btn-filter.active').each(function () {
                    let filter = $(this).data('filter');
                    $('.ticket-' + filter).parent().show();
                    i++;

                });
                if (i > 0) {
                    $('.ticket-reset').removeClass('d-none');
                } else {
                    $('.ticket').parent().show();
                    $('.ticket-reset').addClass('d-none');
                }
            }

            $(document).on('click', '.ticket-filter .btn-filter', function (e) {
                e.preventDefault(e);
                $(this).toggleClass('active');
                filterTickets();
            });
            $(document).on('click', '.ticket-reset .btn-reset-filter', function (e) {
                e.preventDefault(e);
                $('.ticket-filter .btn-filter.active').removeClass('active');
                $('.ticket').parent().show();
                $('.ticket-reset').addClass('d-none');
            });
        }

        $(document).on('click', '.nav--social .nav-link', function (e) {
            e.preventDefault(e);
            e.stopPropagation(e);
            var target = $(this).attr('href');
            if (target.indexOf('https://') != -1) {
                $('#forwardInfoPopup').modal('show');
                $(document).on('click', '#forwardInfoPopup .btn', function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    if ($(this).hasClass('confirm')) {
                        $('#forwardInfoPopup').modal('hide');
                        window.open(target, '_blank');
                    }
                });
            } else {
                window.location = target;
            }
        });
        $(document).on('click', '.download-link', function (e) {
            e.preventDefault(e);
            e.stopPropagation(e);
            let url = $(this).attr('href');
            window.open(url, '_blank').focus();
        });

        $('[data-bs-toggle="tooltip"]').tooltip();
        $('[data-bs-toggle="collapse"]').collapse();
        $('[data-bs-toggle="popover"]').popover();
        // $('[data-bs-toggle="dropdown"]').dropdown();

        sal({
            threshold: 1,
            once: false,
        });

        if ($('.ticket-container .card-ticket').length) {
            function cardTicketHeight() {
                let elements = $('.card-ticket');
                let heights = elements.map((index, element) => $(element).height());
                let maxHeight = Math.max(...heights);
                elements.each((index, element) => $(element).height(maxHeight));
            }

            cardTicketHeight();
            $(window).on("resize", cardTicketHeight);
        }

        if (window.matchMedia("(max-width: 767px)").matches) {
            if ($('.table').length) {
                $('.table').each(function () {
                    $(this).wrap('<div class="tableresp"></div>');
                });
            }
            if ($('.accordion-collapse').length) {
                $('.accordion-collapse.show').each(function () {
                    $(this).collapse();
                });
            }
        }


    });


    $(window).on('load', function () {

        $('.btn-primary, .btn-secondary').each(function () {
            if (!$(this).has('span').length) {
                $(this).wrapInner('<span></span>');
            }
        });

        // if($('.slick-slider').length) {
        //     $('.slide-prev').click(function(e){
        //         e.preventDefault();
        //         let sid = $(this).data('slider');
        //         console.log(sid);
        //         $(sid).slick('slickPrev');
        //     });
        //     $('.slide-next').click(function(e){
        //         e.preventDefault();
        //         let sid = $(this).data('slider');
        //         $(sid).slick('slickNext');
        //     });
        // }

        if ($('.start .news-slider').length) {

            $('.news-slider').slick({
                infinite: false,
                slidesToShow: 3,
                slidesToScroll: 1,
                arrows: true,
                prevArrow: '<div class="slick-prev"><i class="fa-light fa-chevron-left"></i></div>',
                nextArrow: '<div class="slick-next"><i class="fa-light fa-chevron-right"></i></div>',
                responsive: [
                    {
                        breakpoint: 1024,
                        settings: {
                            infinite: true,
                            slidesToShow: 2,
                        }
                    },
                    {
                        breakpoint: 640,
                        settings: {
                            infinite: true,
                            slidesToShow: 1,
                        }
                    }
                ]
            });
            if (window.matchMedia("(max-width: 1023px)").matches) {

            }
        }

        if ($('.timetables__nav').length) {
            $('.timetable-spinner').addClass('hide');
            $('.timetables__nav').removeClass('hide');
            $('.timetables__body').removeClass('hide');
        }


    });

    $.fn.filterJobs = function (callback) {
        let formData = $('#jobFilter').serialize();

        jQuery.ajax({
            async: 'false',
            url: window.location.protocol + "//" + window.location.hostname + '/ajax.filter-jobs',
            data: {formData: formData, ajaxRequest: true},
            type: 'POST',
            dataType: 'html',
            beforeSend: function () {
                $('#ajax-spinner').removeClass('hidden');
                $('.submit-btn-text').addClass('hidden');
                $('#tx_jobfair_filter .btn-primary').prop('disabled', true);
                $('#tx_jobfair_filter input, #tx_jobfair_filter select').prop('disabled', true);
            },
            success: function (result) {
                let html = $(result).find('.jobfair');
                $('.jobfair').replaceWith(html);

                if (typeof callback === 'function') {
                    callback();
                }
            },
            error: function (error) {
                console.log(error);
            }
        });
    }

    $.fn.deployNewsStartpage = function (callback) {

        jQuery.ajax({
            async: 'false',
            url: window.location.protocol + "//" + window.location.hostname + '/ajax.news-startpage',
            type: 'GET',
            dataType: 'html',
            beforeSend: function () {
                $('#ajax-spinner').removeClass('hidden');
            },
            success: function (result) {
                $('.news-startpage').replaceWith(result);

                if (typeof callback === 'function') {
                    callback();
                }
            },
            error: function (error) {
                console.log(error);
            }
        });
    }


    $.fn.deployNewsAktuelles = function (callback) {

        jQuery.ajax({
            async: 'false',
            url: window.location.protocol + "//" + window.location.hostname + '/ajax.news-aktuelles',
            type: 'GET',
            dataType: 'html',
            beforeSend: function () {
                $('#ajax-spinner').removeClass('hidden');
            },
            success: function (result) {
                $('.news-aktuelles').replaceWith(result);

                if (typeof callback === 'function') {
                    callback();
                }
            },
            error: function (error) {
                console.log(error);
            }
        });
    }

    $.fn.deployChat = function () {
        jQuery.getScript('https://chatnrw-production-messaging-webchat.patty-awseuc1.swops.cloud/embed.js', function () {
            console.log("Chat deployed.");
            $().initChat();
        }).fail(function () {
            console.log("Chat couldn't be deployed.")
            $().deployChat();
        });

    }

    $.fn.initChat = function () {
        let chat = new smoopeChat.default(document.body, {
            livechat: '01J0TFX8V5EVXP1DWWKYVM1E62',
            configurationURL: 'https://chatnrw-production-messaging-webmain.patty-awseuc1.swops.cloud/.well-known/web'
        });
        chat.insert();
    }

    $.fn.initializeFilterJobs = function () {
        $('#jobFilter').on("submit", function (e) {
            e.preventDefault();
            $().filterJobs(function () {
                $().initializeFilterJobs();
            });
        })
    }

})(jQuery);
