function updatePrice(id) {
	if(id != 0) {
		$('input_field_car_price').value = cars[id].price;
		$('input_field_code_model').value = cars[id].code.model;
		$('input_field_code_body').value = cars[id].code.body;
		$('input_field_code_version').value = cars[id].code.version;
		$('input_field_code_motor').value = cars[id].code.motor;
		if(['1PZ9','1PMP'].contains(cars[id].code.model) == true || (cars[id].code.model == '1PD2' && cars[id].code.body == 'CO'))
			$('currency').innerHTML = '&euro;';
		else
			$('currency').innerHTML = 'TL';
	}
	else {
		$('input_field_car_price').value = '';
		$('input_field_code_model').value = '';
	}
	updateFinalPrice();
}

function updateFinalPrice() {
	choosedCar = $('input_select_model').value;

	if(choosedCar != 0) {
		var price = cars[$('input_select_model').value].price_brut.toInt();
		var apport = $('input_field_apport').value.trim().toInt();
		if(!isNaN(apport) && apport!=0) {
			var result = price-apport;
			if(result>0 && (price >= apport)) {
				$('input_field_car_pricecalculatedbrut').value = result;
				$('input_field_car_pricecalculated').value = number_format(result, 0, ',', '.');
			}
			else {
				$('input_field_car_pricecalculatedbrut').value = '';
				$('input_field_car_pricecalculated').value = '';
			}
		}
		else {
			$('input_field_apport').value = '';
			$('input_field_car_pricecalculatedbrut').value = '';
			$('input_field_car_pricecalculated').value = '';
		}
	}
	else {
		$('input_field_car_pricecalculatedbrut').value = '';
		$('input_field_car_pricecalculated').value = '';
	}
	buttonStatus();
}

function buttonStatus() {
	checked = false;
	$$('.tr_finance_radios input').each(function(radioInput) {
		if(radioInput.checked == true && !isNaN($('input_field_car_pricecalculatedbrut').value.toInt())) {
			$('compareButton').getParent().addClass('activated');
			checked = true;
		}
	});
	if(checked==false) {
		$('compareButton').getParent().removeClass('activated');
	}
}

	function fillResults(data,xml) {
		// Get XML root
		var rsp_root = xml.getElementsByTagName('root').item(0);
		// Get XML general tag
		var rsp_general = rsp_root.getElementsByTagName('generalrate').item(0);
		// Get XML months tags
		var rsp_months = rsp_root.getElementsByTagName('monthrates').item(0).getElementsByTagName('rate');
		// Get XML car tag
		var rsp_car = rsp_root.getElementsByTagName('car').item(0);

		// GENERAL RATE
		var GENERAL_RATE = 1+rsp_general.getAttribute('bsmv').toFloat();
		if(rsp_root.getAttribute('type') == 'VU')
			GENERAL_RATE = (GENERAL_RATE.toFloat()+rsp_general.getAttribute('kkdf_vu').toFloat()).round(2);
		else
			GENERAL_RATE = GENERAL_RATE.toFloat()+rsp_general.getAttribute('kkdf').toFloat().round(2);

		// BASE PRICE & FINAL PRICE (calculated from base price, participation and general rate)
		var BASEPRICE = $('input_field_car_pricecalculatedbrut').value;
		var FINALPRICE = BASEPRICE-(rsp_car.getAttribute('participation').toFloat()/GENERAL_RATE);

		// Reset Table content
		//$('tr_finance_results_tbody').innerHTML = '';
		$$('#tr_finance_results_tbody tr').each(function(tr) {
			tr.dispose();
		});

		// Browse the months rates & Filling the table
		rate = 0;
		for (var i = 0; i < rsp_months.length; i++)
		{
			rate = rsp_months.item(i);
			// Get the month rate, the month number and calculate the first VPM
			if(rate.firstChild != undefined && rate.firstChild != null)
				var rsp_month_rate = rate.firstChild.nodeValue.toFloat();
			else
				var rsp_month_rate = 0;
			if(rsp_month_rate != 0)
			{
				var rsp_month = rate.getAttribute('month');
				var VPM1 = VPM(rsp_month_rate,rsp_month,FINALPRICE);

				// Calculed Rate
				var CALCULATED_RATE = taux(rsp_month,VPM1,$('input_field_car_pricecalculatedbrut').value.toFloat())*100;
				if(CALCULATED_RATE<=0.1) {
					CALCULATED_RATE = 0.00001;
				}
				else if(rsp_car.getAttribute('participation').toFloat() != 0) {
					CALCULATED_RATE = Math.ceil(CALCULATED_RATE*100)/100;
				}

				FINAL_RATE = CALCULATED_RATE*GENERAL_RATE/100;

				var VPM2 = VPM(FINAL_RATE,rsp_month,BASEPRICE);
				if(VPM2!=null) {
					var tr = new Element('tr');
					if(i%2!=0)
						tr.addClass('alternate');

						var tds = {};
						tds.month = new Element('td');
							tds.month.innerHTML = rate.getAttribute('month');
						tds.taux = new Element('td');
							tds.taux.innerHTML = number_format(CALCULATED_RATE, 2, ',', '.');
						tds.price = new Element('td');
							tds.price.innerHTML = number_format(VPM2.round(2), 2, ',', '.');
						$each(tds, function(td) {
							tr.appendChild(td);
						});
						$('tr_finance_results_tbody').appendChild(tr);
				}
			}

			/*debug*/
			/*
			console.error(rsp_month);
			console.log('GENERAL_RATE: '+GENERAL_RATE);
			console.log('BASEPRICE: '+BASEPRICE);
			console.log('FINALPRICE: '+FINALPRICE);
			console.log('rate: '+rsp_month);
			console.log('rsp_month_rate: '+rsp_month_rate);
			console.log('VPM1: '+VPM1);
			console.log('CALCULATED_RATE: '+CALCULATED_RATE);
			console.log('FINAL_RATE: '+FINAL_RATE);
			console.log('VPM2: '+VPM2);
			*/
		}
	}


