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 CBHeroBannerCarousel(
	carousel
	, prevButton
	, nextButton
	, ulSlide
	, slides
	, nav
	, transition_time
) {
	const navItems = Array.from(nav).slice(0, -1);

	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 updateCarousel() {
		ulSlide.style.transform = 'translate3d(-' + currentIndex + '00vw, 0, 0)';

		slides.forEach((slide) => {
			slide.classList.remove('active');
		});

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

		if (currentIndex == 0) {
			setTimeout(() => {
				ulSlide.style.transition = 'none';
				ulSlide.style.transform = 'translate3d(-' + currentIndex + '00vw, 0, 0)';
			}, 700);
			currentIndex = slides.length;
		} else {
			ulSlide.style.transition = 'transform 0.7s ease-in-out';
		}

		navItems.forEach((navItem) => {
			navItem.classList.remove('active');
		});

		slides[currentIndex - 1].classList.add('active');
		navItems[currentIndex - 1].classList.add('active');
		if (slides.length == 1) {
			nav[nav.length - 1].style.display = 'none';
		}
	}

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

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

	function stopAutoSlide() {
		clearInterval(autoSlideInterval);
	}

	prevButton.addEventListener('click', function () {
		stopAutoSlide();
		autoSliding = false;
		currentIndex--;
		updateCarousel();
		startAutoSlide();
	});

	nextButton.addEventListener('click', function () {
		stopAutoSlide();
		autoSliding = false;
		nextSlide();
		startAutoSlide();
	});

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

	carousel.addEventListener('mouseover', function () {
		stopAutoSlide();
	});

	carousel.addEventListener('mouseout', function () {
		if (autoSliding) {
			startAutoSlide();
		}
	});

	let touchStartX = 0;
	let touchEndX = 0;

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

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

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

			autoSliding = false;
		});
	}

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

	updateCarousel();
	startAutoSlide();

	function adjustCarousel() {
		var windowWidth = window.innerWidth;
		var listSlide = carousel.querySelectorAll('ul:first-child>li');
		var maxHeight = windowWidth >= 1024 ? 705 : 0;

		listSlide.forEach(function (element) {
			var article = element.querySelector('article');
			if (article) {
				if (windowWidth < 1024) {
					article.style.height = 'auto';
				} else {
					article.style.height = '100%';
				}
				var currentHeight = article.offsetHeight;
				if (currentHeight > maxHeight) {
					maxHeight = currentHeight;
				}
			}
		});

		listSlide.forEach(function (element) {
			var article = element.querySelector('article');
			var figure = element.querySelector('figure');

			if (article) {
				article.style.height = maxHeight + 'px';
			}
			if (figure) {
				if (windowWidth > 1024) {
					figure.style.height = maxHeight + 'px';
				} else {
					figure.style.height = '';
				}
			}
		});

		if (windowWidth >= 768 && windowWidth <= 1024) {
			const slide = carousel.querySelector('ul:first-child>li.active>figure');
			slide.addEventListener('click', function () {
				var url = slide.getAttribute('data-url');
				if (url) {
					window.open(url, '_blank');
				}
			});
		}
	}

	adjustCarousel();

	window.addEventListener('resize', function () {
		adjustCarousel();
	});
}


