/**
 * Investiční kalkulátor
 * @author Jan Prachař <jprachar@lundegaard.cz>
 * 
	cal = new Calculator
	cal.init(); //inicializace na defaultni nastaveni/zobrazení
	cal.setProduct(product); //nastaví product (a doby spoření, měs. částky, defaultní hodnoty)
	cal.setSavingLength(sl); //nastaví dobu spoření
	cal.setMonthAmount(ma); //nastaví měsíční částku
	
	cal.calculate(); //vynuti prepocitani vynosu, voláno všemi předchozími metodami
	
	//read-only properties:
	cal.products //pole produktů
	cal.savingLengths //pole roků
	cal.monthAmounts //pole castek
	cal.currency //měna
	cal.selectedProduct //vybraný produkt
	cal.selectedSavingLength //vybrana delka sporeni, nastaví se rovnež po změně produktu
	cal.selectedMonthAmount //vybrana castka, nastaví se rovnež po změně produktu
	cal.visibleSavingLengths //roky, ktere zobrazit (nastavuje se také při každé změně produktu)
	cal.visibleMonthAmount //castky, ktere zobrazit (nastavuje se také při každé změně produktu)
	cal.interest //úrok
	cal.sum //soucet nasporenych castek
	cal.amount //celkový výnos
	cal.disclaimer //text disclaimeru

 */
function Calculator ()
{
	this.loadData();
	this.page = new Calculator_Page(this);
}

/**
 * Načte data z konfiguračního souboru 
 */
Calculator.prototype.loadData = function()
{
	var configure = new Calculator_Configure();

	this.products = configure.products;
	
	this.savingLengths = new Array();
	for (var a=configure.minSavingLength; a<=configure.maxSavingLength; a++) {
		this.savingLengths.push(a);
	}
	
	this.monthAmounts = new Array();
	for (var a=configure.minMonthAmount; a<=configure.maxMonthAmount; a+=configure.stepMonthAmount) {
		this.monthAmounts.push(a);
	}
	
	this.currency = configure.currency;
	this.disclaimer = configure.disclaimer;
}

/**
 * Nastaví defaultní produkt
 */
Calculator.prototype.loadDefaults = function()
{
	for (var product in this.products) {
		if (this.products[product]['default']) {
			this.selectedProduct = this.products[product];
			break;
		}
	}
}

/**
 * Inicializace
 */
Calculator.prototype.init = function()
{
	this.loadDefaults();
	this.initSavingLengths();
	this.initMonthAmounts();

	this.calculate();
	//this.page.refresh();
}

Calculator.prototype.initSavingLengths = function()
{
	if (this.selectedProduct['finalYear'] !== null) {
		var currentDate = new Date();
		var lengthToFinalYear = this.selectedProduct['finalYear'] - currentDate.getFullYear();
		var defaultLength = lengthToFinalYear;
	} else {
		var defaultLength = this.selectedProduct['defaultLength'];
	}

	this.visibleSavingLengths = new Array();
	for (var length in this.savingLengths) {
		if ((this.savingLengths[length] >= this.selectedProduct['minLength']) && (this.savingLengths[length] <= this.selectedProduct['maxLength']) || in_array(this.savingLengths[length],this.selectedProduct['extraLengths'])) {
			if (this.selectedProduct['finalYear'] === null || this.savingLengths[length] <= lengthToFinalYear) {
				this.visibleSavingLengths.push(this.savingLengths[length]);
				if (this.savingLengths[length] == defaultLength) {
					this.selectedSavingLength = this.savingLengths[length];
				}
			}
		}
	}
}

Calculator.prototype.initMonthAmounts = function()
{
	this.visibleMonthAmounts = new Array();
	for (var amount in this.monthAmounts) {
		this.visibleMonthAmounts.push(this.monthAmounts[amount]);
		if (this.monthAmounts[amount] == this.selectedProduct['defaultMonthAmount']) {
			this.selectedMonthAmount = this.monthAmounts[amount];
		}
	}
}