/* DOMREADY */
window.addEvent('domready', function()
{
	$('input_field_apport').addEvent('keyup', updateFinalPrice);

	$$('.tr_finance_radios input').each(function(radioInput) {
		radioInput.addEvent('click', function() {
			if(!isNaN($('input_field_car_pricecalculatedbrut').value.toInt())) {
				$('compareButton').getParent().addClass('activated');
			}
		});
	});

	$('compareButton').addEvent('click', function() {
		if($('compareButton').getParent().hasClass('activated')) {
			$('financeForm').set('send', {onComplete:fillResults});
			$('financeForm').send();
		}
	});
});


/* Made by Mathias Bynens <http://mathiasbynens.be/> */
function number_format(a, b, c, d) {
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 e = a + '';
 f = e.split('.');
 if (!f[0]) {
  f[0] = '0';
 }
 if (!f[1]) {
  f[1] = '';
 }
 if (f[1].length < b) {
  g = f[1];
  for (i=f[1].length + 1; i <= b; i++) {
   g += '0';
  }
  f[1] = g;
 }
 if(d != '' && f[0].length > 3) {
  h = f[0];
  f[0] = '';
  for(j = 3; j < h.length; j+=3) {
   i = h.slice(h.length - j, h.length - j + 3);
   f[0] = d + i +  f[0] + '';
  }
  j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
  f[0] = j + f[0];
 }
 c = (b <= 0) ? '' : c;
 return f[0] + c + f[1];
}

/* Calc VPM & TAUX */
var iter=0;
function test(n,M,C) {
	var myText="Resultats:<br>";
	myDiv=document.getElementById('test');

	T=taux(n,M,C);

	myText+="<B>Forumlue Taux(): "+Math.round(T*10000)/100+"%</B><BR>";
	T2=puissance(1+T,12)-1;
	myText+="<B>Taux Final: "+Math.round(T2*10000)/100+"%</B>";
	myDiv.innerHTML=myText;
}

function taux(n,M,C) {
	// T0 initial est 10% au bout d'un certain nombre d'iteration, le taux converge vers la solution
	T=M/C*(1-1/puissance(1+0.1,n));
	// On fait 3000 iterations pour etre sur.
	if(n<=3)
		iterations = 5000;
	else
		iterations = 3000;
	for(i=0;i<iterations;i++) {
		T=M/C*(1-1/puissance(1+T,n));
	}
	return T;
}

function tauxBase(n,M,C,T) {
	return M/C*(1-1/puissance(1+T,n));
}


function puissance(x,y) {
	//return y>0?y==Math.round(y)?y==1?x:x*puissance(x,y-1):x<0?"Non défini !":decomp(x,y):x==0?"Non défini !":y<0?1/puissance(x,-y):1;
	return Math.pow(x,y);
}

function VPM(TauxMensuel,Mois,Emprunt) {
	if(TauxMensuel==0) {
		return Emprunt/Mois;
	}
	else {
		return Emprunt * (TauxMensuel / (1 - puissance(1 + TauxMensuel, -Mois)));
	}
}