function CBFeatureCarousel(
	carousel,
	carouselCaption,
	prevButton,
	nextButton,
	dotsContainer,
	transition_time
) {
	let captionIndex = 1;
	let carouselIndex = 1;
	let autoSlideInterval;
	let autoSliding = true;
	const slidesCount = carousel.querySelectorAll('li').length;

	function setupCarousel() {
		const originalSlides = [...carousel.querySelectorAll('li')];

		const lastSlideClone = originalSlides[slidesCount - 1].cloneNode(true);
		lastSlideClone.classList.add('clone');
		carousel.insertBefore(lastSlideClone, originalSlides[0]);

		const firstSlideClone = originalSlides[0].cloneNode(true);
		firstSlideClone.classList.add('clone');
		carousel.appendChild(firstSlideClone);

		const gap = parseFloat(getComputedStyle(carousel).columnGap) || 0;
		const slideWidth = originalSlides[0].offsetWidth;

		const offset = (carousel.parentElement.offsetWidth - slideWidth) / 2;
		const translateX = -carouselIndex * (slideWidth + gap) + offset;

		carousel.style.transition = 'none';
		carousel.style.transform = `translateX(${translateX}px)`;
	}

	function updateCarousel(slideIndex) {
		const parentWidth = carousel.parentElement.offsetWidth;
		const gap = parseFloat(getComputedStyle(carousel).columnGap) || 0;
		const slideWidth = carousel.querySelectorAll('li')[0].offsetWidth;

		const offset = (parentWidth - slideWidth) / 2;
		let translateX = -slideIndex * (slideWidth + gap) + offset;

		carousel.style.transition = 'transform 0.5s ease';
		carousel.style.transform = `translateX(${translateX}px)`;

		carousel.addEventListener('transitionend', function handler() {
			if (slideIndex == slidesCount + 1) {
				carousel.style.transition = 'none';
				const resetOffset = -1 * (slideWidth + gap) + offset;
				carousel.style.transform = `translateX(${resetOffset}px)`;
			}
			if (slideIndex == 0) {
				carousel.style.transition = 'none';
				const resetOffset = -slidesCount * (slideWidth + gap) + offset;
				carousel.style.transform = `translateX(${resetOffset}px)`;
			}
			carousel.removeEventListener('transitionend', handler);
		}, { once: true });
	}

	function setupCarouselCaption() {
		const captions = [...carouselCaption.querySelectorAll('li')];
		const visibleItems = 3;
		const style = window.getComputedStyle(carouselCaption);
		const gap = parseFloat(style.gap) || 0;

		for (let i = 0; i < visibleItems; i++) {
			const firstClone = captions[i].cloneNode(true);
			firstClone.classList.add('first-caption-cloned');
			carouselCaption.appendChild(firstClone);
		}

		for (let i = visibleItems - 1; i >= 0; i--) {
			const index = captions.length - visibleItems + i;
			const lastClone = captions[index].cloneNode(true);
			lastClone.classList.add('last-caption-cloned');
			carouselCaption.insertBefore(lastClone, carouselCaption.firstChild);
		}

		const itemWidth = captions[0].offsetWidth;
		const totalItemWidth = itemWidth + gap;

		carouselCaption.style.transition = 'none';
		carouselCaption.style.transform = `translateX(${-totalItemWidth * visibleItems}px)`;
		captions[0].classList.add('active');
	}

	function updateCaption(slideIndex) {
		const visibleItems = 3;

		const item = carouselCaption.querySelector('li');
		const itemWidth = item.offsetWidth;
		const style = window.getComputedStyle(carouselCaption);
		const gap = parseFloat(style.gap) || 0;
		const totalItemWidth = itemWidth + gap;

		const newOffset = -totalItemWidth * (visibleItems - 1 + slideIndex);
		carouselCaption.querySelectorAll('li').forEach(el => {
			el.classList.remove('active');
		});
		const resetCondition = slideIndex > slidesCount || slideIndex == (slidesCount - 1) * -1;
		let activeIndex = visibleItems - 1 + slideIndex;
		carouselCaption.querySelectorAll('li')[activeIndex].classList.add('active');
		if (resetCondition) {
			let resetIndex = slidesCount - 1;
			if (resetIndex < visibleItems)
				resetIndex = visibleItems;
			carouselCaption.querySelectorAll('li')[resetIndex].classList.add('active');
		}

		carouselCaption.style.transition = 'transform 0.5s ease';
		carouselCaption.style.transform = `translateX(${newOffset}px)`;

		carouselCaption.addEventListener('transitionend', function handler() {
			setTimeout(function () {
				if (slideIndex > slidesCount || slideIndex == (slidesCount - 1) * -1) {
					carouselCaption.style.transition = 'none';
					const resetOffset = -totalItemWidth * visibleItems;
					carouselCaption.style.transform = `translateX(${resetOffset}px)`;
				}
				carouselCaption.removeEventListener('transitionend', handler);
			}, 250);
		}, { once: true });
	}

	function nextSlide() {
		captionIndex++;
		updateCaption(captionIndex);

		if (captionIndex == slidesCount + 1)
			captionIndex = 1;

		carouselIndex++;
		updateCarousel(carouselIndex);
		if (carouselIndex == slidesCount + 1)
			carouselIndex = 1;

		setActiveDots(carouselIndex);
	}

	function prevSlide() {
		captionIndex--;
		updateCaption(captionIndex);
		if (captionIndex == (slidesCount - 1) * -1)
			captionIndex = 1;

		carouselIndex--;
		updateCarousel(carouselIndex);
		if (carouselIndex == 0)
			carouselIndex = slidesCount;

		setActiveDots(carouselIndex);
	}

	function setActiveDots(index) {
		const dots = dotsContainer.querySelectorAll('li');
		dots.forEach(el => {
			el.classList.remove('active');
		});

		dots[index - 1].classList.add('active');
	}

	function startAutoSlide() {
		if (autoSliding && slidesCount >= 1 && typeof (autoSlideInterval) === 'undefined') {
			autoSlideInterval = setInterval(nextSlide, transition_time);
		}
	}

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

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

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

	carousel.addEventListener('mouseover', function () {
		stopAutoSlide();
	});

	carousel.addEventListener('mouseout', function () {
		if (autoSliding) {
			startAutoSlide();
		}
	});

	carouselCaption.addEventListener('mouseover', function () {
		stopAutoSlide();
	});

	carouselCaption.addEventListener('mouseout', function () {
		if (autoSliding) {
			startAutoSlide();
		}
	});

	dotsContainer.addEventListener('mouseover', function () {
		stopAutoSlide();
	});

	dotsContainer.addEventListener('mouseout', function () {
		if (autoSliding) {
			startAutoSlide();
		}
	});

	dotsContainer.querySelectorAll('li').forEach((el, index) => {
		el.addEventListener('click', function () {
			carouselIndex = index + 1;
			captionIndex = index + 1;
			updateCaption(captionIndex);
			updateCarousel(carouselIndex);

			this.parentElement.querySelectorAll('li').forEach(li => li.classList.remove('active'));
			this.classList.add('active');
		});
	})

	setupCarousel();
	setupCarouselCaption();
	startAutoSlide();

	window.addEventListener('resize', function () {
		this.setTimeout(function () {
			updateCaption(captionIndex);
			updateCarousel(captionIndex);
		}, 500);
	});
}