// requires jQuery.js, commonCalculator.js
jQuery(function() {
	jQuery("#calculatorForm").bind('submit', calculate);	
	
	calculate();
});

function calculate() {
	var initialInvestment = getInputMoney("#initialInvestment");
	var monthlyInvestment = getInputMoney("#monthlyInvestment");
	var annualRate = getInputRate("#annualRate");
	var yearsDesired = getInputNumber("#yearsDesired");
	
	var becomeMillionaire = new Calculators.planning.BecomeMillionaire(initialInvestment, monthlyInvestment, annualRate, yearsDesired);

/*
	console.debug(becomeMillionaire.getInitialInvestment());
	console.debug(becomeMillionaire.getMonthlyInvestment());
	console.debug(becomeMillionaire.getAnnualRate());
	console.debug(becomeMillionaire.getYearsDesired());		
	*/
	//console.debug(becomeMillionaire.getYearlySchedule());
	jQuery("#reportCalculatedYears").text(becomeMillionaire.getYearsToBecomeMillionaire());
	jQuery("#reportYearsDesired").text(yearsDesired);
	jQuery("#reportTotalAccumulated").text(becomeMillionaire.getAmountAtDesiredYears().formatted());
	jQuery("#reportChangeInitial").text(becomeMillionaire.getRecommendedInitialInvestment().formatted());
	jQuery("#reportChangeMonthly").text(becomeMillionaire.getRecommendedMonthlyInvestment().formatted());
	jQuery("#reportChangeRate").text(becomeMillionaire.getRecommendedRate().formatted());	
	plotValues(becomeMillionaire);
	return false;
}

function plotValues(becomeMillionaire){
	var chart = new FusionCharts("FusionCharts/FCF_Line.swf", "graphId", "560", "400");
	var dataXml = generateDataXml(becomeMillionaire);
	chart.setDataXML(dataXml);
	chart.render("graph");
};
// 		afd8f8, f6bd0f
function generateDataXml(becomeMillionaire){
	var returnXml = new Array();
	returnXml.push("<?xml version='1.0'?>\n");
	returnXml.push("<graph caption='Years to Become a Millionaire' xAxisName='Year' yAxisName='Accumulated' showNames='1' showValues='0' decimalPrecision='2' formatNumberScale='0' numberPrefix='$' formatNumber='1' animation='0' lineColor='afd8f8' showShadow='0' outCnvBaseFontColor='999999'>");
	returnXml.push("<set name='0' value='"+becomeMillionaire.getInitialInvestment().getAmount()+"'  showname='1'/>");
	for(var i = 0; i < becomeMillionaire.getYearlySchedule().length; i++) {
		var modulus = Math.round(becomeMillionaire.getYearlySchedule().length / 9);
		var showName = '0';
		if((i % modulus == modulus - 1))
			showName = '1';
		var value = becomeMillionaire.getYearlySchedule()[i].getAccumulatedSavings();
  returnXml.push("<set name='"+becomeMillionaire.getYearlySchedule()[i].getPeriodNumber()+"' value='"+value.getAmount()+"' showname='"+showName+"'/>");
	}
	returnXml.push("<trendLines>");
  returnXml.push("<line startValue='1000000' color='f6bd0f' displayvalue='Millionaire' />"); 
  returnXml.push("</trendLines>");
	returnXml.push("</graph>");
	return returnXml.join("");
}
