// Cookie
function setCookie(cookieName,cookieValue,daysToExpire,path,domain)
{
	var date = new Date();
	date.setTime(date.getTime()+(daysToExpire*24*60*60*1000));
	document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString() + '; path=' + path;
	// + 'domain=' + domain
}

function getCookieValue(cookieName) 
{
	var cookieValue = document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
	return cookieValue ? cookieValue.pop() : '0';
}

function is_email(email)
{
	var regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	return regex.test(email);
}

$(document).ready(function() 
{
	setTimeout(function(){ init(); }, 50);
});

function init()
{
	$('a[href*="#order"]').each(function() {
		$(this).on("click", function(e) {
			e.preventDefault();
			$([document.documentElement, document.body]).animate({
				scrollTop: $("#order").offset().top - 80
			}, 500);
		})
	});
	
	// Main menu toggle
	$(".nav_toggle").on("click", function()
	{
		if($("#menu_list").hasClass("open"))
		{
			$("#menu_list").removeClass("open");
		}
		else
		{
			$("#menu_list").addClass("open");
		}				
	});

	let cookies = getCookieValue('Policy');
	if(cookies != 'true') 
	{
		$("#cookie").show();
		$("footer").find(".container").addClass("cookie_spacer");
	}

	$('#cookie .close').click(function()
	{
		$('#cookie').hide();
		$(".cookie_spacer").removeClass("cookie_spacer");
		setCookie('Policy', 'true', '365', '/');
	});

	$(".personal_data_link").on("click", function(event)
	{
		event.preventDefault();
		window.open('/personal_data/', "_blank");
	});

	var urlSearchParams = new URLSearchParams(window.location.search);
	var params = Object.fromEntries(urlSearchParams.entries());

	for(let i in params)
	{
		if(i.indexOf("utm_") > -1)
		{
			setCookie(i, params[i], '365', '/');
		}
	}

	$("#bx-panel-expander").on("click", function()
	{
		$(".header_with_offset").removeClass("header_with_offset").addClass("header_with_offset_extended");
		$(".content_with_offset").removeClass("content_with_offset").addClass("content_with_offset_extended");
	});

	$("#bx-panel-hider").on("click", function()
	{
		$(".header_with_offset_extended").removeClass("header_with_offset_extended").addClass("header_with_offset");
		$(".content_with_offset_extended").removeClass("content_with_offset_extended").addClass("content_with_offset");
	});

	$(".header_recall_button").on("click", function()
	{
		ComagicWidget.openSitePhonePanel();
	});

	// News Slider
	const setupPrevNextBtns = (prevBtn, nextBtn, embla) => {
		if (typeof prevBtn != "undefined" && prevBtn != null) {
			prevBtn.addEventListener("click", embla.scrollPrev, false);
		}
		if (typeof nextBtn != "undefined" && nextBtn != null) {
			nextBtn.addEventListener("click", embla.scrollNext, false);
		}
	};

	const disablePrevNextBtns = (prevBtn, nextBtn, embla) => {
		return () => {
			if(prevBtn !== null)
			{
				if (embla.canScrollPrev()) prevBtn.removeAttribute("disabled");
				else prevBtn.setAttribute("disabled", "disabled");
			}

			if(nextBtn !== null)
			{
				if (embla.canScrollNext()) nextBtn.removeAttribute("disabled");
				else nextBtn.setAttribute("disabled", "disabled");
			}
		};
	};

	const newsWrapper = document.getElementById("news");
	const newsSlider = document.querySelector(".news_slider_wrapper");

	if (typeof newsSlider != "undefined" && newsSlider != null) {
		let newsSliderOption = {
			loop: false,
			dragFree: true,
			slidesToScroll: 1,
			containScroll: "trimSnaps",
			align: "center",
			skipSnaps: false
		};
		const prevBtn = newsWrapper.querySelector(".prev");
		const nextBtn = newsWrapper.querySelector(".next");
		const News = EmblaCarousel(newsSlider, newsSliderOption);

		const disablePrevAndNextBtns = disablePrevNextBtns(prevBtn, nextBtn, News);
		setupPrevNextBtns(prevBtn, nextBtn, News);
		News.on("select", disablePrevAndNextBtns);
		News.on("init", disablePrevAndNextBtns);
	}

	// Переключение расширенного фильтра в каталоге
	/*
	let richFilterToggle = document.getElementById("rich_filter_toggle");
	if (typeof richFilterToggle != "undefined" && richFilterToggle != null) {
		richFilterToggle.addEventListener("click", function (event) {
			document.getElementById("filter").classList.toggle("visible");
			document
				.getElementById("catalog_small_filter")
				.classList.toggle("hidden");
		});
	}
	*/

	// Контакты
	let officeViewToggle = document.getElementById("officeViewToggle");
	if (typeof officeViewToggle != "undefined" && officeViewToggle != null) {
		officeViewToggle.querySelectorAll(".tab").forEach((tab) => {
			tab.addEventListener("click", (event) => {
				if (!event.currentTarget.classList.contains("active")) {
					let tabAttr = event.currentTarget.getAttribute("data-view");
					for (let sibling of tab.parentNode.children) {
						sibling.classList.remove("active");
					}
					event.currentTarget.classList.add("active");
					document.getElementById("map").classList.toggle("visible");
					document.getElementById("offices").classList.toggle("visible");
				}
			});
		});
	}

	// Слайдер в лизинге
	const specialSliderWrapper = document.querySelector("#special_slider");

	if (
		typeof specialSliderWrapper != "undefined" &&
		specialSliderWrapper != null
	) {
		document.querySelectorAll(".section_title")[0].classList.add("wp");
		let specialSliderOption = {
			loop: false,
			dragFree: true,
			containScroll: "trimSnaps",
		};

		const prevBtn = specialSliderWrapper.querySelector(".prev");
		const nextBtn = specialSliderWrapper.querySelector(".next");
		const specialSlider = EmblaCarousel(specialSliderWrapper, specialSliderOption);

		const disablePrevAndNextBtns = disablePrevNextBtns(prevBtn, nextBtn, specialSlider);
		setupPrevNextBtns(prevBtn, nextBtn, specialSlider);
		specialSlider.on("select", disablePrevAndNextBtns);
		specialSlider.on("init", disablePrevAndNextBtns);
	}

	// Слайдер в лизинге внутренний
	const leasingSliderWrapper = document.querySelector("#leasing_slider");

	if (
		typeof leasingSliderWrapper != "undefined" &&
		leasingSliderWrapper != null
	) {

		const leasingContainer = document.querySelector(".leasing_offer");
		let leasingSliderOption = {
			loop: false,
			dragFree: true,
			containScroll: "trimSnaps",
		}; 

		const prevBtn = leasingContainer.querySelector(".prev");
		const nextBtn = leasingContainer.querySelector(".next");
		const leasingSlider = EmblaCarousel(leasingSliderWrapper, leasingSliderOption);

		const disablePrevAndNextBtns = disablePrevNextBtns(prevBtn, nextBtn, leasingSlider);
		setupPrevNextBtns(prevBtn, nextBtn, leasingSlider);
		leasingSlider.on("select", disablePrevAndNextBtns);
		leasingSlider.on("init", disablePrevAndNextBtns);
	}

	// Слайдер с точками
	const setupDotBtns = (dotsArray, embla) => {
		dotsArray.forEach((dotNode, i) => {
			dotNode.addEventListener("click", () => embla.scrollTo(i), false);
		});
	};
	const generateDotBtns = (dots, embla) => {
		const template = document.getElementById("embla-dot-template").innerHTML;
		dots.innerHTML = embla.scrollSnapList().reduce(acc => acc + template, "");
		return [].slice.call(dots.querySelectorAll(".embla__dot"));
	};

	const selectDotBtn = (dotsArray, embla) => () => {
		const previous = embla.previousScrollSnap();
		const selected = embla.selectedScrollSnap();
		dotsArray[previous].classList.remove("is-selected");
		dotsArray[selected].classList.add("is-selected");
	};

	const sliderWithFade = document.querySelector("#single_slider");
	if (
		typeof sliderWithFade != "undefined" &&
		sliderWithFade != null
	) {
		let sliderWithFadeOption = {
			loop: false,
			skipSnaps: false
		};
		const singleSlider = EmblaCarousel(
			sliderWithFade,
			sliderWithFadeOption
		);
		
		const dots = document.querySelector(".slider_dots");
		const dotsArray = generateDotBtns(dots, singleSlider);
		const setSelectedDotBtn = selectDotBtn(dotsArray, singleSlider);
		setupDotBtns(dotsArray, singleSlider);
		singleSlider.on("select", setSelectedDotBtn);
		singleSlider.on("init", setSelectedDotBtn);
	}

	// Выпадающие блоки
	const dropdownBlock = document.querySelectorAll(".dropdown_block");
	if (dropdownBlock.length > 0) {
		for (i = 0; i < dropdownBlock.length; i++) {
			dropdownBlock[i].querySelectorAll(".block_header").forEach((block) => {
				block.addEventListener("click", (event) => {
					block.closest(".dropdown_block").classList.toggle("open");
				});
			});
		}
	}

	// Фильтры
	const filterBlock = document.querySelectorAll(".sort_selector");
	if (filterBlock.length > 0) {
		for (i = 0; i < filterBlock.length; i++) {
			filterBlock[i].querySelectorAll("button").forEach((block) => {
				block.addEventListener("click", (event) => {
					block.closest(".sort_selector").classList.toggle("open");
				});
			});
		}
	}

	$(document).on('DOMNodeInserted', function(e) 
	{
		if ( $(e.target).hasClass('carrotquest-messenger-right_bottom') ) 
		{
			comagic_position(true);
		}
	});

	$(window).on("resize", function()
	{
		comagic_position(false);
	});
}

function comagic_position(init)
{
	var style = "";
	if(window.innerWidth >= 1280)
	{
		style = "margin-bottom: 3px !important; right: -14px!important; z-index: 999!important;";
//		style = 'bottom: -10px!important; right: -14px!important; z-index: 999!important;';
	}
//	else if(window.innerWidth >= 480)
//	{
//		style = "bottom: " + (init ? "60" : "0") + "px!important; right: -14px!important; z-index: 999!important;";
//	}
	else
	{
		style = "margin-bottom: 73px !important; right: -14px!important; z-index: 999!important;";
//		style = 'bottom: -15px!important; right: -14px!important; z-index: 999!important;';
	}

	$('.carrotquest-messenger-right_bottom').attr('style', style);
}