/**
 * Obsluhuje změnu kteréhokoliv comboboxu
 */
Calculator.prototype.changeHandler = function(target)
{
	if (target == this.productCombo) {
		this.setProduct(this.products[target[target.selectedIndex].value]); 
	} else if (target == this.savingLengthCombo) {
		this.setSavingLength(target.options[target.selectedIndex].value); 
	} else if (target == this.monthAmountCombo) {
		this.setMonthAmount(target.options[target.selectedIndex].value); 
	}
}

Calculator.prototype.setProduct = function(product)
{
	if (this.selectedProduct.id != product.id) {
		this.selectedProduct = product;
		this.initSavingLengths();
		this.initMonthAmounts();
		this.calculate();
	}
	//this.page.refresh();
}

Calculator.prototype.setSavingLength = function(savingLength)
{
	this.selectedSavingLength = savingLength; 
	this.calculate();
	//this.page.refresh();
}

Calculator.prototype.setMonthAmount = function(monthAmount)
{
	this.selectedMonthAmount = monthAmount; 
	this.calculate();
	//this.page.refresh();
}

/**
 *
 */
Calculator.prototype.calculateMonthAmount = function(money)
{

//alert("asdf");
      var savingLength = parseInt(this.selectedSavingLength);
   		var mon =  money;			
			this.interest = this.selectedProduct['interest'];
			
			var perc = (this.interest/100)/12;
			var months = savingLength * 12; //sliderYearValue
			
			var res = 1 + perc;
			res = Math.pow(res,months);
			res = res - 1;
			res = res / perc;
			
			var spl = mon / res;
			
			var splTotal = months * spl;
			var intTotal = mon - splTotal;
   
     
     //this.amount
     this.amount = money;
     this.sum = Math.round(splTotal);
     this.selectedMonthAmount = Math.round(spl);
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
}; 
/**
 * Přepočítá výnos
 */
Calculator.prototype.calculate = function()
{

	var months = 0;
	var savingLength = parseInt(this.selectedSavingLength);
	var finalYear = this.selectedProduct['finalYear'];
	/* Pokud je zadán koncový rok */
	if (finalYear !== null) {
		var currentDate = new Date();
		/* Pokud se spoří až na konec */
		if (savingLength == finalYear - currentDate.getFullYear()) {
			months = -currentDate.getMonth()+6; // měsíce do konce roku + 6 měsícu navíc (je to do června finálního roku)
		}
	}
	
	months += 12*savingLength;

	//window.alert(months);
	this.interest = this.selectedProduct['interest'];
	var monthAmount = parseInt(this.selectedMonthAmount);
	this.sum = months*monthAmount;
	this.amount = 0;
	for (var month=1; month<=months; month++) {
		this.amount += monthAmount;
		this.amount += this.amount*(this.interest/12/100);
	}
	this.amount = Math.round(this.amount);
}

/**
 * Stránky kalkulátoru
 */
function Calculator_Page(calculator)
{
	this.number = 3;
	this.calculator = calculator;
	
	this.pages = new Array();
	this.pages[3] = document.getElementById('page3');
	

	this.productElement3 = document.getElementById('calculatorProductElement3');
	this.savingLengthElement3 = document.getElementById('calculatorSavingLengthElement3');
	this.monthAmountElement3 = document.getElementById('calculatorMonthAmountElement3');
	this.interestElement3 = document.getElementById('calculatorInterestElement3');
	this.sumElement3 = document.getElementById('calculatorSumElement3');
	this.amountElement3 = document.getElementById('calculatorAmountElement3');
	
	this.disclaimerElement = document.getElementById('calculatorDisclaimer');
	this.showDisclaimer = false;
	this.disclaimerElement.style.display = 'none';
	
	document.getElementById('calculatorDisclaimerPar').innerHTML = this.calculator.disclaimer;
}

Calculator_Page.prototype.next = function()
{
	if (this.number < 3) {
		this.number++;
	}
	this.refresh();
}

