var App = function () {


    function initBootstrap() {

        $('[data-toggle="tooltip"]').tooltip();
        $('[data-toggle="popover"]').popover();


        if ($('.navbar-onepage').length > 0) {
            $('body').scrollspy({ target: $('.navbar-onepage'), offset: ($('#nav-primary').height()+21) });
        }

    }

    function initLightbox() {

        /* fix for missing title attribute in lightbox a tags */
        $('.lightbox').each(function () {
            if (this.title === '') {
                $(this).attr('title', $("img", $(this)).attr('title'));
            }
            const parents = $(this).parents('figure');
            if (parents.length > 0) {
                if ($('.image-caption span.description',parents.get(0)).length > 0) {
                    $(this).attr('data-description',$('.image-caption span.description', parents.get(0)).html());
                }
            }

        });



        const lightbox = GLightbox({
            selector: '.lightbox'
        });
        lightbox.on('open', () => {
            App.compensateScrollbar(true);
        });
        lightbox.on('close', () => {
            App.compensateScrollbar(false);
        });

    }

    function initHeader() {
        if (jQuery('.navbar-user').length > 0 && jQuery('.fixed-top').height() > 0 && jQuery('.navbar-user').height() > 0) {
            jQuery(window).scroll(function () {
                if (jQuery(window).scrollTop() > 100) {
                    jQuery('#nav-primary').addClass('navbar-shrinked');
                } else {
                    jQuery('#nav-primary').removeClass('navbar-shrinked');
                }
            });
        }

        $('.hero video').each(function() {
            var video = this;
            video.oncanplaythrough = function() {
                video.muted = true;
                video.play();
            }
        });
    }

    function initParallaxBg() {
        jQuery('.parallaxBg').parallax();
    }

    function initMmenu() {

        if ($('body').hasClass('cached-mobile-menu')) {
            var pageId = $('body').attr('id').split('_')[1];
            $('#sidemenu .nav-item-' + pageId + '').addClass('current').parent().addClass('current');
        }

        var navTitle = document.head.querySelector("[name=navtitle]") ? document.head.querySelector("[name=navtitle]").content : '';

        $('#sidemenu').mmenu({
            extensions: ['position-left', 'pagedim-black'],
            navbar: {
                title: navTitle
            },
            navbars: [{
                position: 'bottom',
                height: 2,
                content: ['<div id="mobile-footer"></div>']
            }],
            hooks: {
                /* change fixed position while opening the mmenu */
                'open:before': function() {
                    var scrollTopPosition = $(window).scrollTop();
                    $('.fixed-top').css('position', 'absolute').css('top', scrollTopPosition + 'px');
                },
                'close:finish': function() {
                    $('.fixed-top').css('position', 'fixed').css('top', '0px');
                }
            }
        },{
        classNames: {
            selected: 'current'
        }
        });

        $('#mobile-footer').html($('#nav-mobile-footer').html());
    }

    function initFlexslider() {

        /* flexslider im hero */
        $('.hero .flexslider').flexslider({
            'controlNav': false,
            'selector': '.slides > div'
        });

    }

    function initEqualHeight() {


        $('.equal-height').matchHeight({
            byRow: true,
            property: 'min-height'
        });
        $('.ce-header').matchHeight({
            byRow: true,
            property: 'min-height'
        });


        /*
        $('h2').matchHeight({
            byRow: true,
            property: 'min-height'
        });
        $('h3').matchHeight({
            byRow: true,
            property: 'min-height'
        });*/
    }

    function initSmoothScroll() {

        var navbarHeight = $('#nav-primary').height();
        if ($('.navbar-user').length > 0) {
            navbarHeight -= $('.navbar-user').height();
        }

        /* section index on same pages */
        $('a.this-page').on('click', function(event) {
            event.preventDefault();

            var hash = this.hash;
            $('html, body').animate({
                scrollTop: $(hash).offset().top-(navbarHeight+20)
            }, 800, function(){
            });
        });


        /* from here on only for one pager */
        if ($('.navbar-onepage').length === 0) return;

        /* Add smooth scrolling on all links inside the navbar */
        $('#page a[href*="#"]').not('.sr-only').not('[data-parent]').not('[data-toggle]').not('[data-slide]').on('click', function(event) {

            event.preventDefault();
            var hash = this.hash;
            // Using jQuery's animate() method to add smooth page scroll
            // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
            $('html, body').animate({
                scrollTop: $(hash).offset().top-(navbarHeight+20)
            }, 800, function(){
                // Add hash (#) to URL when done scrolling (default click behavior)
                //window.location.hash = hash;
            });
        });

        /* one page: link on logo */
        $('.navbar-onepage .navbar-brand a').on('click', function(event) {
            event.preventDefault();
            $('html, body').animate({
                scrollTop: 0
            }, 800, function(){

            });
        });

        $('.nav-onepage a').on('click', function(event) {
            $(this).closest('.navbar-collapse.show').collapse('hide');
        });

    }

    function initAjaxModals() {

        var modalTemplate = jQuery('<div class="modal fade" id="ajax-modal" tabindex="-1" role="dialog" aria-labelledby="ajaxModalLabel" aria-hidden="true">\n' +
          ' <button type="button" class="close" data-dismiss="modal" aria-label="Close">\n' +
          ' <span aria-hidden="true">&times;</span>\n' +
          ' </button>\n' +
          ' <div class="modal-dialog" role="document">\n' +
          ' <div class="modal-content">\n' +
          ' <div class="modal-header">\n' +
          ' <h5 class="modal-title" id="ajaxModalLabel"></h5>\n' +
          ' </div>\n' +
          ' <div class="modal-text"></div>\n' +
          ' <div class="modal-body">\n' +
          ' </div>\n' +
          ' </div>\n' +
          ' </div>\n' +
          '</div>').attr('id','modalContact');


        jQuery('body').append(modalTemplate);
        let modalBody = modalTemplate.find('.modal-body');

        let showContent = function(content) {

            modalBody.html(content);
            modalTemplate.find('.modal-title').html(modalBody.find('h2').html());
            modalBody.find('h2').remove();
            let form = modalTemplate.find('form');

            form.find('[type=submit]').on('click', function (e) {
                e.preventDefault();

                /* show spinner */


                let values = form.serialize();
                values = values += '&'+jQuery(e.target).attr('name')+'='+jQuery(e.target).attr('value');

                jQuery.ajax({
                    type: "POST",
                    url: form.attr('action'),
                    data: values,
                    headers: {
                        'Cache-Control': 'no-cache, no-store, must-revalidate',
                        'Pragma': 'no-cache',
                        'Expires': '0'
                    },
                    dataType: 'html',
                    success: showContent
                });

            });

        };

        jQuery('.modal-ajax').on('click', function (e) {
            e.preventDefault();
            let url = jQuery(this).data('url');

            /* show spinner */

            jQuery.ajax({
                type: "POST",
                url: url,
                headers: {
                    'Cache-Control': 'no-cache, no-store, must-revalidate',
                    'Pragma': 'no-cache',
                    'Expires': '0'
                },
                dataType: 'html',
                success: function (content) {
                    showContent(content);
                    modalTemplate.modal('show');

                    /* hide spinner */

                }
            });
        });

    }

    function initAriaBar() {

        if (jQuery('.nav-aria').length === 0) return;

        jQuery('body').addClass('with-aria-bar');

        if ($.cookie('aria-high-contrast') == '1') {
            jQuery('body').addClass('high-ct-enabled');
            jQuery(this).addClass('active');
            jQuery('.btn-contrast').addClass('active');
        }

        jQuery('.btn-contrast').on('click',function (event) {
            event.preventDefault();
            if (jQuery(this).hasClass('active')) {
                jQuery('body').removeClass('high-ct-enabled');
                jQuery(this).removeClass('active');
                $.removeCookie('aria-high-contrast');
            } else {
                jQuery('body').addClass('high-ct-enabled');
                jQuery(this).addClass('active');
                $.cookie('aria-high-contrast', '1');
            }
        });

    }

    function initCompareSlider() {
        if ($(".beforeafterdefault").length > 0) {
            $(".beforeafterdefault").cndkbeforeafter({autoSliding: true});
        }
    }

    function initScrollbarWidth(App) {
        // thx d.walsh
        var scrollDiv = document.createElement('div');
        scrollDiv.className = 'scrollbar-measure';
        document.body.appendChild(scrollDiv);
        var scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
        document.body.removeChild(scrollDiv);
        App.scrollbarWidth = scrollbarWidth;
    }

    return {

        scrollbarWidth: 0,

        init: function () {

            initBootstrap();
            initScrollbarWidth(this);
            initLightbox();
            initHeader();
            initMmenu();
            initFlexslider();
            initParallaxBg();
            initEqualHeight();
            initSmoothScroll();
            initAjaxModals();
            initAriaBar();
            initCompareSlider();

        },
        compensateScrollbar: function(compensate) {
            if (compensate) {
                $('body, .fixed-top, .fixed-bottom, .is-fixed, .sticky-top').css('padding-right', this.scrollbarWidth);
            } else {
                $('body, .fixed-top, .fixed-bottom, .is-fixed, .sticky-top').css('padding-right', 0);
            }
        }
    }
}();

var page = $('body').not('.page-onepage').find('#page');

if (!$('#nav-primary').hasClass('overlay-menu-section')) {
    page.css('padding-top', $('.fixed-top').height());
}

jQuery(document).ready(function () {

    if (!$('#nav-primary').hasClass('overlay-menu-section')) {
        /* Padding der Seite einstellen, damit das Menü den Inhalt nicht überlappt.  */
        page.animate({'padding-top': $('.fixed-top').height()});
        $(window).resize(function () {
            page.css('padding-top', $('.fixed-top').height());
        });
    }

    App.init();
});


