class CBHeader {
	constructor(header, arrow_down, arrow_up) {
		this.header = header;
		this.logo = this.header.querySelector('a'); //Header part 1
		this.burgerBtn = this.header.querySelector('button'); //Header part 2
		this.mainMenu = this.header.querySelector('ul'); //Header part 3
		this.loginMenu = this.header.querySelector('nav'); //Header part 4
		this.arrow_down = arrow_down;
		this.arrow_up = arrow_up;
	}

	init() {
		window.addEventListener('resize', (e) => {
			this.checkResponsive();
		});
		this.checkResponsive();
		this.toggleMobileMenu();
	}

	checkResponsive() {
		const width = window.innerWidth;
		if (
			width <= 1100 && this.header.classList.contains('mobile') ||
			width > 1100 && !this.header.classList.contains('mobile')
		) {
			return;
		}

		//Remove the header content
		this.header.innerHTML = '';

		//Add the mobile menu and login menu to the mobile wrapper
		if (width <= 1100) {
			this.header.classList.add('mobile');
			let mobileWrapper = document.createElement('section');
			let mobileMenu = this.mainMenu.cloneNode(true);

			//Add arrow icons to the menu items that have children
			mobileMenu.querySelectorAll('li').forEach(el => {
				if (el.querySelector('ul') !== null) {
					el.querySelector('a').insertAdjacentHTML('afterend', `<button onclick="this.parentNode.classList.toggle('active');">${this.arrow_down}</button>`);
				}
			});

			//Add the mobile menu and login menu to the mobile wrapper
			mobileWrapper.append(mobileMenu, this.loginMenu);
			this.header.append(this.logo, this.burgerBtn, mobileWrapper);
			this.toggleMobileSubMenu();
		}

		//Add the desktop menu and login menu to the header
		if (width > 1100) {
			this.header.classList.remove('mobile');
			this.header.append(this.logo, this.mainMenu, this.loginMenu);
		}
	}

	toggleMobileMenu() {
		this.header.querySelector('button').addEventListener('click', (e) => {
			e.preventDefault();
			this.header.classList.toggle('active');

			//Close all submenus when the mobile menu is closed
			if (!this.header.classList.contains('active')) {
				this.header.querySelector('nav').querySelector('button').classList.remove('active');
				this.header.querySelectorAll('section > ul > li').forEach(el => {
					el.classList.remove('active');
				});
			}
		});
	}

	toggleMobileSubMenu() {
		// this.header.querySelectorAll('section > ul > li > a').forEach(el => {
		// 	const parent = el.parentElement;
		// 	if (parent.querySelector('ul'))
		// 		el.addEventListener('click', (e) => {
		// 			if (!parent.classList.contains('active')) {
		// 				e.preventDefault();
		// 				parent.classList.toggle('active');
		// 			}
		// 		});
		// });
	}
}

CBFooter = function () {
	//Handle scroll to anchor links with offset.
	function scrollToAnchor(elName) {
		const targetElement = document.querySelector(`a[name=${elName}]`);
		if (targetElement) {
			const headerOffset = 80;
			const elementPosition = targetElement.getBoundingClientRect().top + window.scrollY;
			const offsetPosition = elementPosition - headerOffset;
			window.scrollTo({
				top: offsetPosition,
				behavior: "smooth"
			});
		}
	}

	//Add event sto links with hash
	document.querySelectorAll('a[href^="#"]').forEach(anchor => {
		anchor.addEventListener("click", function (e) {
			e.preventDefault();
			const elName = this.getAttribute("href").substring(1);
			scrollToAnchor(elName);
		});
	});

	//Scroll to anchor if hash is present in URL
	if (window.location.hash) {
		setTimeout(() => {
			const elName = window.location.hash.substring(1);
			scrollToAnchor(elName);
		}, 100); // Small delay to ensure the page is loaded before scrolling
	}
}

function CBError(errors){
	var _errno=null;
	var _error=null;
	function errno(){return _errno;}
	function error(){return _error;}
	function reset(){_errno=null;error=null;}
	function set(errno,replaceObj,ret){
		_errno=errno;
		_error=errors[errno];
		for(let i in replaceObj){
			_error=_error.replace('{'+i+'}',replaceObj[i]);
		}
		if(typeof(ret)=='undefined'){ret=false;}
		return ret;
	}
	return {
		errno	:errno,
		error	:error,
		reset	:reset,
		set		:set
	}
}


