// jason's additional functionality
// october 2006
var activeStory = 0;//calc default values
var canPrint = false;//user can only print when results are showing
var Stories = new Array ('Story0','Story1');

//---------------------------- currentAccount, avgReturn, newMoney, currentAge, retirementAge, yearsToLast
Stories["Story0"] = new Array('','','','','','');
Stories["Story1"] = new Array('40,000','4','3,500','32','62','25');


function setStory(thisStory, start) {
	toggleDiv("ResultsPane", false);
	toggleDiv("Help", false);
	canPrint = false;
	if (start) {
		window.location.hash = 'CalcStart';
	}
	
	for (var i=0; i < Stories.length; i++) {
		if (thisStory == Stories[i]) {
			if (thisStory == 'Story0') {
				useMyNumbers(true);
			} else {
				toggleDiv(thisStory, true);
				activeStory = i;
				resetFieldBgColor('fff');
				useStoryNumbers(Stories[i]);
				Calculate(false);
			}
		} else {
			toggleDiv(Stories[i], false);
		}
	}
}

function useMyNumbers(reset) {
	document.aspnetForm.numbers[0].checked = true;
	activeStory = 0;
	if (reset) {
		useStoryNumbers('Story0');
	}
	resetFieldBgColor('c6f7a2');
	for (var i=0; i < Stories.length; i++) {
		toggleDiv(Stories[i], false);
	}
	toggleDiv("ResultsPane", false);
	toggleDiv("Help", false);
	canPrint = false;
}

function useStoryNumbers(str) {
	document.aspnetForm.currentAccount.value = Stories[str][0];
	document.aspnetForm.avgReturn.value = Stories[str][1];
	document.aspnetForm.newMoney.value = Stories[str][2];
	document.aspnetForm.currentAge.value = Stories[str][3];
	document.aspnetForm.retirementAge.value = Stories[str][4];
	document.aspnetForm.yearsToLast.value = Stories[str][5];
}

function toggleDiv(thisDiv, state) {
	toggle = eval('document.getElementById(\''+ thisDiv +'\')');
	if (state) {
		toggle.style.display = "block";
	} else {
		toggle.style.display = "none";
	}
}


function fieldUpdate(field,fieldPosition,isValueCheck,isAddZeros) {
	thisField = eval('document.aspnetForm.'+ field);
	if (activeStory != 0) {
		useMyNumbers(false);
	} else {
		toggleDiv("ResultsPane", false);
		toggleDiv("Help", false);
	
	}
	thisField.style.backgroundColor = '#fff';
	
	if (ValueCheck(thisField, isValueCheck)) {
		if (isValueCheck) {
			if (thisField.value > 99) { 
				thisField.value = '99.99'; 
			}
		}
		thisField.value=addzeros(thisField.value, isAddZeros);
	}
}

function resetFieldBgColor(color) {
	document.aspnetForm.currentAccount.style.backgroundColor = "#"+ color +"";
	document.aspnetForm.avgReturn.style.backgroundColor = "#"+ color +"";
	document.aspnetForm.newMoney.style.backgroundColor = "#"+ color +"";
	document.aspnetForm.currentAge.style.backgroundColor = "#"+ color +"";
	document.aspnetForm.retirementAge.style.backgroundColor = "#"+ color +"";
	document.aspnetForm.yearsToLast.style.backgroundColor = "#"+ color +"";
}


function printCalc() {
	if (canPrint) {
		window.print();
	} else {
		alert('Please calculate the results before printing');
	}
}

function init() {
	document.aspnetForm.numbers[activeStory].checked = true;
	setStory (Stories[activeStory], false);
}

function resetCalc(frm) {
	setStory('Story0', true);
}

function addzeros(num, useDecimals) {  
// Takes an unformatted number and adds formatting (commas and up to 2 decimal places).

	if (useDecimals == true) {
		if (num == null || isNaN(num) || Number(num) == 0) { return 0; }
		num = parseFloat(num);
		num = Math.round(100*num);
		num = num.toString();
		var p1 = num.substring(0, num.length - 2);
		var p2 = num.substring(num.length - 2, num.length);
		num = p1 + '.' + p2;
	}

	var txtNumber = '' + num;
	var rxSplit = new RegExp('([0-9])([0-9][0-9][0-9][,.])');
	var arrNumber = txtNumber.split('.');
	arrNumber[0] += '.';
	do { arrNumber[0] = arrNumber[0].replace(rxSplit, '$1,$2');	} 
	while (rxSplit.test(arrNumber[0]));

	if (arrNumber.length > 1) {
	return arrNumber.join('');
	}
	else {
	return arrNumber[0].split('.')[0];
    }	
}

