var complectPrices = new Array();

function selectorChanged(selector) {
	
	var selectorID     = selector.id;
	var selectorVALUES = $('#' + selectorID).selectedValues();
	var selectorVALUE  = selectorVALUES[0];
	
	switch (selectorID) {
		
		case 'modelSelector':
			updateComplectations(selectorVALUE);
			updateBanks(selectorVALUE);
		break;
		
		case 'bankSelector':
			updateLoan(selectorVALUE);
		break;
		
		case 'complectSelector':
			updatePrice(selectorVALUE);
			updateInitial();
		break;
		
		case 'initialSelector':
			updateInitial();
		break;
		
		default:
		break;
		
	}
	
}

function updateComplectations(modelID) {	
	$.getJSON("/ajax/loan/mmf/",{what : "complectations", model_id : modelID}, function(data) { fillComplectations(data); });
}

function updateBanks(modelID) {	
	$.getJSON("/ajax/loan/mmf/",{what : "banks", model_id : modelID}, function(data) { fillBanks(data); });
}

function updateLoan(bankID) {
	$.getJSON("/ajax/loan/mmf/",{what : "bank", bank_id : bankID}, function(data) { fillLoanData(data); });
}

function updatePrice(complectID) {
	if (complectPrices.length) {
		$("#priceContainer").text("Цена этой комплектации: " + number_format( complectPrices[complectID], 0, ".", " " ) + ' руб.');
	}
}

function updateInitial() {
	var selectedComplect = $("#complectSelector").selectedValues();
	var selectedInitial  = $("#initialSelector").selectedValues();
	
	if (selectedComplect > 0  && selectedInitial > 0) {
		var initial = Math.round(complectPrices[selectedComplect] * selectedInitial / 100);
		$("#initialContainer").html("Размер начального взноса: " + number_format(initial, 0, ".", " " ) + " руб.");
	}
	else {
		$("#initialContainer").html("&nbsp;");
	}
	
}

function fillComplectations(data) {
	complectPrices = new Array();
	
	var optionsArray = new Array();
	optionsArray[0] = "--- Выберите комплектацию ---";
	for(var i = 0; i < data.length; i++) {
		optionsArray[data[i]["id"]] = data[i]["name"];	
		complectPrices[data[i]["id"]] = data[i]["price"];	
	}	
	$("#complectSelector").removeOption(/./);
	$("#complectSelector").addOption(optionsArray,false);
	$("#complectSelector").removeAttr("disabled");
	
	$("#priceContainer").html("&nbsp;");	
	$("#resultContainer").fadeOut("normal");
}

function fillBanks(data) {
	var optionsArray = new Array();
	optionsArray[0] = "--- Выберите банк ---";
	for(var i = 0; i < data.length; i++) {
		optionsArray[data[i]["id"]] = data[i]["name"];	
	}	
	$("#bankSelector").removeOption(/./);
	$("#bankSelector").addOption(optionsArray,false);
	$("#bankSelector").removeAttr("disabled");
	
	$("#periodSelector").removeOption(/./);
	$("#initialSelector").removeOption(/./);
}

function fillLoanData(data) {
	var optionsArray = new Array();
	optionsArray[0] = "--- Укажите срок кредита ---";
	for(var i = 0; i < data["periods"].length; i++) {
		optionsArray[data["periods"][i]] = data["periods"][i] + ' мес.';	
	}
	$("#periodSelector").removeOption(/./);
	$("#periodSelector").addOption(optionsArray,false);
	$("#periodSelector").removeAttr("disabled");
	
				
	var optionsArray = new Array();
	optionsArray[0] = "--- Укажите размер начального взноса ---";
	for(var i = 0; i < data["initials"].length; i++) {
		optionsArray[data["initials"][i]] = data["initials"][i] + ' %';	
	}
	$("#initialSelector").removeOption(/./);	
	$("#initialSelector").addOption(optionsArray,false);
	$("#initialSelector").removeAttr("disabled");
	
	$("#resultContainer").fadeOut("normal");
}

function calculate() {
	var complect = $("#complectSelector").selectedValues();
	var initial  = $("#initialSelector").selectedValues();
	var period   = $("#periodSelector").selectedValues();
	var bank     = $("#bankSelector").selectedValues();
	
	if (complect > 0 && initial > 0 && period > 0 && bank > 0) {
		$.getJSON("/ajax/loan/mmf/",{what : "calc", bank_id : bank, complect_id : complect, initial : initial, period : period}, function(data) { showResults(data); });
	}
	else {
		alert("Вы указали не все параметры");
	}
	
}

function showResults(data) {
	
	$("#resultName").html(data['car']);
	$("#resultPrice").html(number_format(data['price'],0,"."," "));
	$("#resultInitialPercent").html(data['initialPercent']);
	$("#resultInitialPrice").html(number_format(data['initialPrice'],0,"."," "));
	$("#resultLoanSum").html(number_format(data['loan'],0,"."," "));
	$("#resultPeriod").html(data['period']);
	$("#resultRate").html(data['rate']);
	$("#resultMonthPayment").html(number_format(data['monthPayment'],0,"."," "));
	$("#resultTotalPayment").html(number_format(data['totalSum'],0,"."," "));
	
	$("#resultContainer").fadeIn("normal");
}