function CBCarouselAccountCards(
	el
	, transition_time
	, slidesToShow
	, autoSlidingSetting
) {
	//check for responsive. TODO: put this number in settings
	let isIpad = window.innerWidth <= 1024;
	let isMobile = window.innerWidth <= 576;

	const slides = el.querySelectorAll('article[aria-label="Account cards carousel"] > ul > li');
	const navItems = el.querySelectorAll('nav>ol[data-responsive="mobile"]>li');

	const navCarousel = {
		carouselContainer: el.querySelector('article'),
		prevButton: el.querySelector('.prev'),
		nextButton: el.querySelector('.next'),
		prevButton2: el.querySelector('nav[aria-label="Carousel navigation"] .prev'),
		nextButton2: el.querySelector('nav[aria-label="Carousel navigation"] .next'),
		ulSlide: el.querySelector('article>ul'),
		slides: el.querySelectorAll('article[aria-label="Account cards carousel"] > ul > li'),
		navItems: el.querySelectorAll('nav>ol[data-responsive="mobile"]>li'),
		transition_time: transition_time,
		slidesToShow: isIpad ? slidesToShow - 1 : slidesToShow,
		autoSlidingSetting: autoSlidingSetting,
		dotsActionMobile: el.querySelectorAll('ol[data-responsive="mobile"] li'),

		//private properties
		slidesToScroll: 1,
		currentIndex: 1,
		autoSlideInterval: undefined,
		autoSliding: autoSlidingSetting,

		updateCarousel() {
			var $this = this;
			const isPC = window.innerWidth > 1024;
			if ($this.slides.length == 3 && isPC) {
				el.querySelector('ol[data-responsive="mobile"]').style.display = "none";
				el.querySelector('.prev').style.display = "none";
				el.querySelector('.next').style.display = "none";
				$this.stopAutoSlide();
			} else {
				el.querySelector('ol[data-responsive="mobile"]').style.display = "block";
				el.querySelector('.prev').style.display = "block";
				el.querySelector('.next').style.display = "block";
			}
			$this.slides.forEach((slide) => {
				slide.classList.remove('active');
			});

			var carouselWidth = parseInt($this.ulSlide.style.getPropertyValue('--carousel-width'));
			var carouselSlideWidth = parseInt($this.ulSlide.style.getPropertyValue('--carousel-slide-width'));
			const computedStyles = window.getComputedStyle($this.ulSlide);
			var slideGap = computedStyles.gap != "" ? parseInt(computedStyles.gap) : 0;
			isIpad = window.innerWidth <= 1024;
			var positionTranslate = $this.slides.length > 3 ? ((carouselWidth / 3) + (slideGap / 3)) : 0;
			var slideLength = 0;
			if (isMobile) {
				slideLength = carouselWidth;
			} else {
				slideLength = isIpad ? ((carouselWidth / 2) + (slideGap / 2)) : positionTranslate;
			}
			$this.ulSlide.style.transform = 'translate3d(-' + $this.currentIndex * slideLength + 'px, 0, 0)';

			if ($this.slides.length < $this.currentIndex) {
				setTimeout(() => {
					$this.ulSlide.style.transition = 'none';
					$this.ulSlide.style.transform = 'translate3d(-' + slideLength + 'px, 0, 0)';
				}, 700);
				$this.currentIndex = 1;
			} else {
				$this.ulSlide.style.transition = 'transform 0.7s ease-in-out';
			}

			if ($this.currentIndex == 0) {
				setTimeout(() => {
					$this.ulSlide.style.transition = 'none';
					$this.ulSlide.style.transform = 'translate3d(-' + $this.slides.length * slideLength + 'px, 0, 0)';
				}, 700);
				$this.currentIndex = slides.length;
			} else {
				$this.ulSlide.style.transition = 'transform 0.7s ease-in-out';
			}
			$this.slides[$this.currentIndex - 1].classList.add('active');
			//update nav
			if (navItems.length > 3 || isMobile || isIpad) {
				navItems.forEach((navItem) => {
					navItem.classList.remove('active');
				});
	
				navItems[$this.currentIndex - 1].classList.add('active');
			}

			// Update position nav pre and next
			const carouselNav = el.querySelector('nav[aria-label="Carousel navigation"]');
			const ol = carouselNav.querySelector("ol[data-responsive='mobile']");
			const nav = carouselNav.querySelector('nav');
			nav?.style.setProperty("max-width", ol.offsetWidth + 100 + "px");
			
			$this.dotsActionMobile?.forEach((li, index) => {
				li.addEventListener("click", function () {
					$this.autoSliding = false;
					$this.stopAutoSlide();
					$this.dotsActionMobile.forEach(dot => dot.classList.remove("active"));
					this.classList.add("active");
					if (index == 0) {
						$this.ulSlide.style.transform = `translate3d(-${slideLength}px, 0, 0)`;
					} else {
						$this.ulSlide.style.transform = `translate3d(-${(index + 1) * slideLength}px, 0, 0)`;
					}
				});
			});
		},

		nextSlide() {
			var $this = this;
			$this.currentIndex++;
			$this.updateCarousel();
		},

		startAutoSlide() {
			var $this = this;

			if ($this.autoSlidingSetting && $this.autoSliding && ($this.slides.length > 3 || isIpad || isMobile) && typeof ($this.autoSlideInterval) == 'undefined') {
				$this.autoSlideInterval = setInterval(function () { $this.nextSlide(); }, $this.transition_time);
			}
		},

		stopAutoSlide() {
			var $this = this;
			clearInterval($this.autoSlideInterval);
			$this.autoSlideInterval = undefined;
		},

		adjustCarousel() {
			var $this = this;
			var carouselWidth = $this.carouselContainer.offsetWidth;
			$this.ulSlide.style.setProperty('--carousel-width', carouselWidth + 'px');
			const computedStyles = window.getComputedStyle($this.ulSlide);
			var slideGap = computedStyles.gap != "" ? parseInt(computedStyles.gap) : 0;
			const isMobile = window.innerWidth <= 576;
			const isIpad = window.innerWidth <= 1024;

			if (isIpad) {
				$this.ulSlide.style.setProperty('--carousel-slide-width', ((carouselWidth - ($this.slidesToShow - 1) * slideGap) / $this.slidesToShow) + 'px');
				var navDotIpad = document.querySelectorAll('nav>ol[data-responsive="ipad"] ol');
				var headerNavButtons = document.querySelectorAll(
					'section[rel="CBCarouselAccountCards"] > header > nav'
				);

				if (navDotIpad.length > 0 && headerNavButtons.length > 0) {
					navDotIpad.forEach((ol, index) => {
						let olWidth = ol.offsetWidth;

						if (headerNavButtons[index]) {
							headerNavButtons[index].style.width = `${olWidth + 100}px`;
						}
					});
				}
			}
			else if (isMobile) {
				$this.ulSlide.style.setProperty('--carousel-slide-width', carouselWidth + 'px');

				var navDotMobile = document.querySelectorAll('nav>ol[data-responsive="mobile"] ol');
				var headerNavButtons = document.querySelectorAll(
					'section[rel="CBCarouselAccountCards"] > header > nav'
				);

				if (navDotMobile.length > 0 && headerNavButtons.length > 0) {
					navDotMobile.forEach((ol, index) => {
						let olWidth = ol.offsetWidth;

						if (headerNavButtons[index]) {
							headerNavButtons[index].style.width = `${olWidth + 100}px`;
						}
					});
				}
			} else {
				$this.ulSlide.style.setProperty('--carousel-slide-width', ((carouselWidth - ($this.slidesToShow - 1) * slideGap) / $this.slidesToShow) + 'px');

				document.querySelectorAll('section[rel="CBCarouselAccountCards"] > header > nav').forEach((nav) => {
					nav.style.width = '100px';
				});
			}
		},

		init() {
			var $this = this;
			window.addEventListener('resize', function () {
				isIpad = window.innerWidth <= 1024 && window.innerWidth > 576;
				isMobile = window.innerWidth <= 576;
				if (isIpad) {
					$this.slidesToShow = 2;
				} else if (isMobile) {
					$this.slidesToShow = 1;
				} else {
					$this.slidesToShow = 3;
				}
			});
			//clone first slides based on slidesToShow number    			
			let numberOfFirstClone = 0;
			if ($this.slides.length < $this.slidesToShow) {
				numberOfFirstClone = 0;//ignore this, asume the number of slides is always greater or equal than 3
			} else {
				numberOfFirstClone = $this.slidesToShow;
			}

			for (let index = 0; index < numberOfFirstClone; index++) {
				const firstSlideClone = this.slides[index].cloneNode(true);
				firstSlideClone.classList.add('first-slide-clone');
				$this.ulSlide.appendChild(firstSlideClone);

				const lastSlideClone = this.slides[this.slides.length - 1 - index].cloneNode(true);
				lastSlideClone.classList.add('last-slide-clone');
				$this.ulSlide.insertBefore(lastSlideClone, $this.ulSlide.firstChild);
			}

			$this.currentIndex = 1;
			$this.autoSlideInterval;
			$this.autoSliding = true;

			if ($this.prevButton) {
				$this.prevButton.addEventListener('click', function () {
					preSlider();
				});
			}
			if ($this.nextButton) {
				$this.nextButton.addEventListener('click', function () {
					nextSlider();
				});
			}

			if ($this.prevButton2) {
				$this.prevButton2.addEventListener('click', function () {
					preSlider();
				});
			}
			if ($this.nextButton2) {
				$this.nextButton2.addEventListener('click', function () {
					nextSlider();
				});
			}

			if ($this.navItems && $this.navItems.length > 1) {
				$this.navItems.forEach((dot, index) => {
					dot.addEventListener('click', function () {
						if ($this.slides.length > 3) {
							$this.stopAutoSlide();
							$this.autoSliding = false;
							$this.currentIndex = index;
							$this.currentIndex++;
							$this.updateCarousel();
						}
					});
				});
			}

			function preSlider() {
				if ($this.slides.length > 3 || isIpad) {
					$this.stopAutoSlide();
					$this.autoSliding = false;
					$this.currentIndex--;
					$this.updateCarousel();
					$this.autoSliding = true;
					$this.startAutoSlide();
				}
			}

			function nextSlider() {
				if ($this.slides.length > 3 || isIpad) {
					$this.stopAutoSlide();
					$this.autoSliding = false;
					$this.nextSlide();
				}
			}


			$this.carouselContainer.addEventListener('mouseover', function () {
				$this.stopAutoSlide();
			});

			$this.carouselContainer.addEventListener('mouseout', function () {
				if ($this.autoSliding) {
					$this.startAutoSlide();
				}
			});

			let touchStartX = 0;
			let touchEndX = 0;

			if ($this.slides.length > 1) {
				$this.carouselContainer.addEventListener('touchstart', function (e) {
					$this.stopAutoSlide();
					touchStartX = e.changedTouches[0].screenX;
				});

				$this.carouselContainer.addEventListener('touchend', function (e) {
					touchEndX = e.changedTouches[0].screenX;

					if (touchStartX - touchEndX > 50) {
						$this.nextSlide();
					} else if (touchEndX - touchStartX > 50) {
						const prevIndex = $this.currentIndex > 0 ? $this.currentIndex - 1 : slides.length - 1;
						$this.currentIndex = prevIndex;
						$this.updateCarousel();
					}

					$this.autoSliding = false;
				});
			}

			$this.carouselContainer.querySelectorAll('li a').forEach((a) => {
				a.addEventListener('click', (event) => {
					event.stopPropagation();
				});
			});

			$this.adjustCarousel();
			$this.updateCarousel();

			window.addEventListener('resize', function () {
				$this.adjustCarousel();
				$this.updateCarousel();
			});
			document.addEventListener("DOMContentLoaded", () => {
				$this.carouselContainer.classList.add('carousel-initialized');
				$this.startAutoSlide();
			});
		}
	}
	navCarousel.init();

}