function ValueCheck(refVal, AllowDecimal) {
// Validates the contents of a field, checking for illegal characters and nags if it finds any.

	if (refVal.value.length == 0) { return true; }
	var DecimalFlag = false;	var bDec = true; var FieldValid = true;
	for (var i=0; i < refVal.value.length; i++) {
		var c = refVal.value.charCodeAt(i);
        if ((c > 57 || c < 48)) {
			if (c==46) {
				if (AllowDecimal == false || DecimalFlag == true) {	var bDec = false; }
				else { DecimalFlag = true; } }
			else if (c==44 || c==36 || c==37) { }
			else { FieldValid = false; }
			}
	}
	if (FieldValid==false || bDec==false) {
		if (AllowDecimal) { alert('Only numbers and a decimal can be entered into this field.\nPlease adjust the value.'); }
		else { alert('Only enter numbers into this field.\nPlease adjust the value.'); }
		refVal.focus();	refVal.select(); return false; }
	else { return true; } 
}

function FormatToNumber(refVal) {
// Returns a formatted number to it's root form ($1,000.00 to 1000).

	tmpVar = refVal.value;
	if (tmpVar.length != 0) { 
		for (count = 0; count < tmpVar.length; count ++) {
			if (tmpVar.charCodeAt(count) == 44 || tmpVar.charCodeAt(count) == 36 || tmpVar.charCodeAt(count) == 37) {
				tmpVar = tmpVar.substring(0, count) + tmpVar.substring(count+1, tmpVar.length); }
		}}
	return tmpVar;
}

//////////////////////////////////////////////////

//This function adds comma formating to the number
var ErrorObjects=new Array();

