/*
* UI: Process clicks on bank form
* Change value of input field
*/
function c_click(element) {
	if (element.id == 'year') {
		var defvalue = year_default;
	} else if (element.id == 'price') {
		var defvalue = price_default;
	}
	if (element.value == defvalue){element.value=''}
}

/*
* UI: Process blur on bank form
* Change value of input field
* if both fields is not empty - try to calculate loan
*/
function c_blur(element){


	if (element.id == 'year') {
		var defvalue = year_default;
	} else if (element.id == 'price') {
		var defvalue = price_default;
	}
	if (element.value == ''){element.value=defvalue}
	else {

		var year = parseInt($F('year'));
		var price = parseFloat($F('price').replace(' ', ''));

		if (!price || !year) return;
		loan = process_loan(year, price);
		if (loan) {
			$('present_value').value = loan[0];
			$('loan_term').value = loan[1];
			$('monthly_payment').value = loan[2];
		}
	}

}
/*
* UI: Show loan for the table
* Found current row in the table and classes year and .end with current year prices
* parse values
* and show it on specifiec classes
*/
function adv_loan(img) {
	

	block = $(img).up('tr');
	var year = block.previous().down('.year').innerHTML;
	var price = block.previous().down('.end').innerHTML.replace('&nbsp;', ' ');
	if (price.match(/у\.е\./)) {
		price = parseInt(price) * 8;
	} else {
		price = parseInt(price);
	}		
	if (!price || !year) {
	
		return false;
	}
	
	loan = process_loan(year, price);
	if (loan) {
		if (loan[1] == 1) {
			 loan_term = loan[1] + ' год';
		} else if (loan[1] > 4) {
			 loan_term = loan[1] + ' лет';
		} else {
			 loan_term = loan[1] + ' года';
		}
		
		block.down('.present_value').innerHTML = loan[0] + ' грн.';
		block.down('.loan_term').innerHTML = loan_term;
		block.down('.monthly_payment').innerHTML = loan[2] + ' грн.';;
		
		block.down('.bank').show();	
	}
}

/* 
* Calculate loan 
* All errors will be shown in div#error
* change variables at the top to customize script
* @return array of present value, loan rerm and monthly payment
* 
*/
function process_loan(year, price) {
		
		var minprice = 10000;
		var theDate=new Date();
		var percent = 0.6;
		var curyear = theDate.getFullYear();
		var minyear = curyear - 7;
		var interest_rate = 0.1799		

		if (year <= minyear) {
			$('error').innerHTML = 'Автомобиль должен быть старше ' + minyear + ' года';
			return false;
		} else if (year > curyear) {
			$('error').innerHTML = 'Автомобили из будущего еще не кредитуют в ' + curyear + ' году';
			return false;
		} else if (price < minprice) {
			$('error').innerHTML = 'Цена должена быть больше ' + minprice;
			return false;			
		} else {
			$('error').innerHTML = '';

			var present_value = price * percent;
			var loan_term;	//if (2011-year < 2;5;7-(2011-year)) * И(ЕСЛИ(2011-B5>7;0;7-(2011-B5)))
			if (curyear - year < 2) {
				loan_term = 5;
			} else {
				loan_term = 7 - (curyear - year);
			}
			if (loan_term < 1 ) return;

			var monthly_payment = calculate_payment(present_value, interest_rate / 12, loan_term * 12)
			
			return new Array(present_value, loan_term, monthly_payment);
		
		}	
}

/* 
 * Calculate PMT depending on present value, invest rate and loan term
 * Round result to 2 
*/
function calculate_payment(PV, IR, NP) {
	var PMT = (PV * IR) / (1 - Math.pow(1 + IR, -NP))
	return round_decimals(PMT, 2)
}

/* 
 * Mathermatical round original_number to decimals
*/
function round_decimals(original_number, decimals) {
	var result1 = original_number * Math.pow(10, decimals)
	var result2 = Math.round(result1)
	var result3 = result2 / Math.pow(10, decimals)
	return (result3)
}



function showModelsByMark(mark){
	if (!$('search_models')) return;
	search_models = $('search_models')
	search_models.innerHTML = '';

	var option = document.createElement('option');
	option.value='';
	option.innerHTML='Любая модель';
	search_models.appendChild(option);


	for (var link in Marks[mark].models ) {
		var model = Marks[mark].models[link]

		var option = document.createElement('option');
		option.value=link;
		option.innerHTML=model.name;
		search_models.appendChild(option);

	}

}

function toggleDetail(id){
	if ($('detail_'+id).visible()) {
		$('link_'+id).className = '';
		$('detail_'+id).hide();
	} else {
		$('link_'+id).className = 'details';
		$('detail_'+id).show();
	}
}



function validateRegForm(form) {

	$$(".notice").each (function (element) {element.className = ''});

	var error = '';
	if (!form.email.value) {
		error += 'Пожалуйста, укашите Email<br />'
		form.email.className = "notice";
	} else if (form.email.value == '') {
		error += 'Email не может быть пустым<br />'
		form.email.className = "notice";
	}

	if (!form.passwd.value ) {
		error += 'Пожалуйста, укажите пароль<br />'
		form.passwd.className = "notice";
	}
	if (form.passwd.value != form.confirm.value) {
		error += 'Пароль не совпадает с подтверждением<br />'
		form.confirm.className = "notice";
	}

	if (!form.last_name.value ) {
		error += 'Укажите фамилию<br />'
		form.last_name.className = "notice";
	}

	if (!form.first_name.value ) {
		error += 'Укажите имя<br />'
		form.first_name.className = "notice";
	}

	if (error != '') {
		$$('#register .error').first().innerHTML = error;
		return false;
	} else {
		$$('#register .error').first().innerHTML = '';
		return true;
	}

}

var lightbox = 0;
Init = function (){
	 new Lightbox();

}
window.onload = Init;


