const body = document.body;
const privacy = document.querySelector(".pwPrivacy");
let timer;

document.addEventListener("DOMContentLoaded", () => {
    timer = setInterval(function () {
        toggleBodyClassList();
        saveConsent();

        if (privacy) {
            hideCookieConsentOnPrivacyPage();
        }
    }, 200);
});
function toggleBodyClassList() {
    const cookieNotice = document.querySelector(
        ".klaro.klaro_customStyles .cookie-notice"
    );
    const isCookieNoticeShown = cookieNotice ? true : false;

    const isCookieModalShown = document.querySelector(
        "#klaro .klaro.we_cookie_consent.klaro_customStyles .cookie-modal"
    );

    if (!isCookieNoticeShown && !isCookieModalShown) {
        // default
        body.classList.remove("blur");
        return false;
    }

    if (isCookieNoticeShown || isCookieModalShown) {
        body.classList.add("blur");
    }
}

function hideCookieConsentOnPrivacyPage() {
    const cookieNotice = document.querySelector(
        ".klaro.klaro_customStyles .cookie-notice"
    );
    const isCookieNoticeShown = cookieNotice ? true : false;
    const showConsentButton = document.querySelector(".js-showConsentModal");

    if (!privacy || !isCookieNoticeShown) {
        return;
    }

    body.classList.remove("blur");
    cookieNotice.classList.add("d-none");

    showConsentButton.addEventListener("click", () => {
        cookieNotice.classList.remove("d-none");
    });

    clearInterval(timer);
}

function saveConsent() {
    let buttons = document.querySelectorAll('.cm-btn');

    buttons.forEach((button) => {
        button.addEventListener('click', makeAjaxRequest);
    })
}

async function makeAjaxRequest() {
    let url = '/?type=181818&no_cache=1&tx_pkwebsitekit_ajax[controller]=Ajax&tx_pkwebsitekit_ajax[action]=consent&saveConsent=1';
    const response =  await fetch(url);
}




var Teasergroup = function () {
    var self = this;
    this.windowWidth = $(window).width();

    this.constructor = function () {
        self.isMobile = self.windowWidth <= 767;
        self.isMobileMedium = self.windowWidth > 767 && self.windowWidth <= 991;
        self.isDesktop = self.windowWidth >= 992;
        self.isBootstrapDesign = false;

        $(document).ready(function () {
            if ($(".design-9").length > 0 || $(".design-10").length > 0)
                self.isBootstrapDesign = true;

            if ($(".design-10").length > 0) {
                // Change max. characters on teasergroup 4 text (may change on viewport resize)
                if ($(window).width() > 992) {
                    self.setEllipsisOnText(
                        ".teasergroup-4 .content-container p",
                        4
                    );
                } else if ($(window).width() > 575 && $(window).width() < 992) {
                    self.setEllipsisOnText(
                        ".teasergroup-4 .content-container p",
                        3
                    );
                } else if ($(window).width() < 576) {
                    self.setEllipsisOnText(
                        ".teasergroup-4 .content-container p",
                        "auto"
                    );
                }
            }
        });

        $(window).resize(function () {
            setTimeout(function () {
                self.handleViewportResize();
            }, 500);
        });

        $(window).on("orientationchange", function () {});

        $(window).on("load", function () {
            //Wenn alle Ressourcen (incl. Bilder) geladen sind
        });
    };

    this.setEllipsisOnText = function (selector, lines) {
        $(selector).ellipsis({
            lines: lines,
            ellipClass: "ellip",
            responsive: true,
        });
    };

    this.handleViewportResize = function () {
        if ($(".design-10").length > 0) {
            if ($(window).width() < 767) {
                // remove ellipsis on teasergroup 4
                if ($(window).width() < 576) {
                    self.setEllipsisOnText(
                        ".teasergroup-4 .content-container p",
                        "auto"
                    );
                } else {
                    self.setEllipsisOnText(
                        ".teasergroup-4 .content-container p",
                        3
                    );
                }

                // Triggered after the size of the viewport has changed.
                if (self.windowWidth > 767) {
                    // Switch to mobile ( < 768px )
                    if (self.isMobile !== false || self.isMobile != 0) {
                        self.isMobileMedium = 0;
                        self.isDesktop = 0;
                        self.isMobile = 1;

                        self.windowWidth = $(window).width();
                    }
                }
            } else if (
                (self.windowWidth < 767 || self.windowWidth > 992) &&
                $(window).width() > 767 &&
                $(window).width() < 992
            ) {
                // Switch to tablet ( > 768px && < 992px )
                if (self.isMobileMedium !== true || self.isMobileMedium != 1) {
                    self.isDesktop = 0;
                    self.isMobile = 0;
                    self.isMobileMedium = 1;
                    self.windowWidth = $(window).width();

                    self.setEllipsisOnText(
                        ".teasergroup-4 .content-container p",
                        3
                    );
                }
            } else if (self.windowWidth < 992 && $(window).width() > 992) {
                // Switch to desktop ( > 992px )
                if (self.isDesktop === false || self.isDesktop == 0) {
                    self.isMobile = 0;
                    self.isMobileMedium = 0;
                    self.isDesktop = 1;
                    self.windowWidth = $(window).width();
                }

                self.setEllipsisOnText(
                    ".teasergroup-4 .content-container p",
                    4
                );
            }
        }
    };

    this.constructor();
};