function addCommas(nStr)
{
	nStr += '';
	x = nStr.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 ResetForm(which){
var pass=true
var first=-1
if (document.images){
for (i=0;i<which.length;i++){
var tempobj=which.elements[i]
 if (tempobj.type=="text"){
  eval(tempobj.value="")
  if (first==-1) {first=i}
 }
 else if (tempobj.type=="checkbox") {
  eval(tempobj.checked=0)
  if (first==-1) {first=i}
 }
 else if (tempobj.col!="") {
  eval(tempobj.value="")
  if (first==-1) {first=i}
 }
}
}
which.elements[first].focus()
return false
}


//This function fills or clears the sample numbers
function Sample(fill) {

if (fill == true)
{
clearAllError();
document.aspnetForm.customNumbers[1].checked=true;
document.aspnetForm.currentAccount.value = "40,000";
document.aspnetForm.avgReturn.value = "4";
document.aspnetForm.newMoney.value = "3,500";

document.aspnetForm.currentAge.value = "32";
document.aspnetForm.retirementAge.value = "62";
//document.aspnetForm.yearsToRetirement.value = "30";

document.aspnetForm.yearsToLast.value = "25";
document.getElementById("rrspTotal").innerHTML = "326,033.18";
document.getElementById("howMuch2").innerHTML = "20,870.02";
}
else
{
clearAllError();
document.aspnetForm.currentAccount.value = "";
document.aspnetForm.avgReturn.value = "";
document.aspnetForm.newMoney.value = "";

document.aspnetForm.currentAge.value = "";
document.aspnetForm.retirementAge.value = "";
//document.aspnetForm.yearsToRetirement.value = "";

document.aspnetForm.yearsToLast.value = "";
document.getElementById("rrspTotal").innerHTML = "";
document.getElementById("howMuch2").innerHTML = "";
}
}

function ClearResults() {
document.getElementById("rrspTotal").innerHTML = "";
document.getElementById("howMuch2").innerHTML = "";
}

//This functions calls validate function then optionally calls calculate function
function Calculate(results) {
	if (Validate()) {
		toggleDiv ("ResultsPane", true);
		canPrint = true;
		CalculateFunction();
		if (results) {
			window.location.hash = 'ResultsStart';
		}
	}
}


//This function calculates the form
function CalculateFunction() {

var CUR = document.aspnetForm.currentAccount.value.replace(",","");
CUR = CUR.replace(",","");
var ARR = document.aspnetForm.avgReturn.value.replace(",","")/100;
var AC = document.aspnetForm.newMoney.value.replace(",","");

var CURR_AGE = document.aspnetForm.currentAge.value.replace(",","");
var RET_AT_AGE = document.aspnetForm.retirementAge.value.replace(",","");

var RET_AGE = RET_AT_AGE - CURR_AGE;
var RET_LENGTH = document.aspnetForm.yearsToLast.value.replace(",","");


var e = Math.pow((1+ARR),RET_AGE);
var f = (e-1)/ARR;
var g = Math.round((CUR*e + AC*f)*100)/100;

var h = Math.pow((1+ARR),-RET_LENGTH);
var i = Math.round(((g*ARR)/(1-h))*100)/100;

document.aspnetForm.currentAccount.value = addCommas(CUR);
document.aspnetForm.newMoney.value = addCommas(AC);
document.getElementById("rrspTotal").innerHTML =  addCommas(g);
document.getElementById("howMuch2").innerHTML = addCommas(i);

}
//--------------------------------------------- Validation -------------------------------------------//
function showError(obj){
	obj.focus();
	obj.select();
	obj.className="BlankField";
	ErrorObjects[ErrorObjects.length]=obj;
}
//
function clearAllError(){
	var i=0;
	for(i=0;i<ErrorObjects.length;i++){
		ErrorObjects[i].className="";
	}
}

function check_CUR() {

var CUR_Format =/(^\d{1,10}$)|(^\d{0,9}\.\d{1,2}$)/;
var CUR = document.aspnetForm.currentAccount.value.replace(",","");
CUR = CUR.replace(",","");

if (CUR_Format.test(CUR)) 
	{
		if (CUR>=0 && CUR<1000000000)
			{
			return true;
			}
		else 
			{
			return false;
			}
	}
else
	{
	return false;
	}	
}


function check_ARR() {

var ARR_Format =/(^\d{1,2}$)|(^\d{0,2}\.\d{1,2}$)/;
var ARR = document.aspnetForm.avgReturn.value;

if (ARR_Format.test(ARR)) 
	{
		if (ARR>0 && ARR<=30)
			{
			return true;
			}
		else 
			{
			return false;
			}
	}
else
	{
	return false;
	}	
}

function check_AC() {

var AC_Format =/(^\d{1,5}$)|(^\d{0,5}\.\d{1,2}$)/;
var AC = document.aspnetForm.newMoney.value.replace(",","");

if (AC_Format.test(AC)) 
	{
		if (AC>=0 && AC<=20000)
			{
			return true;
			}
		else 
			{
			return false;
			}
	}
else
	{
	return false;
	}	
}


function check_RET_AGE() {

var RET_AGE_Format =/(^\d{1,2}$)/;

var CURR_AGE = document.aspnetForm.currentAge.value.replace(",","");
var RET_AT_AGE = document.aspnetForm.retirementAge.value.replace(",","");

var RET_AGE = RET_AT_AGE - CURR_AGE;

if (RET_AGE_Format.test(RET_AGE)) 
	{
		if (RET_AGE>=1 && RET_AGE<60)
			{
			return true;
			}
		else 
			{
			return false;
			}
	}
else
	{
	return false;
	}	
}

function check_RET_LENGTH() {

var RET_LENGTH_Format =/(^\d{1,2}$)/;
var RET_LENGTH = document.aspnetForm.yearsToLast.value.replace(",","");

if (RET_LENGTH_Format.test(RET_LENGTH)) 
	{
		if (RET_LENGTH>=1 && RET_LENGTH<=50)
			{
			return true;
			}
		else 
			{
			return false;
			}
	}
else
	{
	return false;
	}	
}


function Validate() {

clearAllError();
try
	{
		if (!check_CUR())
			{
			showError(document.aspnetForm.currentAccount);
			throw "What's your total RRSP savings to date? Please enter the amount, with or without cents or commas (must be less than $1,000,000,000).";
			return false;
			}
		if (!check_ARR())
			{
			showError(document.aspnetForm.avgReturn);
			throw "This is the annual rate of return. Please enter a number greater than 0 and less than or equal to 30. You can use a whole number or use one decimal point.";
			return false;
			}
		if (!check_AC())
			{
			showError(document.aspnetForm.newMoney);
			throw "This is what you plan to contribute each year from now on. Please enter the amount, with or without cents or commas. Remember - the government sets a limit on how much you can contribute to your RRSP each year.";
			return false;
			}
		if (!check_RET_AGE())
			{
			showError(document.aspnetForm.yearsToRetirement);
			throw "How many years before you retire? Please enter the number of years (must be less than 60).";
			return false;
			}
		if (!check_RET_LENGTH())
			{
			showError(document.aspnetForm.yearsToLast);
			throw "How many years will your retirement last? Please enter the number of years (must be less than 51).";
			return false;
			}
	}
catch(e)
	{
		alert(e);
		return false;
	}
	return true;
}
