var calculation = { car_price: 0, CAR_PRICE_MIN: 0, CAR_PRICE_MAX: 0, initial_payment: 0, lease_period: 0, monthly_payment: 0, redemption_payment: 0, tax_savings: 0, vat_reimbursement: 0 };
var calculation_default = {};
var current_image = 0;
var max_images = 0;
var photos = {};
var fullscreen = false;

let touchstartX = 0;
let touchstartY = 0;
let touchendX = 0;
let touchendY = 0;

console.log({ calculation });

function calculator(props)
{
	for(let i in calculation)
	{
		calculation[i] = parseInt(props[i], 10);
	}

	$("#FORM_FIELD_PRICE").val(calculation.car_price);
	$("#FORM_FIELD_PREPAID").val(calculation.initial_payment);
	$("#FORM_FIELD_TERM").val(calculation.lease_period);
	$("#FORM_FIELD_REDEMPTION").val(calculation.redemption_payment);

	calculation_default = { ...calculation };
}

function calculate(param, value)
{
	if(param !== undefined)
	{
		calculation[param] = value;
	}

	$("#FORM_FIELD_PRICE").val(calculation.car_price);
	$("#FORM_FIELD_PREPAID").val(calculation.initial_payment);
	$("#FORM_FIELD_TERM").val(calculation.lease_period);
	$("#FORM_FIELD_REDEMPTION").val(calculation.redemption_payment);

	$.post("/api/calculation/", 
	{
		car_price: calculation.car_price, 
		initial_payment: calculation.initial_payment, 
		lease_period: calculation.lease_period, 
		redemption_payment: calculation.redemption_payment, 	
	}, function(response)
	{
		for(let i in response) { calculation[i] = parseInt(response[i], 10); }

		$("#calculator_car_price_value").text(calculation['car_price'].toLocaleString()+" ₽");
		$("#calculator_monthly_payment_value").text(calculation['monthly_payment'].toLocaleString());
		$("#calculator_tax_savings_value").text(calculation['tax_savings'].toLocaleString());
		$("#calculator_vat_reimbursement_value").text(calculation['vat_reimbursement'].toLocaleString());
	}, "json");
}

$("#calculation_reset").on("click", function()
{
	console.log("calculation_reset");
	console.log(calculation_default);

	calculation = { ...calculation_default };

	var $input_range_car_price = $(`#calculation_car_price`);
	$input_range_car_price.val(calculation['car_price']).change();
	$("#calculator_car_price_value").text(calculation['car_price'].toLocaleString()+" ₽");

	var $input_range_car_price = $(`#calculation_initial_payment`);
	$input_range_car_price.val(calculation['initial_payment']).change();

	var $input_range_car_price = $(`#calculation_lease_period`);
	$input_range_car_price.val(calculation['lease_period']).change();

	var $input_range_car_price = $(`#calculation_redemption_payment`);
	$input_range_car_price.val(calculation['redemption_payment']).change();
});

$(".car_details_menu").on("click", function(e)
{
	e.preventDefault();
	$(".car_details_menu").removeClass("active");
	$(this).addClass("active");

	$(".info_block").removeClass("active");
	$("#info_block_"+$(this).data("id")).addClass("active");
});

$(".touch_header").on("click", function(e)
{
	e.preventDefault();
	$(this).toggleClass("opened");
	$(this).parent().toggleClass("active");
});

function calculator_car_price_save()
{
	var v = parseInt($("#calculator_car_price_input").val(), 10);
	console.log(v, calculation['CAR_PRICE_MIN'], calculation['CAR_PRICE_MAX']);
	if(v >= calculation['CAR_PRICE_MIN'] && v <= calculation['CAR_PRICE_MAX'])
	{
		var $input_range_car_price = $(`#calculation_car_price`);
		$input_range_car_price.val(v).change();
		calculate('car_price', v);

		$("#calculator_car_price_value").show();
		$("#calculator_car_price_editor").hide();
	}
	else
	{
		$("#calculator_car_price_value").show();
		$("#calculator_car_price_editor").hide();
	}
}

function fullpage_prev()
{
	//fullscreen && 
	if(current_image > 0)
	{
		$(".photo_480_"+current_image).animate({ opacity: 0.0, }, 500);
		current_image--;
		$(".photo_480_"+current_image).animate({ opacity: 1.0, }, 500);

		if(current_image === 0)
		{
			$("#overlay_left").css("display", "none");
		}
		$("#overlay_right").css("display", "flex");
		$("#overlay_image").attr("src", photos['1080'][current_image]);
	}
}

