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 = {};

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() 
{
    var $document = $(document);
    var selector = '[data-rangeslider]';
    var $element = $(selector);

    // 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)
	{
		$('html, body').animate({
			scrollTop: $("#calc").offset().top - 100
		}, 200);
	});

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