function CBSubscribeToInsightsModal(
	trigger,
	modal,
	closeButton,
	formElement,
	submitElement,
	inputElements,
	validationElements,
	confirmModal,
	confirmCloseButton,
	recaptchaSiteKey,
	feedbackElement,
) {
	// View functions
	function View_clearValidationElements() {
		if (!validationElements) return;
		for (var i in validationElements) {
			if (validationElements[i]) {
				validationElements[i].innerHTML = '';
			}
		}
	}

	function View_clearInputElements() {
		if (!inputElements) return;
		for (var i in inputElements) {
			if (inputElements[i]) {
				inputElements[i].value = '';
				if (inputElements[i].type === 'checkbox') {
					inputElements[i].checked = false;
				}
			}
		}
	}

	function View_displayError(field, message) {
		if (validationElements && validationElements[field]) {
			validationElements[field].innerHTML = message;
		}
	}

	function View_disableSubmission() {
		if (submitElement) {
			submitElement.disabled = true;
		}
		feedbackElement.style.display = 'flex';
	}

	function View_enableSubmission() {
		if (submitElement) {
			submitElement.disabled = false;
		}
		feedbackElement.style.display = 'none';
	}

	function View_disableElements() {
		if (inputElements) {
			for (var field in inputElements) {
				if (inputElements[field]) {
					inputElements[field].disabled = true;
				}
			}
		}
		View_disableSubmission();
	}

	function View_enableElements() {
		if (inputElements) {
			for (var field in inputElements) {
				if (inputElements[field]) {
					inputElements[field].disabled = false;
				}
			}
		}
		View_enableSubmission();
	}

	function openModal() {
		modal.showModal();
		document.body.style.overflow = 'hidden';
	}

	function closeModal() {
		modal.close();
		document.body.style.overflow = '';
		View_clearValidationElements();
		View_clearInputElements();
	}

	// Controller functions
	function Ctrl_stateChange() {
		if (this.readyState !== XMLHttpRequest.DONE) {
			return;
		}
		View_enableElements();

		var responseText = this.responseText.trim();

		// Success case
		if (this.status === 200 && responseText === 'Success') {
			closeModal();
			if (confirmModal) {
				confirmModal.removeAttribute('hidden');
				confirmModal.showModal();
			}
			return;
		}

		// Handle validation errors (try to parse JSON)
		try {
			var res = JSON.parse(responseText);
			if (res && typeof res === 'object') {
				for (var field in res) {
					View_displayError(field, res[field]);
				}
				return;
			}
		} catch (e) {
			// Not JSON, show generic error
		}

		View_displayError('form', 'Could not process request. Please try again later.');
	}

	function Ctrl_formSubmit(token) {
		var FD = new FormData(formElement);
		FD.append('token', token);
		View_clearValidationElements();
		View_disableElements();
		Data_send(FD);
	}

	function Data_send(FD) {
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = Ctrl_stateChange;
		xhr.open('POST', window.location.href, true);
		xhr.send(FD);
	}

	function handleSubmit(e) {
		e.preventDefault();
		e.stopPropagation();
		if (!recaptchaSiteKey) {
			Ctrl_formSubmit('');
			return;
		}
		var recaptchaSK = recaptchaSiteKey
		grecaptcha.ready(function () {
			grecaptcha.execute(recaptchaSK, { action: 'submit' }).then(function (token) {
				Ctrl_formSubmit(token);
			});
		});
	}

	// Open modal on trigger click
	trigger.addEventListener('click', function (e) {
		e.preventDefault();
		openModal();
	});

	// Close modal on close button click
	if (closeButton) {
		closeButton.addEventListener('click', closeModal);
	}

	// Close modal when clicking outside (on backdrop)
	modal.addEventListener('cancel', function (event) {
		event.preventDefault();
		closeModal();
	});

	// Additional click handler for backdrop (fallback)
	modal.addEventListener('click', function (event) {
		if (event.target === modal) {
			var formRect = formElement.getBoundingClientRect();
			var clickX = event.clientX;
			var clickY = event.clientY;
			var isOutsideForm = clickX < formRect.left ||
				clickX > formRect.right ||
				clickY < formRect.top ||
				clickY > formRect.bottom;

			if (isOutsideForm) {
				closeModal();
			}
		}
	});

	// Form submit handler
	if (formElement) {
		formElement.addEventListener('submit', handleSubmit);
	}


	function closeConfirmModal(e) {
		if (e) {
			e.preventDefault();
			e.stopPropagation();
		}
		confirmModal.setAttribute('hidden', '');
		confirmModal.close();
		document.body.style.overflow = '';
	}

	confirmCloseButton.addEventListener('click', closeConfirmModal);
	confirmModal.addEventListener('click', function (event) {
		if (event.target === confirmModal) {
			closeConfirmModal(event);
		}
	});

	confirmModal.addEventListener('cancel', function (e) {
		e.preventDefault();
		closeConfirmModal();
	});
}