function fullpage_next()
{
//	console.log("fullpage_next()");
	if(current_image < max_images)
	{
		$(".photo_480_"+current_image).animate({ opacity: 0.0, }, 500);
		current_image++;
		$(".photo_480_"+current_image).animate({ opacity: 1.0, }, 500);

		if(current_image === max_images)
		{
			$("#overlay_right").css("display", "none");
		}
		$("#overlay_left").css("display", "flex");
		$("#overlay_image").attr("src", photos['1080'][current_image]);
	}
}

$(function() 
{
    var $document = $(document);
    var selector = '[data-rangeslider]';
    var $element = $(selector);

	photos = JSON.parse($("#photos").val());
	max_images = photos['1080'].length - 1;

    // For ie8 support
    var textContent = ('textContent' in document) ? 'textContent' : 'innerText';

    // Example functionality to demonstrate a value feedback
    function valueOutput(element) 
	{
        var value = element.value;
        var output = element.parentNode.getElementsByTagName('output')[0] || element.parentNode.parentNode.getElementsByTagName('output')[0];
        output[textContent] = value;
    }

    $document.on('input', 'input[type="range"], ' + selector, function(e) 
	{
        valueOutput(e.target);
    });

    $document.on('click', '#js-example-disabled button[data-behaviour="toggle"]', function(e) 
	{
        var $inputRange = $(selector, e.target.parentNode);

        if ($inputRange[0].disabled) {
            $inputRange.prop("disabled", false);
        }
        else {
            $inputRange.prop("disabled", true);
        }
        $inputRange.rangeslider('update');
    });

    $document.on('click', '#js-example-change-value button', function(e) {
        var $inputRange = $(selector, e.target.parentNode);
        var value = $('input[type="number"]', e.target.parentNode)[0].value;

        $inputRange.val(value).change();
    });

	$document.on('click', '#js-example-change-attributes button', function(e) 
	{
		var $inputRange = $(selector, e.target.parentNode);
		var attributes = {
			min: $('input[name="min"]', e.target.parentNode)[0].value,
			max: $('input[name="max"]', e.target.parentNode)[0].value,
			step: $('input[name="step"]', e.target.parentNode)[0].value
		};

		$inputRange.attr(attributes);
		$inputRange.rangeslider('update', true);
	});

	$document
	.on('click', '#js-example-destroy button[data-behaviour="destroy"]', function(e) {
		$(selector, e.target.parentNode).rangeslider('destroy');
	})
	.on('click', '#js-example-destroy button[data-behaviour="initialize"]', function(e) {
		$(selector, e.target.parentNode).rangeslider({ polyfill: false });
	});

	$document.on('click', '#js-example-hidden button[data-behaviour="toggle"]', function(e) {
		var $container = $(e.target.previousElementSibling);
		$container.toggle();
	});

	$element.rangeslider({
		polyfill: false,
		onInit: function() 
		{
			valueOutput(this.$element[0]);
		},
		onSlide: function(position, value) 
		{
			if(this.$element.attr('data-slider-name') === "car_price")
			{
				$("#calculator_car_price_value").text(value.toLocaleString()+" ₽");
			}
		},
		onSlideEnd: function(position, value) 
		{
			calculate(this.$element.attr('data-slider-name'), value);
		}
	});

	$("#calculator_car_price_value").on("click", function()
	{
		$("#calculator_car_price_input").val(parseInt(calculation.car_price, 10));
		$("#calculator_car_price_value").hide();
		$("#calculator_car_price_editor").show();
	});

	$("#calculator_car_price_save").on("click", function()
	{
		calculator_car_price_save();
	});

	$("#calculator_car_price_input").on("keydown", function(event)
	{
		if(event.keyCode === 13)
		{
			event.preventDefault();
			calculator_car_price_save();
		}
	});

	$("#to_calculator_button").on("click", function(event)
	{
		leasing_form_used_buy = false;
		$(".order_title").text("Оформить автомобиль с пробегом в лизинг");
		$("#form_leasing_used_email").attr("href", "mailto:buy@evoleasing.ru").text("buy@evoleasing.ru");
		$("#FORM_FIELD_IS_IZT").val("");

		$('html, body').animate({
			scrollTop: $("#calc").offset().top - 100
		}, 200);
	});

	$("#to_form_button").on("click", function(event)
	{
		leasing_form_used_buy = true;
		$(".order_title").text("Купить автомобиль с пробегом");
		$("#form_leasing_used_email").attr("href", "mailto:izt@evoleasing.ru").text("izt@evoleasing.ru");
		$("#FORM_FIELD_IS_IZT").val("Да");

		$('html, body').animate({
			scrollTop: $("#order").offset().top - 100
		}, 200);
	});

	$("#to_used_catalog_button").on("click", function(event)
	{
		document.location.href = "/used/";
	});

	var scrollContainer = $('.scroll_images');
	var imageWidth = $('.thumb').outerWidth(true);
	var isScrolling = false; // Флаг для определения активного скролла

	$('.scroll_images_button').on('click', function() {
		if (!isScrolling) {
		isScrolling = true;

		var direction = $(this).hasClass('scroll_images_button_left') ? 'left' : 'right';
		var scrollOffset = direction === 'left' ? -imageWidth : imageWidth;

		scrollContainer.animate({scrollLeft: scrollContainer.scrollLeft() + scrollOffset}, 'fast', function() {
			isScrolling = false;
		});
		}
	});

	$(".thumb").eq(0).addClass("active");
	$(".thumb").on("click", function(event)
	{
		var new_image = $(this).data("index");
		if(current_image !== new_image)
		{
			$(".photo_480_"+current_image).animate({ opacity: 0.0, }, 500);
			$(".photo_480_"+new_image).animate({ opacity: 1.0, }, 500);
			$(this).addClass("active").siblings().removeClass("active");
			current_image = new_image;
		}
	});

	$(".photo_480").on("click", function(event)
	{
		var url = photos['1080'][current_image];

		$("#overlay_image").attr("src", url);
		if(current_image > 0)
		{
			$("#overlay_left").css("display", "flex");
		}

		if(current_image < max_images)
		{
			$("#overlay_right").css("display", "flex");			
		}

		$("body").css("overflow", "hidden");
		$("#fullscreen").css("display", "flex");
		fullscreen = true;

		touchstartX = 0;
		touchstartY = 0;
		touchendX = 0;
		touchendY = 0;
		console.log("INIT");
	});

	$("#overlay_close").on("click", function(event)
	{
		$("#fullscreen").css("display", "none");
		$("#overlay_left").css("display", "none");
		$("#overlay_right").css("display", "none");
		$("body").css("overflow", "inherit");
		fullscreen = false;
	});

	$("#overlay_left").on("click", function(event)
	{
		fullpage_prev();
	});

	$("#overlay_right").on("click", function(event)
	{
		fullpage_next();
	});

	$("#pdf_download").on("click", function(event)
	{
		var contract = $("#contract").val();

		$.ajax({
			url: '/api/catalog/pdf/',
			method: 'GET',
			data: {
				contract
			}, 
			xhrFields: { responseType: 'arraybuffer'}
		}).then(function (data) 
		{
			var blob = new Blob([data], { type:"application/pdf" });
			var link = document.createElement('a');
			link.href = window.URL.createObjectURL(blob);
			link.download = "evoleasing_offer_"+contract+".pdf";
			link.click();
		});
	});

	$("body").keydown(function(e) 
	{
		if(e.keyCode == 37)
		{
			fullpage_prev();
		}
		else if(e.keyCode == 39)
		{
			fullpage_next();
		}
	});

	$('.scroll_images').on("scroll", function(event)
	{
		var scrollPanelWidth = $('.scroll_images').outerWidth(true);

		if(event.target.scrollLeft > 0)
		{
			$(".scroll_images_button_left").css("display", "block");
		}
		else
		{
			$(".scroll_images_button_left").css("display", "none");
		}

		if((event.target.scrollLeft + scrollPanelWidth) >= event.target.scrollWidth)
		{
			$(".scroll_images_button_right").css("display", "none");
		}
		else
		{
			$(".scroll_images_button_right").css("display", "block");
		}
	});
});

const gestureZone = document.getElementById('photo_480_wrapper');
const gestureZoneFullImage = document.getElementById('overlay_image');

gestureZone.addEventListener('touchstart', function(event) {
	touchstartX = event.changedTouches[0].screenX;
	touchstartY = event.changedTouches[0].screenY;
}, false);

gestureZone.addEventListener('touchend', function(event) {
	touchendX = event.changedTouches[0].screenX;
	touchendY = event.changedTouches[0].screenY;
	handleGesture();
}, false); 

gestureZoneFullImage.addEventListener('touchstart', function(event) {
	touchstartX = event.changedTouches[0].screenX;
	touchstartY = event.changedTouches[0].screenY;
}, false);

gestureZoneFullImage.addEventListener('touchend', function(event) {
	touchendX = event.changedTouches[0].screenX;
	touchendY = event.changedTouches[0].screenY;
	handleGesture();
}, false);

function handleGesture() 
{
    if (touchendX < touchstartX) 
	{
		fullpage_next();
    }
    
	if (touchendX > touchstartX) 
	{
		fullpage_prev();
	}
}