var years_cases=['рік', 'роки', 'років'];
var month_cases=['місяць', 'місяці', 'місяців'];
var year_txt=document.getElementById("year_txt");
var month_txt=document.getElementById("month_txt");
var btn = document.getElementById('calculate');
var result=document.getElementById("result");
var histo=document.getElementById("histo");
var form=document.getElementById("form");
var wrong=false;

function init(){
	Hide();
}   
    
function YearTxt(what){
	var index=0;
	wrong = false;
	switch (what) {
		case '0': index=2; break;
		case '1': index=0; break;
		case '2': index=1; break;
		case '3': index=1; break;
		case '4': index=1; break;
		default: 
		if (what > 4 && what < 18 || what == '') { index=2 } else { index=2; wrong=true; }
	}
	if (wrong) { 
		alert ("Вік дитини не може перевищувати 18 років");
		born_year.value="";
		born_year.focus();
		btn.disabled=true;
	}
	year_txt.innerHTML=years_cases[index];	
}

function MonthTxt(what){
	var index=0;
	
	switch (what) {
		case '': index=2; break;
		case '0': index=2; break;
		case '1': index=0; break;
		case '2': index=1; break;
		case '3': index=1; break;
		case '4': index=1; break;
		default: 
		if (what>4 && what<13 || what=='' ) { 
			index=2; 
		} else { 
			born_month.value="";
		}
	}
	month_txt.innerHTML=month_cases[index];
}

// покакзать объекты в списке id
function Show(id) {
	Hide();
	arr = id.split(',');
	for(i=0; i < arr.length; i++ ){
		document.getElementById(arr[i]).style.display='block';
	}
	document.getElementById('form').style.display='block';	
	document.getElementById('note').style.display='block';
	Verify();
}

// скрыть объекты
function Hide() {
	for(i=0; i < 7; i++ ){
		document.getElementById(i).style.display='none';
	}
	result.style.display='none';
	histo.style.display='none';	
	btn.disabled=true;
}

//проверить поля формы
function Verify(){
	var born_year=document.getElementById("born_year").value;
	var born_month =document.getElementById("born_month").value;
	var payment=document.getElementById("payment").value;
	var total=document.getElementById("total").value;
	var monthly=document.getElementById("monthly").value;
	var yearly=document.getElementById("yearly").value;
	var percent=document.getElementById("percent").value;
	
	btn.disabled=true;
		
	switch (isPlan()) {
		case 'fbu1': if ((born_year || born_month) && payment && monthly && percent) { btn.disabled=false; } else { btn.disabled=true; } break;
		case 'fbu2': if ((born_year || born_month) && payment && yearly && percent) { btn.disabled=false; } else { btn.disabled=true; } break;
		case 'fbu3': if ((born_year || born_month) && payment && total && percent) { btn.disabled=false; } else { btn.disabled=true; } break;
		case 'fbu4': if ((born_year || born_month) && monthly && total && percent) { btn.disabled=false; } else { btn.disabled=true; } break;
	}
	
	YearTxt(born_year);
	MonthTxt (born_month);
}

function isPlan() {
	var inputs=document.getElementsByTagName('input');
	for(i=0; i < inputs.length; i++){
		if (inputs[i].checked) { 
			return inputs[i].id 			
		}
	}
}

