
setTimeout(()=>{
window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/lib/swiper-bundle.min.css', 'head');
window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/css/slider-main.min.css', 'head');
window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/css/catalog-main-category.min.css', 'head');
window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/css/advatages-main.min.css', 'head');
window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/css/reviews-main.min.css', 'head');
// window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/css/product-main.min.css', 'head');
window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/css/vk-main.min.css', 'head');
window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/css/subscribe.min.css', 'head');
window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/css/blog-main.min.css', 'head');
window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/css/catalog-menu-load.min.css', 'head');
window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/css/menu.min.css', 'head');
window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/css/serach-input.min.css', 'head');
window.VILKA.addCss('/local/templates/ORTONICA_2023/assets/lib/fancybox.css', 'head');


window.VILKA.addScript(window.VILKA.template.path+'/events.js', 'head', null, false);
window.VILKA.addScript(window.VILKA.template.path+'/components/main-menu.js', 'head', function() {
    /* Вызов меню */
    window.VILKA.menuNavigation = new window.VILKA.menuNavigation();
}, false);


window.VILKA.addScript(window.VILKA.template.path+'/components/catalog-menu.js', 'head', function () {
    // глобальная переменная работы с меню каталога
    window.VILKA.catalogNavigation = new window.VILKA.catalogNavigation();
}, false);
window.VILKA.addScript(window.VILKA.template.path+'/functions/search-show.js', 'head', function () {
    /* Вызов глобальной функции появления поиска */
    window.VILKA.searchShow = new window.VILKA.searchShow();
}, false);
window.VILKA.addScript(window.VILKA.template.path+'/functions/filter-tab.js', 'head', function () {
    // Вызов глобальной переменой для фильтра табов
    window.VILKA.filterTab = new window.VILKA.filterTab();
}, false);
window.VILKA.addScript(window.VILKA.template.path+'/functions/event-on-space.js', 'head', function () {
    /* Вызов глобальной функции клика вне компонента на скрытие каталога */
    window.VILKA.clickOnSpaceCatalogMenu = new window.VILKA.clickOnSpaceCatalogMenu();

    /* Вызов глобальной функции клика вне компоненна на скрытие меню */
    window.VILKA.clickOnSpaceMainMenu = new window.VILKA.clickOnSpaceMainMenu();

    /* Вызов глобальной функции скрытия на ливе меню каталога */
    window.VILKA.mouseLeaveOnSpaceCatalogMenu = new window.VILKA.mouseLeaveOnSpaceCatalogMenu();
}, false);


// слайдеры
window.VILKA.addScript('/local/templates/ORTONICA_2023/assets/lib/swiper-bundle.min.js', 'head', function () {
	if ($(".vk-slider").length > 0) {
        const swiperVk = new Swiper('.vk-slider', {
            slidesPerView: 3,
            spaceBetween: 20,
            // centeredSlides: true,
            loop: true,

            breakpoints: {
                // when window width is >= 320px
                320: {
                    slidesPerView: 1,
                    navigation: {
                        nextEl: '.vk-slider__next',
                        prevEl: '.vk-slider__prev',
                    }
                },
                401: {
                    slidesPerView: 1.2,
                    navigation: {
                        nextEl: '.vk-slider__next',
                        prevEl: '.vk-slider__prev',
                    }
                },
                498: {
                    slidesPerView: 1.5,
                    navigation: {
                        nextEl: '.vk-slider__next',
                        prevEl: '.vk-slider__prev',
                    }
                },
                617: {
                    slidesPerView: 1.8,
                    navigation: {
                        nextEl: '.vk-slider__next',
                        prevEl: '.vk-slider__prev',
                    }
                },
                768: {
                    slidesPerView: 2.4,
                    navigation: {
                        nextEl: '.vk-slider__next',
                        prevEl: '.vk-slider__prev',
                    }
                },
                955: {
                    slidesPerView: 2.8,
                    navigation: {
                        nextEl: '.vk-slider__next',
                        prevEl: '.vk-slider__prev',
                    }
                },
                1170: {
                    slidesPerView: 3.2,
                    navigation: {
                        nextEl: '.vk-slider__next',
                        prevEl: '.vk-slider__prev',
                    },
                    loop: false,
                },
                1370: {
                    slidesPerView: 4.3,
                    navigation: {
                        nextEl: '.vk-slider__next',
                        prevEl: '.vk-slider__prev',
                    },
                    loop: false,
                }
            }
        });
    }

    if ($(".blog-slider").length > 0) {
        const swiperBlog = new Swiper('.blog-slider', {
            slidesPerView: 3,
            spaceBetween: 15,
            loop: true,

            breakpoints: {
                // when window width is >= 320px
                320: {
                    slidesPerView: 1.2,
                    navigation: {
                        enabled: false
                    }
                },
                768: {
                    slidesPerView: 2.3,
                    navigation: {
                        nextEl: '.blog-slider__next',
                        prevEl: '.blog-slider__prev',
                    }
                },
                1170: {
                    slidesPerView: 3.4,
                    navigation: {
                        nextEl: '.blog-slider__next',
                        prevEl: '.blog-slider__prev',
                    }
                }
            }
        });
    }

    if ($(".product-slider").length > 0) {
        const swiperProduct = new Swiper('.product-slider', {
            slidesPerView: 3,
            spaceBetween: 15,
            loop: false,

            breakpoints: {
                // when window width is >= 320px
                320: {
                    slidesPerView: 1.2,
                    navigation: {
                        enabled: false
                    }
                },
                320: {
                    slidesPerView: 1.5,
                    navigation: {
                        enabled: false
                    }
                },
                474: {
                    slidesPerView: 1.8,
                    navigation: {
                        enabled: false
                    }
                },
                577: {
                    slidesPerView: 2.1,
                    navigation: {
                        enabled: false
                    }
                },
                678: {
                    slidesPerView: 2.4,
                    navigation: {
                        enabled: false
                    }
                },
                768: {
                    slidesPerView: 3.1,
                    navigation: {
                        nextEl: '.product-slider__next',
                        prevEl: '.product-slider__prev',
                        enabled: false
                    }
                },
                895: {
                    slidesPerView: 3.4,
                    navigation: {
                        nextEl: '.product-slider__next',
                        prevEl: '.product-slider__prev',
                        enabled: false
                    }
                },
                1014: {
                    slidesPerView: 3.8,
                    navigation: {
                        nextEl: '.product-slider__next',
                        prevEl: '.product-slider__prev',
                        enabled: false
                    }
                },
                1170: {
                    slidesPerView: 4.4,
                    navigation: {
                        nextEl: '.product-slider__next',
                        prevEl: '.product-slider__prev',
                        enabled: false
                    }
                }
            }
        });
    }

    if ($(".reviews-slider").length > 0) {
        const swiperReviews = new Swiper('.reviews-slider', {
            slidesPerView: 3,
            spaceBetween: 5,
            loop: true,
            shortSwipes: false,
            breakpoints: {
                // when window width is >= 320px
                320: {
                    slidesPerView: 1.2,
                    navigation: {
                        enabled: false
                    }
                },
                768: {
                    slidesPerView: 2.3,
                    navigation: {
                        nextEl: '.reviews-slider__next',
                        prevEl: '.reviews-slider__prev',
                    }
                },
                1170: {
                    slidesPerView: 3.2,
                    navigation: {
                        nextEl: '.reviews-slider__next',
                        prevEl: '.reviews-slider__prev',
                    }
                }
            }
        });
    }

    if ($(".banner-slider").length > 0) {
        const swiperBanner = new Swiper('.banner-slider', {
            slidesPerView: 1,
            loop: true,
            spaceBetween: 5,
            autoplay: {
                delay: 5000,
            },
            pagination: {
                el: '.banner-pagination',
                type: 'bullets',
                clickable: true
            },

            breakpoints: {
                // when window width is >= 320px
                320: {
                    navigation: {
                        enabled: false
                    }
                },
                768: {
                    navigation: {
                        nextEl: '.banner-btn__next',
                        prevEl: '.banner-btn__prev',
                    }
                }
            }
        });
    }

	// init product slider
	if ($(".swiper_main").length > 0) {
		// console.log('init product slider')
		const swiper_thumbnail = new Swiper(".swiper_thumbnail", {
			// direction: 'vertical',
			slidesPerView: 'auto',
			spaceBetween: 10,
			centeredSlides: false,
			navigation: {
				prevEl: '.slider-thumbs-wrapper .arr-left',
				nextEl: '.slider-thumbs-wrapper .arr-right'
			},
			breakpoints: {
				// 0: {
				// 	direction: 'horizontal',
				// },
				// 1199: {
				// 	direction: 'vertical',
				// }
			}
		})
		const swiperMain = new Swiper('.swiper_main', {
			loop: true,
            autoHeight: true,
			thumbs: {
				swiper: swiper_thumbnail,
			},
			navigation: {
				prevEl: '.slider-thumbs-wrapper .arr-left',
				nextEl: '.slider-thumbs-wrapper .arr-right'
			},
            on: {
                init: function () {
                    // console.log('swiper initialized');
                    $('.product-img-wrapper.with-slider.loading').removeClass('loading')
                },
            },
		})
		window.changeColorProp = false


        swiperMain.on('slideChange', function (slide) {
			const src = $('.swiper_main .swiper-slide.slide_0 img').data('src')
			if(!window.changeColorProp ) {
				$('.swiper-slide.slide_0 img').attr('src', src)
			}
			window.changeColorProp = false
		})






		$('li.color-prop').click(function () {
			const color = $(this).data('color')
			changeColorSlide(color)
		})
		function changeColorSlide(color) {
            // console.log('changeColorSlide color -> ', color)
			let currentColorSrc = ''
			for(let key in window.productColorPhotos) {
				if(window.productColorPhotos[key]['color'] === color) {
					currentColorSrc = window.productColorPhotos[key]['SRC']
					break
				}
			}

			window.changeColorProp = true
			$('.swiper-slide.slide_0 img').attr('src', currentColorSrc)
            swiperMain.slideTo(1)
		}
        window.changePropSlide = function() {
            if(!swiperMain) return;
            setTimeout(()=>{
                $('.swiper-slide.slide_0 img').attr('src', window.actualProduct.PREVIEW_PICTURE.SRC)
                swiperMain.slideTo(1)
            },10)

        }
		// $('.slider-thumbs-wrapper .arr-left').click(()=>swiper)
	}

	// video slider
	// console.log("$('.vi-video-slider-wrapper .swiper').length", $('.vi-video-slider-wrapper .swiper').length)
	if($('.vi-video-slider-wrapper .swiper').length > 0) {

		const videoSlider = new Swiper('.vi-video-slider-wrapper .swiper', {
			slidesPerView: 1,
			spaceBetween: 20,
			navigation: {
				nextEl: '.vi-video-slider-wrapper .vi-next',
				prevEl: '.vi-video-slider-wrapper .vi-prev',
			},
			breakpoints: {
				768: {
					slidesPerView: 2,
					spaceBetween: 40,
				}
			}
		});
	}


}, false);

// подписка на рассылку, заказать звонок
window.VILKA.addScript('/local/templates/ORTONICA_2023/assets/lib/fancybox.umd.js', 'head', function () {

	// подписка на рассылку
	$('#subscribe-form').submit(function (e) {
		e.preventDefault()
		// console.log('subscribe')
		const EMAIL = $(this).find('.subscribe__form-email').val()
		const form = $(this)
		$.ajax({
			url: '/local/forms/mailing.php',
			method: 'post',
			data: {EMAIL, submit: 'Y', AJAX: 'Y', calc: '0.12841649065312755', RESULT_OK: 'Y'},
			success: function(data){
				data = JSON.parse(data)
				if(data.STATUS === 'ok') {
					$(form).trigger("reset");
				}
				Fancybox.show([
					{
						src: `<p>${data.MESSAGE}</p>`,
						type: "html",
					},
				]);
			}
		});
	})

// заказать звонок
    $(".callback-forms-ort #FORM_AGREE").change(function () {
        let form = $(this).closest('.callback-forms-ort');
        if(!$(this).is(':checked')) {
            form.find('.button[type="submit"]').addClass('disabled');
        } else {
            form.find('.button[type="submit"]').removeClass('disabled');
        }
    });

    $('.callback-forms-ort').each(function() {
        let cbForm = $(this);
        let cbFormName = cbForm.find('input[name="NAME"]');
        let cbFormPhone = cbForm.find('input[name="PHONE"]');
        let cbFormButton = cbForm.find('.call-button');
        // let cbFormButton = cbForm.find('button');

        cbFormName.add(cbFormPhone).keyup(function() {
            cbFormAllowed(cbForm, cbFormName, cbFormPhone, cbFormButton);
        });


        cbFormAllowed(cbForm, cbFormName, cbFormPhone, cbFormButton);

        cbForm.submit(function (e) {
            e.preventDefault();

            const data = {
                NAME: cbForm.find('input[name="NAME"]').val(),
                PHONE: cbFormPhone.val(),
                PAGE_URL: window.location.href,
                hash: 'hjfdks76sDgas@hjk',
                ajax_action: 'callback'
            };

            // if (new URLSearchParams(window.location.search).get('zz_test2') === 'y') {

                if( cbForm.hasClass('cbfoe') ){
                    data.cbfoe = 'cbfoe';
                }


            //     console.log('data', data);
            //
            // console.log('stopped testing');
            // return false;
            // }



            if (!countCbFormPhoneDigits(cbFormPhone.val())) {
                console.log('Не заполнен телефон');
                return false;
            }

            console.log('length:', cbForm.find('input[name="PHONE"]').val().length);
            console.log('send form data:', data);

            $.ajax({
                url: '/local/ajax/controller.php',
                method: 'post',
                data,
                success: function(data) {
                    if(data === 'OK') {
                        cbForm.trigger("reset");
                        Fancybox.show([
                            {
                                src: `<p>Спасибо, Ваша заявка отправлена</p>`,
                                type: "html",
                            },
                        ]);
                    } else {
                        console.log(data);
                        Fancybox.show([
                            {
                                src: `<p>Сервер временно не отвечает, попробуйте повторить попытку позже</p>`,
                                type: "html",
                            },
                        ]);
                    }
                }
            });
        });
    });



    function countCbFormPhoneDigits(phoneValue) {
        var digits = phoneValue.replace(/\D/g, ''); // Удаляем все нецифровые символы, оставляем только цифры
        console.log('cbForm digits', digits);
        console.log('cbForm digits.length', digits.length);
        return digits.length === 11;
    }

    function cbFormAllowed(cbForm, cbFormName, cbFormPhone, cbFormButton) {
        if (
            cbFormName.val().length < 3 ||
            !countCbFormPhoneDigits(cbFormPhone.val())
        ) {
            // console.log('cbFormButton disabled');
            // console.log('cbFormButton', cbFormButton);
            // console.log('cbFormName.val().length', cbFormName.val().length);
            // console.log('countCbFormPhoneDigits(cbFormPhone.val())', countCbFormPhoneDigits(cbFormPhone.val()));
            cbFormButton.attr('disabled', 'disabled');
        } else {
            // console.log('cbFormButton allowed');
            cbFormButton.removeAttr('disabled');
        }
    }


}, false);


window.VILKA.addScript('/local/templates/ORTONICA_2023/assets/lib/inputmask.js', 'head', function () {
	// console.log($('input[type="tel"], .phone-input'))
	$('input[type="tel"], .phone-input').inputmask({
		"mask": "+7 (999) 999-99-99",
	});

}, false);


function refreshRegionPhoneTooltip() {
	const target = document.getElementById('region-phone-tippy')
	const currentRegion = $('.header__contact .region .reg_name')
	const valid = $(currentRegion).length && $(currentRegion).text() !== ''
	if(!valid) return;

	const regionName = $(currentRegion).text()
	if(!window.citiesPhones.hasOwnProperty(regionName)) return;

	const tel = window.citiesPhones[regionName]
	$(target).addClass('with-arrow')

	let content = `<a class="tooltip-phone-item" href="tel:+7${tel}"><b>${tel}</b>${regionName}</a>`
	// console.log('left',$(target).offset().left, 'top',$(target).offset().top)
	const instance = tippy(target, {
		allowHTML: true,
		content,
		interactive: true,
		arrow: false,
		theme: 'white',
		placement: 'bottom-end',
		maxWidth: 220,
		offset: [0, 0],
	});

}
window.VILKA.addScript('/local/templates/ORTONICA_2023/assets/lib/popper.min.js', 'head',  false);
window.VILKA.addScript('/local/templates/ORTONICA_2023/assets/lib/tippy-bundle.umd.js', 'head',  function () {

	// обновляем региональные телефоны
	refreshRegionPhoneTooltip()
	$('.region .region_sp a').click(refreshRegionPhoneTooltip)


	if ($('[data-tippy-content]').length) {
		tippy('[data-tippy-content]',{
			allowHTML: true,
			theme: 'white',
			arrow: false,
		});
	}

});
if(window.productHas3D) {
	window.VILKA.addScript('/local/templates/ORTONICA_2023/assets/lib/threesixty.js', 'head',  ()=>{
		init3d()
		function init3d(){
			const threesixty = new ThreeSixty(document.querySelector('.threesixty_images'), {
				//count: <?//=$files_count?>//,
				speed: 60,
				image: window.vfiles,
				prev: document.getElementById('threesixty-prev'),
				next: document.getElementById('threesixty-next')
			});
			threesixty.play();
		}
	});
}
	// console.log('window.productHas3D = ', window.productHas3D)ы





},20)