Calculator_Page.prototype.previous = function()
{
	if (this.number > 1) {
		this.number--;
	}
	this.refresh();
}

Calculator_Page.prototype.changeDisclaimerVisibility = function()
{
	this.showDisclaimer = !this.showDisclaimer;
	if (this.showDisclaimer) {
		this.disclaimerElement.style.display = 'block';
	} else {
		this.disclaimerElement.style.display = 'none';
	}
}

/**
 * Otevře nové okno obsahují text zadané stránky
 */
Calculator_Page.prototype.print = function(number)
{
	this.refreshPage(number);
	var printWindow = window.open('','Tisk',
		'height=850px, width=810px, top=0, left=100px, resizable=no, status=no, toolbar=no, menubar=yes,location=no, scrollbars=yes');
	printWindow.document.write(
		'<html><head>'+
		'<link href="/Styles/calculator.css" rel="stylesheet" type="text/css">'+
	    '</head>'+
	    '<body>'+
	    '<div id="calculatorContent">');
	printWindow.document.write(document.getElementById('calculatorContent').innerHTML);
	printWindow.document.write('</div></body></html>');
	printWindow.document.close();
	
	for (var i in this.pages) {
		if (number == i) {
			printWindow.document.getElementById(('page'+i)).style.display = 'block';
		} else {
			printWindow.document.getElementById(('page'+i)).style.display = 'none';
		}
	}

	printWindow.document.getElementById('calculatorContent').style.top = '0px';
	printWindow.document.getElementById('calculatorDisclaimer').style.display = 'block';
	printWindow.document.getElementById('calculatorClose').style.display = 'none';
	
	printWindow.focus();
	printWindow.print();
}

/**
 * Překreslí aktuální stránku
 */
Calculator_Page.prototype.refresh = function()
{
	for (var i in this.pages) {
		if (this.number == i) {
			this.pages[i].style.display = 'block';
			this.refreshPage(i);
		} else {
			this.pages[i].style.display = 'none';
		}
	}
}

Calculator_Page.prototype.refreshPage = function(number)
{
	if (number == 3) {
		this.productElement3.innerHTML = this.calculator.selectedProduct['name'];
		this.savingLengthElement3.innerHTML = this.calculator.selectedSavingLength+' '+getYearUnit(this.calculator.selectedSavingLength);
		this.monthAmountElement3.innerHTML = formatNumber(this.calculator.selectedMonthAmount);
		this.interestElement3.innerHTML = formatNumber(this.calculator.interest);
		this.sumElement3.innerHTML = formatNumber(this.calculator.sum);
		this.amountElement3.innerHTML = formatNumber(this.calculator.amount);

		var heightRel = this.calculator.sum/this.calculator.amount;
		var heightAbs = parseInt(document.getElementById('calculatorGraph2').style.height);

		document.getElementById('calculatorGraph2Column1').style.top = Math.round(heightAbs*(1-heightRel))+'px';
		document.getElementById('calculatorGraph2Column2').style.top = Math.round(-heightAbs*heightRel)+'px';
		document.getElementById('calculatorGraph2Column3').style.top = Math.round(-heightAbs*heightRel)+'px';

		document.getElementById('calculatorGraph2Column1').style.height = Math.round(heightAbs*heightRel)+'px';
		document.getElementById('calculatorGraph2Column2').style.height = Math.round(heightAbs*heightRel)+'px';
		document.getElementById('calculatorGraph2Column3').style.height = Math.round(heightAbs*(1-heightRel))+'px';
	}
}

/**
 * Naformátování čísla - mezery za každým třetím řádem, desetinná čárka
 */
function formatNumber(number)
{
	number += '';
	x = number.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ' ' + '$2');
	}
	return x1 + x2;
}

function getYearUnit(years)
{
	if (years == 1) {
		return 'rok';
	} else if (years >= 2 && years <= 4) {
		return 'roky';
	} else  {
		return 'let';
	}
}

function in_array (needle, haystack, argStrict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
 
    var key = '', strict = !!argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
 
    return false;
}