function calcResults(what){
	var graph=new Array();
	var month_count=0;
	var sum=0; 
	var sum1=0; 
	var j=1;	
	var sum_monthly;
	var date_txt="";	
	var tmp_graph="";
	var tmp_desc = "";
	var tmp_result="";
	var born_year=parseInt(document.getElementById("born_year").value);
	var born_month=parseInt(document.getElementById("born_month").value);
	var year_txt=document.getElementById("year_txt").innerHTML;	
	var month_txt=document.getElementById("month_txt").innerHTML;	
	var payment=document.getElementById("payment").value;
	var total=document.getElementById("total").value;
	var monthly=document.getElementById("monthly").value;
	var yearly=document.getElementById("yearly").value;
	var percent=document.getElementById("percent").value;
	
	percent_txt = percent.replace('.',',');
	payment=parseFloat(payment.replace(',','.'));
	total=parseFloat(total.replace(',','.'));
	monthly=parseFloat(monthly.replace(',','.'));
	yearly=parseFloat(yearly.replace(',','.'));
	percent=parseFloat(percent.replace(',','.'));
	
	histo.style.display='none';	
	
	// введен ли месяц
	if (isNaN(born_month) || born_month == 0) { 
		date_txt = born_year + " " + year_txt; 
		born_month = 0;
	} else {
		date_txt = born_year + " " + year_txt + " " + born_month + " міс.";
	}
	
	// Період накопичення в мес
	month_count = 216 - (born_year*12 + born_month);
	
	//выбираем план рассчета
	switch (isPlan()) {
		
		//---------------------------------------------------------------------------------------------------------------------------------------
		// С ежемесячным пополнением
		//---------------------------------------------------------------------------------------------------------------------------------------
		case 'fbu1': 
			j=0;
			year14 = 168-(born_year*12 + born_month);
			sum = payment*(1+percent/100/12)+monthly;
			for(i=1; i < month_count; i++){
				tmp = i+born_year*12+born_month;
				if (tmp%12==0) { 
						graph[j] = sum;
						j++;
					}
				if (i == year14) { 
					sum14 = sum;
				}
				sum += sum*(percent/100/12) + monthly;				
			}
			
			graph[j] = sum;
			extra = sum - (monthly*month_count + payment);
			total_payment = monthly*month_count + payment;
						
			// Результат
			tmp_result = "<h2>Сума вкладу до 18-річчя: <span class=total>" + sum.toLocaleString() + " грн.</span></h2>";
			tmp_result += "<table cellpadding=0 cellspacing=0 border=0><tr><td valign=top width=55%>";
			
			//Выходные данные
			tmp_result += "<table cellpadding=0 cellspacing=0 class=result width=100% border=0>";
			tmp_result += "<tr><th colspan=2>Розрахунок:</th></tr>";
			tmp_result += "<tr><td>Період накопичення:</td><td align=right>" + month_count + " міс.</td></tr>";
			tmp_result += "<tr><td>Внесено за весь період:</td><td align=right>" + total_payment.toLocaleString() + " грн.</td></tr>";
			tmp_result += "<tr><td>Нараховано відсотків:</td><td align=right>" + extra.toLocaleString() + " грн.</td></tr>";
			if (year14 > 5) { tmp_result += "<tr><td><nobr>Сума вкладу до 14-річчя:</nobr>:</td><td align=right>" + sum14.toLocaleString() + " грн.</td></tr>"; }
			tmp_result += "</table>";
						
			tmp_result += "</td><td>     </td><td valign=top width=45%>";
									
			//Вхідні данні
			tmp_result += "<table cellpadding=0 cellspacing=0 class=result width=100%>";
			tmp_result += "<tr><th colspan=2>Вхідні данні:</th>";
			tmp_result += "<tr><td>Вік дитини:</td><td align=right>" + date_txt + "</td></tr>";
			tmp_result += "<tr><td>Початковий внесок:</td><td align=right>" + payment.toLocaleString() + " грн.</td></tr>";
			tmp_result += "<tr><td>Щомісячне поповнення:</td><td align=right>" + monthly.toLocaleString() + " грн.</td></tr>";
			tmp_result += "<tr><td>Відсоткова ставка:</td><td align=right>" + percent_txt + " %</td></tr>";
			tmp_result += "</table>";
						
			tmp_result += "</td></tr></table>";
			
			//График
			tmp_result += "<div id=show_graph><a onclick=ShowGraph()><small>Графік накопичення</small></a></div>";
			for(i=0; i < graph.length; i++){
				dig = (graph[i]*100/sum).toFixed(0);
				tmp_graph += "<td valign=bottom class=graph><img src=/img/calc/gtop.gif><br><img title='" + graph[i].toFixed(0) + " грн.' src=/img/calc/g.gif width=7 height=" + dig + "></td>";
				tmp_desc += "<td class=desc>" + (i+1+born_year) + "</td>";
			}
			tmp_graph = "<td>&nbsp;</td>" + tmp_graph;
			tmp_desc  = "<td class=x>Вік дитини</td>" + tmp_desc;
			tmp_graph = "<div id=hide_graph class=hand onclick=HideGraph()><small><b style='font-size: 12px;'>Графік накопичення:</b><table cellpadding=0 cellspacing=0 border=0><tr>" + tmp_graph + "</tr><tr>" + tmp_desc + "</tr></table></div>";
						
			result.innerHTML=tmp_result;
			histo.innerHTML=tmp_graph;
			result.style.display='block';
			break;
		
		//---------------------------------------------------------------------------------------------------------------------------------------
		// с ежегодным пополнением
		//---------------------------------------------------------------------------------------------------------------------------------------
		case 'fbu2': 
			year_count = 18 - born_year;
			year14 = 14 - born_year;
			sum = payment*Math.pow((1+percent/100/12),12) + yearly;			
			graph[0] = sum;
			for(i=1; i < year_count; i++){
				sum = sum*Math.pow((1+percent/100/12),12) + yearly;
				graph[i] = sum;
				if (i == year14) { 
					sum14 = sum;					
				}				
			}
			extra = sum - (yearly*year_count + payment);
			total_payment = yearly*year_count + payment;
			
			// Результат
			tmp_result = "<h2>Сума вкладу до 18-річчя: <span class=total>" + sum.toLocaleString() + " грн.</h2>";
			tmp_result += "<table cellpadding=0 cellspacing=0 border=0><tr><td valign=top width=55%>";
						
			//Выходные данные
			tmp_result += "<table cellpadding=0 cellspacing=0 class=result width=100%>";
			tmp_result += "<tr><th colspan=2>Розрахунок:</th></tr>";
			tmp_result += "<tr><td>Період накопичення:</td><td align=right>" + (18*12-born_year*12) + " міс.</td></tr>";
			tmp_result += "<tr><td>Внесено за весь період:</td><td align=right>" + total_payment.toLocaleString() + " грн.</td></tr>";
			tmp_result += "<tr><td>Нараховано відсотків:</td><td align=right>" + extra.toLocaleString() + " грн.</td></tr>";
			if (year14 > 5) { tmp_result += "<tr><td>Сума вкладу до 14-річчя:</td><td align=right>" + sum14.toLocaleString() + " грн.</td></tr>"; }
			tmp_result += "</table>";
						
			tmp_result += "</td><td>     </td><td valign=top width=45%>";
						
			
			//Вхідні данні
			tmp_result += "<table cellpadding=0 cellspacing=0 class=result width=100%>";
			tmp_result += "<tr><th colspan=2>Вхідні данні:</th>";
			tmp_result += "<tr><td>Вік дитини:</td><td align=right>" + date_txt + "</td></tr>";
			tmp_result += "<tr><td>Початковий внесок:</td><td align=right>" + payment.toLocaleString() + " грн.</td></tr>";
			tmp_result += "<tr><td>Щорічне  поповнення:</td><td align=right>" + yearly.toLocaleString() + " грн.</td></tr>";
			tmp_result += "<tr><td>Відсоткова ставка:</td><td align=right>" + percent_txt + " %</td></tr>";
			tmp_result += "</table>";
						
			tmp_result += "</td></tr></table>";
			
			//График
			tmp_result += "<div id=show_graph><p><a onclick=ShowGraph()><small>Графік накопичення</small></a></div>";
			for(i=0; i < graph.length; i++){
				dig = (graph[i]*100/sum).toFixed(0);
				tmp_graph += "<td valign=bottom class=graph><img src=/img/calc/gtop.gif><br><img title='" + graph[i].toFixed(0) + " грн.' src=/img/calc/g.gif width=7 height=" + dig + "></td>";
				tmp_desc += "<td class=desc>" + (i+1+born_year) + "</td>";
			}
			tmp_graph = "<td>&nbsp;</td>" + tmp_graph;
			tmp_desc  = "<td class=x>Вік дитини</td>" + tmp_desc;
			tmp_graph = "<div class=hand id=hide_graph onclick=HideGraph()><p><b>Графік накопичення:</b></div><table cellpadding=0 cellspacing=0 border=0><tr>" + tmp_graph + "</tr><tr>" + tmp_desc + "</tr></table>";
						
			result.innerHTML=tmp_result;
			histo.innerHTML=tmp_graph;
			result.style.display='block';
			
			break;
			
		case 'fbu3': 
			if (eval(total > payment)) {
				sum_monthly = (percent/100/12)*(total-payment*Math.pow((1+percent/100/12),month_count))/(Math.pow(1+percent/100/12,month_count)-1);
			} else {
				sum_monthly = 0;
				monthly=0;
				year14 = 168-(born_year*12 + born_month);
				sum = payment*(1+percent/100/12)+monthly;
				for(i=1; i < month_count; i++){
					tmp = i+born_year*12+born_month;
					if (tmp%12==0) { 
							graph[j] = sum;
							j++;
						}
					if (i == year14) { 
						sum14 = sum;
					}
					sum += sum*(percent/100/12) + monthly;				
				}
				
				graph[j] = sum;
				extra = sum - (monthly*month_count + payment);
				total_payment = monthly*month_count + payment;	
				total = sum;				
			}					
			
			// Результат
			tmp_result = "<h2>Сума щомісячного поповнення: <span class=total>" + sum_monthly.toLocaleString() + " грн.</h2>";
			tmp_result += "<table cellpadding=0 border=0 width=100%><tr><td valign=top width=48%>";
			tmp_result += "<table cellpadding=0 cellspacing=0 class=result width=100%>";
			tmp_result += "<tr><td>Вік дитини:</td><td align=right>" + date_txt + "</td></tr>";
			tmp_result += "<tr><td>Початковий внесок:</td><td align=right>" + payment.toLocaleString() + " грн.</td></tr>";
			tmp_result += "<tr><td>Сума вкладу:</td><td align=right>" + total.toLocaleString() + " грн.</td></tr>";
			tmp_result += "<tr><td>Період накопичення:</td><td align=right>" + month_count + " міс.</td></tr>";
			tmp_result += "<tr><td>Відсоткова ставка:</td><td align=right>" + percent_txt + " %</td></tr>";
			tmp_result += "</table>";
			tmp_result += "</td></tr></table>";
			
			result.innerHTML=tmp_result;
			result.style.display='block';
			break;
		case 'fbu4': 
			sum1 = monthly*(Math.pow((1+percent/100/12),month_count)-1)/(percent/100/12);
			if (sum1 < total) {
				sum_payment = (total-sum1)/Math.pow((1+percent/100/12),month_count);
			} 
			else {
				sum_payment = 0;
				year14 = 168-(born_year*12 + born_month);
				sum = payment*(1+percent/100/12)+monthly;
				for(i=1; i < month_count; i++){
					tmp = i+born_year*12+born_month;
					if (tmp%12==0) { 
							graph[j] = sum;
							j++;
						}
					if (i == year14) { 
						sum14 = sum;
					}
					sum += sum*(percent/100/12) + monthly;				
				}
				
				graph[j] = sum;
				extra = sum - (monthly*month_count + payment);
				total_payment = monthly*month_count + payment;	
				total = sum;				
			}
			
			// Результат
			tmp_result = "<h2>Сума початкового внеску:<span class=total>" + sum_payment.toLocaleString() + " грн.</h2>";
			tmp_result += "<table cellpadding=0 border=0 width=100%><tr><td valign=top width=48%>";
			tmp_result += "<table cellpadding=0 cellspacing=0 class=result width=100%>";
			tmp_result += "<tr><td>Вік дитини:</td><td align=right>" + date_txt + "</td></tr>";
			tmp_result += "<tr><td>Щомісячне поповнення:</td><td align=right>" + monthly.toLocaleString() + " грн.</td></tr>";
			tmp_result += "<tr><td>Сума вкладу:</td><td align=right>" + total.toLocaleString() + " грн.</td></tr>";
			tmp_result += "<tr><td>Період накопичення:</td><td align=right>" + month_count + " міс.</td></tr>";
			tmp_result += "<tr><td>Відсоткова ставка:</td><td align=right>" + percent_txt + " %</td></tr>";
			tmp_result += "</table>";
			tmp_result += "</td></tr></table>";
			
			result.innerHTML=tmp_result;
			result.style.display='block';
			break;
		default: break;
		
	}	
}

function ShowGraph(){
	document.getElementById("histo").style.display='block';
	document.getElementById("hide_graph").style.display='block';
	document.getElementById("show_graph").style.display='none';		
}

function HideGraph(){
	document.getElementById("histo").style.display='none';
	document.getElementById("hide_graph").style.display='none';
	document.getElementById("show_graph").style.display='block';
}