// обновить избранное
window.updateWishList = function (cb = function(){}) {

    fetch(`/local/ajax/controller.php?hash=hjfdks76sDgas@hjk&ajax_action=getWishlist`)
        .then((res)=>res.json())
        .then(r=>{
            window.productInWishList = []
            // обновить шапку
            const headerCnt = $('.header-product__wishlist .header-product__count')
            if(r.length) {
                $(headerCnt).addClass('--active').text(r.length)
                window.productInWishList = r
            }
            cb()
            addWishActiveClassForProductCard()
            // console.log('updateWishList', r)
        })
}
window.updateWishList()

function addWishActiveClassForProductCard() {
    $('.product-item__actions .wish-btn.active').removeClass('active')
    $(window.productInWishList).each((i,id)=>{
        $(`.product-item__actions .wish-btn[data-item="${id}"]`).addClass('active')
    })
}


// call form emul
$(document).ready(function (){

/* Подстройка фона формы под градиент страницы */
    function hexToRgb(hex) {
        const bigint = parseInt(hex.slice(1), 16);
        const r = (bigint >> 16) & 255;
        const g = (bigint >> 8) & 255;
        const b = bigint & 255;
        return { r, g, b };
    }

    function blendColors(color1, color2, ratio) {
        const c1 = hexToRgb(color1);
        const c2 = hexToRgb(color2);

        const r = Math.round(c1.r + (c2.r - c1.r) * ratio);
        const g = Math.round(c1.g + (c2.g - c1.g) * ratio);
        const b = Math.round(c1.b + (c2.b - c1.b) * ratio);

        return `rgb(${r}, ${g}, ${b})`;
    }

    function getGradientColor(yPos) {
        const gradientStops = [
            { color: "#ffffff", position: 0 },    // Начало белого
            { color: "#ffffff", position: 300 },  // Окончание белого
            { color: "#f4f4f4", position: 960 },  // Начало серого
            { color: "#f4f4f4", position: 0.4 * document.documentElement.scrollHeight }, // Окончание серого (процент от высоты страницы)
            { color: "#ffffff", position: document.documentElement.scrollHeight } // Финальный белый
        ];

        for (let i = 0; i < gradientStops.length - 1; i++) {
            const start = gradientStops[i];
            const end = gradientStops[i + 1];

            if (yPos >= start.position && yPos <= end.position) {
                const ratio = (yPos - start.position) / (end.position - start.position);
                return blendColors(start.color, end.color, ratio);
            }
        }

        return gradientStops[gradientStops.length - 1].color;
    }

    function updateBlockBackground() {
        const block = document.querySelector('.cb-emul-wr');
        const blockPosition = block.getBoundingClientRect().bottom + window.scrollY;
        const backgroundColor = getGradientColor(blockPosition);
        block.style.backgroundColor = backgroundColor;

        const blockInner = document.querySelector('.call-order-form');
        blockInner.style.backgroundColor = backgroundColor;
    }

    // window.addEventListener('scroll', updateBlockBackground);
    // window.addEventListener('resize', updateBlockBackground);
    // window.addEventListener('DOMContentLoaded', updateBlockBackground);

    /* Подстройка фона формы под градиент страницы почти END */

    $('.call-form-button, .cof-cross').click(function (){

        // updateBlockBackground(); // Подстройка фона формы под градиент страницы

        $('.cb-emul-wr').toggleClass('cof-open');
        $('.call-order-form').toggleClass('cof-open');
        $('.call-form-button').toggleClass('cof-open');

        return false;
    });
});
// call form emul end