$(document).ready(function () {
    var teasergroup = new Teasergroup();
});


var BcNews = function() {

    var self = this;
	this.windowWidth = $(window).width();
    
    this.constructor = function (){
		self.isMobile = self.windowWidth <= 767;
		self.isMobileMedium = (self.windowWidth > 767) && (self.windowWidth <= 991);
		self.isDesktop = self.windowWidth >= 992;
		self.isBootstrapDesign = false;
		
		self.bcNews = $('.bcnews-main:not(.cloned)');
		self.bcNewsMobileCloned = false;
		self.bcNewsMobile;
		self.bcNewsClone;

		$(document).ready(function(){
			if( $('.design-9').length > 0 || $('.design-10').length > 0 ) self.isBootstrapDesign = true;
			
			//self.initBcNews();
			//self.positionBcNews(); TO DO: prüfen ob Konflike (nach Overhaul entfernt, da kein Mobildesign vorhanden)
			
			if( self.isBootstrapDesign === true ){
				//self.setBcNewsMobileCarousel();
			}
			
			if( self.isDesktop && $('.design-10').length > 0 ){
				self.setTextSlideEffect();
			}
		});

		$(window).resize(function(){
			setTimeout(function(){
				//self.positionBcNews();
				
				self.handleViewportResize();
			}, 500);
		});
		
		$(window).on("orientationchange",function(){
		});
		
		$(window).on("load", function(){
		});
	};
	
	this.setTextSlideEffect = function(){
		self.bcNews.find('.pwTeaser').stop().bind('mouseenter mouseleave', function(e){
			let currentTeaser = $(this);
			let dateText = currentTeaser.find('h4');
			let teaserText = currentTeaser.find('.news-subtitle');
			let slideDuration = 300;
			
			if(teaserText.text().length == 0 ) return false;
			
			// If text has been slided before (viewport change)
			if( teaserText.is(':visible') ){
				teaserText.css('display','none');
			}
			
			if( e.type == 'mouseenter' ){
				dateText.slideUp(slideDuration);
				
				teaserText.slideDown(slideDuration);
			}
			
			if( e.type == 'mouseleave' ){
				teaserText.slideUp(slideDuration);
				
				dateText.slideDown(slideDuration ,function () {
					
				});
			}
		});
	}
	
	this.unsetTextSlideEffect = function(){
		self.bcNews.find('.teaser').unbind('mouseenter mouseleave');
		
		self.bcNews.find('.teaser').each(function(){
			let currentTeaser = $(this);
			let dateText = currentTeaser.find('h4');
			let teaserText = currentTeaser.find('.news-subtitle');
			
			// If text has been slided before (viewport change)
			if( teaserText.attr('style') ){
				teaserText.show();
			}
		});
	}
	
	this.initBcNews = function(){
		//custom function showing current slide
		var status = $('.pwBcNews__pagination');
		var slickElement = $('.bcnews-sidebar .carousel');
		
		/* Beconnect News */
		var slickOptions = {
			slidesToShow: 1,
			slidesToScroll: 1,
			autoplay: true,
			autoplaySpeed: 6000,
			prevArrow: slickElement.find('.prev'),
			nextArrow: slickElement.find('.next'),
			adaptiveHeight: true,
			rows: 0
			/*responsive: [
				{
					breakpoint: 768,
					settings: {
						slidesToShow: 1,
						slidesToScroll: 1,
						infinite: true,
						dots: true,
						arrows: false
					}
				},
				{
					breakpoint: 991,
					settings: {
						slidesToShow: 1,
						slidesToScroll: grid == 4 ? 2 : 1,
						infinite: true,
						dots: true,
						arrows: false
					}
				}
			]*/
		}	

		// Display BeConnect News in Sidebar to slick carousel
		slickElement.slick(slickOptions);
		
		slickElement.on('init reInit afterChange', function (event, slick, currentSlide, nextSlide) {
			var i = (currentSlide ? currentSlide : 0) + 1;
			status.find('.current').text(i); 
		});
	}
	
	this.setBcNewsMobileCarousel = function(){		
		return false;
		// Set slick for mobile view
		var slickElement = self.bcNews.not('.slick-initialized').find('.news-items > .row');
		var paginationContainer = slickElement.parents('.bc-news-list').find('.pagination-container');
		var nextArrow = slickElement.parents('.section').find('.next');
		var prevArrow = slickElement.parents('.section').find('.prev');
				
		var slickOptions = {
			slidesToShow: 1,
			slidesToScroll: 1,
			autoplay: true,
			autoplaySpeed: 10000,
			prevArrow: prevArrow,
			nextArrow: nextArrow,
			adaptiveHeight: true,
			dots: false,
			mobileFirst: true,
			infinite: true,
			responsive: [
				{
					breakpoint: 576,
					settings: {
						slidesToShow: 2,
						slidesToScroll: 2,
					}
				},
				{
					breakpoint: 992,
					settings: 'unslick'
				}
			]
		}
		
		// Create pagination before slick is created						
		self.setCarouselPagination( slickElement, paginationContainer );	
		
		if( !slickElement.hasClass('slick-initialized') ){
			slickElement.slick(slickOptions);
		}
	}

	
	// Same as teasergroup
	this.setCarouselPagination = function( currentCarousel, paginationContainer ){
		if( paginationContainer.length == 0 ) return;
		if( self.bcNews.find('.teaser').length == 0 ) return;
		
		currentCarousel.on('init reInit afterChange', function (event, slick, currentSlide, nextSlide) {
			//currentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based)
			let i = (currentSlide ? currentSlide : 0) + 1; 
			
			let slidesPerPage = slick.options.slidesToShow;
			let maxSlides = slick.slideCount;
			let maxPages = Math.ceil(maxSlides / slidesPerPage);
			let currentSlideIndex = i;
			let currentPage = Math.ceil(currentSlideIndex / slidesPerPage);
			
			if( currentPage < 10 ) currentPage = '0' + String(currentPage);
			if( maxPages < 10 ) maxPages = '0' + String(maxPages);
			
			paginationContainer.text(currentPage + '/' + maxPages);
		});
	}
	
	this.positionBcNews = function(){
		// Design 1-8
		if( self.isBootstrapDesign == false && $('.design-1').length > 0 ){
			// creates copy of original element for usage below nav	
			if( self.bcNewsMobileCloned === false && $('.bcnews-main.cloned').length == 0 ){
				self.bcNewsClone = $('.bcnews-main:not(.cloned)').clone().addClass('cloned');
	
				// append copy 
				if( $('.nav-sub-mobile').next().hasClass('left') ){ 
					// wenn an der position bereits mobile teaser eingepflegt sind, werden news nach den teasern angezeigt
					self.bcNewsClone.insertAfter('.pwMain > .left').hide();
				} else {
					self.bcNewsClone.insertAfter('.nav-sub-mobile').hide();
				}
				
				self.bcNewsMobile = $('.bcnews-main.cloned');
				self.bcNewsMobileCloned = true;
			}
	
			if( $(window).width() > 980 ){
				if( self.bcNews.is(':visible') == false )
					self.bcNews.show();
				
				if( self.bcNewsMobile.is(':visible') == true )
					self.bcNewsMobile.hide();
			} else {
				if( self.bcNews.is(':visible') == true )
					self.bcNews.hide();
					
				if( self.bcNewsMobile.is(':visible') == false )
					self.bcNewsMobile.show();
			}
		}
	}
		
	this.handleViewportResize = function(){		
		
		if( self.isBootstrapDesign == 1 ){
			// Triggered after the size of the viewport has changed.
			if( self.windowWidth > 767 && $(window).width() < 767){
				
				// Switch to mobile ( < 768px )
				if( self.isMobile  !== false || self.isMobile  != 0 ){
					self.isMobileMedium = 0;
					self.isDesktop = 0;
					self.isMobile = 1;
					self.windowWidth = $(window).width();
					
					if( self.isBootstrapDesign === true ){
						self.setBcNewsMobileCarousel();
					}
					
					if( $('.design-10').length > 0 ){
						self.unsetTextSlideEffect();
					}

				}
			} else if( (self.windowWidth < 767 || self.windowWidth > 992) && ($(window).width() > 767) && ($(window).width() < 992) ){
				
				// Switch to tablet ( > 768px && < 992px )
				if( self.isMobileMedium !== true || self.isMobileMedium != 1 ){
					self.isDesktop = 0;
					self.isMobile = 0;
					self.isMobileMedium = 1;
					self.windowWidth = $(window).width();
					
					if( self.isBootstrapDesign === true ){
						self.setBcNewsMobileCarousel();
					}
					
					if( $('.design-10').length > 0 ){
						self.unsetTextSlideEffect();
					}
				}
			} else if( (self.windowWidth < 992) && ($(window).width() > 992) ){
				
				// Switch to desktop ( > 992px )
				if( self.isDesktop === false || self.isDesktop == 0 ){
					self.isMobile = 0;
					self.isMobileMedium = 0;
					self.isDesktop = 1; 
					self.windowWidth = $(window).width();
					
					if( self.isBootstrapDesign === true ){
						self.setBcNewsMobileCarousel();
					}
					
					if( $('.design-10').length > 0 ){
						self.setTextSlideEffect();
					}
				} 
			}
			
			if( $(window).width() < 992 ){}
		}
		
		
	};
	
	this.constructor();
}	

$(document).ready(function(){
	var bcNews = new BcNews();
});


