var descriptions = new Array();
descriptions["ca"] = "Your current age in years.";
descriptions["ale"] = "According to the CDC and the CIA World Fact Book, the average life expectancy in the US is 75 years for males and 80 years for females.";
descriptions["ai"] = "This is your annual gross income before taxes.";
descriptions["aii"] = "This is the percentage by which you expect your annual income to increase year over year.";
descriptions["poiifr"] = "Percentage of your annual gross income invested towards retirement.";
descriptions["crf"] = "This is the total value of your assets from savings accounts, 401k, IRA and any other retirement assets.";
descriptions["ari"] = "The percentage return you expect to gain relative to the amount invested.";
descriptions["air"] = "Average inflation rate is 4%.  Adjusting for extreme economic, social or political events, a more accurate rate would be 5.5%.";
descriptions["aar"] = "The age at which you expect to retire from the work force.";
descriptions["aroifr"] = "A percentage return you expect to gain relative to the amount invested into your retirement account.";
descriptions["anir"] = "The annual income needed to sustain your desired standard of living.";
descriptions["aifos"] = "Pension, trust income, rental payments, disability, etc...";
descriptions["essi"] = "The amount of annual income you expect to get from Social Security.";
descriptions["asw"] = "Total amount you expect to withdraw from your retirement fund annually.";
$(document).ready(function(){
	$("input#Calculate").bind("click", function(){
		var val = $("span#status").html();
		$("span#status").html("calculating ...");
		calculate();
		$("span#status").html(val);
	});
	$("input.source").bind("change", function(){
		validate($(this));
	});
	$(".early").hide();
	$("input.withdrawls").bind("keyup", function(){
		$("span#annualSavingsWithdrawls").html(commatizeNumber(getPeriodDeduction().toFixed(0)));
	}).bind("change", function(){
		$("span#annualSavingsWithdrawls").html(commatizeNumber(getPeriodDeduction().toFixed(0)));
	});
	$(".hover").hoverIntent({
	   sensitivity: 1,
	   interval: 250,
	   over: function(event){
	   	if(typeof(ddrivetip)!='undefined') 
	   		ddrivetip(descriptions[$(this).attr("id")], 250);
	   		positiontip(event);
	   	},
	   timeout: 1,
	   out: hideddrivetip
	});
	initTest();
	$("input.chk").bind("change", function(){
		var target = $(this).attr("tgt");
		if($(this).attr('checked')){
			$("input#"+target).attr("disabled", "");
		}else{
			$("input#"+target).attr("disabled", "disabled");
		}
	}).each(function(){
		var target = $(this).attr("tgt");
		if($(this).attr('checked')){
			$("input#"+target).attr("disabled", "");
		}else{
			$("input#"+target).attr("disabled", "disabled");
		}
	});
});
function initTest(){
	set("currentAge", 35);
	set("avgLifeExpectancy", 78);
	set("annualIncome", "100,000");
	set("annualIncomeIncrease", 3);
	set("percOfIncomeInvestedForRetirement", 1);
	set("currentRetirementFund", 50000);
	set("avgReturnOnInvestment", 15);
	set("annualInflationRate", 4);
	set("ageAtRetirement", 60);
	set("avgReturnOnInvestmentForRetirementFund", 6);
	set("annualIncomeRequired", 35096);
	set("additionalIncome", 0);
	//set("annualSavingsWithdrawls", 35096);
	set("estSocialSecurityIncome", 0);
	$("span#annualSavingsWithdrawls").html(commatizeNumber(getPeriodDeduction().toFixed(0)));
	calculate();
}
// calculations
function getPresentValueSingleCashFlow(F, r, n, roundOff){
	var ret = F *(1/Math.pow((1+r), n));
	if(!roundOff) return ret;
	return round(ret, 2);
}
function getFutureValueSingleCashFlow(P, r, n, roundOff){
	var ret = P * Math.pow((1+r), n);
	if(!roundOff) return ret;
	return round(ret, 2);
}
function getFutureValueGrowingAnnuity(C, g, r, n){
	var ret = -1;
	if(r != g){
		ret = (1 / (r - g))*(Math.pow((1 + r), n) - Math.pow((1 + g), n));
	}else{
		ret = n * Math.pow((1 + r), (n - 1));
	}
	return Math.floor(C * ret);
}
function getFutureValueAnnuity(C, r, n, roundOff){
	var ret = -1;
	ret = C * ((Math.pow((1 + r), n) -1) / r);
	if(!roundOff) return ret;
	return round(ret, 2);
}
// helpers
function round(val, places){
	var pow_ten = 1;
	while(places-- > 0){
		pow_ten *= 10;
	}
	return Math.round(val * pow_ten) / pow_ten;
}
function roundLeft(val, places, upShift){
	if(upShift == null) upShift = 0;
	var pow_ten = 1;
	while(places-- > 0){
		pow_ten *= 10;
	}
	return Math.round((val / pow_ten) + upShift) * pow_ten;
}
function getNumberOfPeriods(){
	return get("ageAtRetirement") - get("currentAge");
}
function getPeriodDeduction(){
	var air = get("annualIncomeRequired");
	var ai = get("additionalIncome");
	var essi = get("estSocialSecurityIncome");
	//var asw = get("annualSavingsWithdrawls");
	var ret = get("annualIncomeRequired") - 
		(get("additionalIncome") + 
		get("estSocialSecurityIncome"));// + get("annualSavingsWithdrawls");

	return ret;
}
function validate(field){
	var val = $(field).val();
	if(val == null || val == ""){
		val = "0";
	}
	var sval = val;
	val = "";
	for(var i = 0; i < sval.length; i++){
		if(sval.charAt(i) == "."){
			val += sval.charAt(i);
			continue;
		}
		try{
			var rep = parseInt(sval.charAt(i));
			if(""+rep != "NaN")
				val += rep;
		}catch (e){};
	}
	var ret = parseFloat(val);
	if(""+ret == "NaN") ret = 0.0;
	var prec = getInt($(field).attr("precision"));
	var max = $(field).attr("max");
	var min = $(field).attr("min");
	if(parseInt(max)+"" == "NaN"){
		max = $(max).val();
		if(parseInt(max)+"" == "NaN"){
			max = 999999999;
		}
	}
	if(parseInt(min)+"" == "NaN"){
		min = $(min).val();
		if(parseInt(min)+"" == "NaN"){
			min = 0;
		}
	}
	if(max != null && max != ""){
		if(parseInt(max) < ret) ret = parseInt(max);
	}
	if(min != null && min != ""){
		if(parseInt(min) > ret) ret = parseInt(min);
	}
	$(field).val(commatizeNumber(ret.toFixed(prec)));
}
function getInt(val){
	val = replaceAll(val, ",", "");
	val = parseInt(val);
	if(val+"" == "NaN")
		return 0;
	return val;
}
function get(name){
	if(name == "numberOfPeriods"){
		return getNumberOfPeriods();
	}else if(name == "periodDeduction"){
		return getPeriodDeduction();
	}
	var tog = $('input#'+name+"CHK");
	if(tog.length != 0){
		if(!$('input#'+name+"CHK").attr('checked')) 
			return 0;
	}
	var ret = 0;
	var val = $('input#'+name).val();
	if(val == null || val == ""){
		return 0;
	}
	val = replaceAll(val, ",", "");
	var ret = parseFloat(val);
	if($('input#'+name).is(".perc")){
		var ret = parseFloat(val) / 100;
		if(""+ret == "NaN") ret = 0;
	}
	return ret;
}
function set(name, value){
	var tog = $('input#'+name+"CHK");
	if(tog.length != 0){
		if(!$('input#'+name+"CHK").attr('checked')){
			var chk = true;
			if(value == null || value == 0 || value == "0") 
				chk = false;
			$('input#'+name+'CHK').attr('checked', chk);
		}
	}
	if(value == null || value == 0 || value == "0") value = "";
	validate($('input#'+name).val(value));
}
// logic
function getPurchasingPowerAtRetirement(periods){
	if(periods == null) periods = get("numberOfPeriods");
	var F = getFutureValueSingleCashFlow(get("currentRetirementFund"),
		get("avgReturnOnInvestment"), periods, true);
	var air = get("annualInflationRate");
	return getPresentValueSingleCashFlow(F, air, 
		periods, true);
}
var tm = 1;
function leftFormatter(dval){
	var val = "";
	dval *= tm;
	if(dval >= 1000000000000){
		val = "$"+(dval / 1000000000000) + "T";
	}else if(dval >= 1000000000){
		val = "$"+(dval / 1000000000) + "B";
	}else if(dval >= 1000000){
		val = "$"+(dval / 1000000)+"M";
	}else if(dval >= 1000){
		val = "$"+(dval / 1000)+"K";
	}else{
		dval = roundLeft(dval, (""+dval).length - 2);
		val = "$"+commatizeNumber(dval);
	}
//	dval = roundLeft(dval, (""+dval).length - 2);
//	var ret = "$"+dval;//commatizeNumber(dval);
//	var ttm = tm;
	//while(ttm > 9){
	//	ret += "0";
	//	ttm /= 10;
	//}
	return val;
}
function getPurchasingPowerPresentValue(periods){
	if(periods == null) periods = get("numberOfPeriods");
	var ret = -1;
	var aii = get("annualIncomeIncrease");
	var air = get("annualInflationRate");
	var ari = get("avgReturnOnInvestment");
	//console.log(aii + " " + air + " " + ari);
	var investedIncome = get("percOfIncomeInvestedForRetirement") * get("annualIncome");
	//console.log(investedIncome);
	if(aii > 0 && air > 0){
		var F = getFutureValueGrowingAnnuity(
			investedIncome,	aii, ari, periods);
		ret = getPresentValueSingleCashFlow(F, air, periods, true);
	}else if(aii > 0 && air == 0){
		ret = getFutureValueGrowingAnnuity(
			investedIncome,	aii, ari, periods);
	}else if(aii == 0 && air > 0){
		var F = getFutureValueAnnuity(investedIncome, ari,
			periods, true);
		ret = getPresentValueSingleCashFlow(F, air, periods, true);
	}else{
		ret = getFutureValueAnnuity(
			investedIncome, ari, periods, true);
	}
	if(ret+"" == "NaN") ret = 0;
	//console.log(ret + "\n------\n");
	return ret;
}
var scale = 1;
var height = 220;
function toScale(val){
	return val / scale;
}
var width = 460;
function getWScale(xtop){
	var ret = (width / xtop);
	return ret;
}
function calculate(){
	printChildScripts = true;
	tm = 1;
	var xLabels = new Array();
	var avgLifeExp = get("avgLifeExpectancy");
	var currentSavings = getPurchasingPowerAtRetirement(null);
	var plannedSavings = getPurchasingPowerPresentValue(null);
	var beginningBalance = currentSavings + plannedSavings;
	var largest = beginningBalance;
	var annualSavingsNeeds = get("periodDeduction");
	var comfortableRetirementAge = avgLifeExp;
	var lowestBalance = 0;
	var currentBalance = beginningBalance;
	var heirsGet = 0;
	// get scale
	$("td.retirementSavings").html("$"+commatizeNumber(beginningBalance.toFixed(0)));
	var currentAge = get("currentAge");
	var ageAtRetirement = get("ageAtRetirement");
	var pre = new Array();
	var post = new Array();
	var runout = new Array();
	for(var i = currentAge; i < ageAtRetirement; i++){
		var pds = i - currentAge;
		var age = i;
		var bal = getPurchasingPowerAtRetirement(pds) + getPurchasingPowerPresentValue(pds);
		if(i == currentAge){
			xLabels.push(""+i);
		}else{
			xLabels.push("");
		}
		post.push(0);
		pre.push(bal);
		runout.push(0);
		if(bal > largest) largest = bal;
		
	}
	xLabels.push(""+ageAtRetirement);
	post.push(currentBalance);
	pre.push(0);
	runout.push(0);
	if(currentBalance > largest) largest = currentBalance;
	currentBalance = beginningBalance - annualSavingsNeeds;
	post.push(currentBalance);
	pre.push(0);
	runout.push(0);
	if(currentBalance > largest) largest = currentBalance;
	var annualInflationRate = get("annualInflationRate");
	var avgROIforFund = get("avgReturnOnInvestmentForRetirementFund");
	var ageRed = false;
	$(".early").hide();
	for(var i = ageAtRetirement + 2; i <= avgLifeExp; i++){
		//ageC++;
		var deduction = 0;
		if(annualInflationRate > 0){
			deduction = annualSavingsNeeds;
		}else{
			deduction = getFutureValueSingleCashFlow(annualSavingsNeeds,
				avgROIforFund, 
				((i - ageAtRetirement) - 1), true);  
		}
		currentBalance -= deduction;
		
		currentBalance = getFutureValueSingleCashFlow(currentBalance,
			avgROIforFund, 1, true);
		if(currentBalance <= 0){
			xLabels.push(""+i-1);
			$('td#fundsExpire').html(i - 1);
			$(".early").show();
			break;
		}else{
			post.push(currentBalance);
			pre.push(0);
			runout.push(0);
			if(currentBalance > largest) largest = currentBalance;
		}
		if(i == (ageAtRetirement + 2)){
			xLabels.push("");
		}else{
			if(i == avgLifeExp){
				xLabels.push("");
				xLabels.push(""+i);
//				ages.append("<td/><td align=right colspan=",ageSpan,">",avgLifeExp,"</td>");
//				skipAge = 0;
			}else{// if(skipAge < ageSpan){
				//xLabels.push(""+i-1);
//				skipAge++;
			//}else{
				xLabels.push("");
//				ages.append("<td/>");
			}
		}
	}
	var w = Math.round(getWScale(pre.length + post.length));
	if(w < 1) w = 1;
	//w = 10;
	// do table here have to figure out red line next
	if(currentBalance <= 0){
		runout.pop();
		runout.push(post.pop());
		post.push(0);
		xLabels.push("(red)"+xLabels.pop());
	}
	if(currentBalance > 0){
		if(annualInflationRate > 0){
			currentBalance = getPresentValueSingleCashFlow(
				currentBalance, annualInflationRate, 1, true); //get("numberOfPeriods"), true); 
		}
	}else{
		currentBalance = 0;
	}
	var top = roundLeft(largest.toFixed(0), (""+largest.toFixed(0)).length - 2, 1);
	var test = new Array();
	var vals = "";
	var newVals = "";
	var testTop = top;
	var l = 10;
	var yGrid = "10";
	while(testTop > 100000){
		l--;
		tm *= 100;
		testTop = top / tm;
	}
	if(tm > 1){
		top = top / tm;
		for(var i = 0; i < post.length; i++){
			if(post[i] > 0) post[i] = post[i] / tm;
		}
		for(var i = 0; i < pre.length; i++){
			if(pre[i] > 0) pre[i] = pre[i] / tm;
		}
		for(var i = 0; i < runout.length; i++){
			if(runout[i] < 0){
				runout[i] = 0;
			}else{
				var rval = runout[i] / tm;
				if(rval < 0) rval = 0;
				runout[i] = rval;
			}
		}
	}
	if(runout[runout.length - 1] < 0) runout[runout.length - 1] = 0;
	$('div#chart')
.chartInit({"painterType":"jsgraphics","backgroundColor":"","textColor":"","axesColor":"","yMin":"0","yMax":top,"xGrid":"0","yGrid":yGrid,"xLabels":xLabels,"showLegend":false,"yFormatter":leftFormatter})
.chartAdd({"label":"preRetire","type":"Bar", "width":w,"color":"rgb(122,193,66)","values":pre})
.chartAdd({"label":"postRetire","type":"Bar", "width":w, "color":"rgb(50,90,19)","values":post,"stackedOn":"preRetire"})
.chartAdd({"label":"runOutYear","type":"Bar", "width":w, "color":"rgb(254,1,1)","values":runout,"stackedOn":"postRetire"})
.chartClear()
.chartDraw();
	$('td#inherit').html("$"+commatizeNumber(currentBalance.toFixed(0)));
}