function CBPromoCarousel(carousel, prevButton, nextButton, ulSlide, slides, navItems, transition_time) {
    if (!slides.length) return;

    // Clone first and last slides for infinite looping
    const firstSlideClone = slides[0].cloneNode(true);
    firstSlideClone.classList.add('first-slide-clone');
    const lastSlideClone = slides[slides.length - 1].cloneNode(true);
    lastSlideClone.classList.add('last-slide-clone');

    ulSlide.appendChild(firstSlideClone);
    ulSlide.insertBefore(lastSlideClone, slides[0]);

    let currentIndex = 1;
    let autoSlideInterval;
    let autoSliding = true;

    function getSlideWidth() {
        return carousel.offsetWidth; // Keep slides full width
    }

    function setUlSlideDimensions() {
        const slideWidth = carousel.offsetWidth;
        const gap = parseFloat(getComputedStyle(ulSlide).gap) || 0;
        const totalSlides = ulSlide.querySelectorAll('li');

        totalSlides.forEach(slide => {
            if (!slide.classList.contains('slide-item')) return;
            slide.style.width = `${slideWidth}px`; // Maintain full width
        });

        // Properly calculate ulSlide width, including gaps
        ulSlide.style.width = `${(totalSlides.length * slideWidth) + ((totalSlides.length - 1) * gap)}px`;
        ulSlide.style.transform = `translate3d(${-currentIndex * (slideWidth + gap)}px, 0, 0)`; // Fix alignment on load
    }

    function updateCarousel() {
        const slideWidth = getSlideWidth();
        const gap = parseFloat(getComputedStyle(ulSlide).gap) || 0;

        // Fix floating precision errors by rounding
        const translateX = Math.round(-(currentIndex * (slideWidth + gap)));

        ulSlide.style.transition = 'transform 0.7s ease-in-out';
        ulSlide.style.transform = `translate3d(${translateX}px, 0, 0)`;

        navItems.forEach(nav => nav.classList.remove('active'));
        slides.forEach(slide => slide.classList.remove('active'));

        if (currentIndex === 0) {
            setTimeout(() => {
                ulSlide.style.transition = 'none';
                currentIndex = slides.length;
                ulSlide.style.transform = `translate3d(${Math.round(-currentIndex * (slideWidth + gap))}px, 0, 0)`;
            }, 700);
            navItems[navItems.length - 1]?.classList.add('active');
        } else if (currentIndex === slides.length + 1) {
            setTimeout(() => {
                ulSlide.style.transition = 'none';
                currentIndex = 1;
                ulSlide.style.transform = `translate3d(${Math.round(-currentIndex * (slideWidth + gap))}px, 0, 0)`;
            }, 700);
            navItems[0]?.classList.add('active');
        } else {
            slides[currentIndex - 1]?.classList.add('active');
            navItems[currentIndex - 1]?.classList.add('active');
        }
    }

    function nextSlide() {
        currentIndex++;
        updateCarousel();
    }

    function prevSlide() {
        currentIndex--;
        updateCarousel();
    }

    function startAutoSlide() {
        if (autoSliding && slides.length > 1 && !autoSlideInterval) {
            autoSlideInterval = setInterval(nextSlide, transition_time);
        }
    }

    function stopAutoSlide() {
        clearInterval(autoSlideInterval);
        autoSlideInterval = undefined;
    }

    prevButton.forEach(el => {
        el.addEventListener('click', () => {
            stopAutoSlide();
            autoSliding = false;
            prevSlide();
        });
    });

    nextButton.forEach(el => {
        el.addEventListener('click', () => {
            stopAutoSlide();
            autoSliding = false;
            nextSlide();
        });
    });

    if (navItems.length > 1) {
        navItems.forEach((dot, index) => {
            dot.addEventListener('click', () => {
                stopAutoSlide();
                autoSliding = false;
                currentIndex = index + 1;
                updateCarousel();
            });
        });
    }

    carousel.addEventListener('mouseover', stopAutoSlide);
    carousel.addEventListener('mouseout', () => {
        if (autoSliding) startAutoSlide();
    });

    let touchStartX = 0;
    let touchEndX = 0;
    if (slides.length > 1) {
        carousel.addEventListener('touchstart', e => {
            stopAutoSlide();
            touchStartX = e.changedTouches[0].screenX;
        });
        carousel.addEventListener('touchend', e => {
            touchEndX = e.changedTouches[0].screenX;
            if (touchStartX - touchEndX > 50) {
                nextSlide();
            } else if (touchEndX - touchStartX > 50) {
                prevSlide();
            }
            autoSliding = false;
            startAutoSlide();
        });
    }

    setTimeout(() => {
        setUlSlideDimensions();
        updateCarousel();
        startAutoSlide();
    }, 100);

    window.addEventListener('resize', () => {
        setUlSlideDimensions();
        updateCarousel();
    });
}
