//Script to calculate pension for a given annual or monthly pension contribution
function pensionTarget()
{
	//new variables specific to pension projection
	var myForm = document.calcTargetPen;
	var contribution = myForm.cont.value;
	contribution = parseFloat(contribution);
	var premium = myForm.prem.value;
	premium = parseFloat(premium);
	var growthRate = 0.07;
	var amc = 0.01;
	var fvr = 0.0025;
	var rpi = 0.025;
	var div = Math.pow(10,0); //used for rounding to nearest whole number
	var ngr = Math.pow((Math.pow((1 + growthRate),(1/365)) - (amc/365)),365);
	var accFactor = (ngr-1)/(1-(Math.pow(ngr,(-1/12))));
	
	var whichSexIndex = 0;
	var whichSex;
	for (whichSexIndex = 0; whichSexIndex < myForm.sex.length; whichSexIndex++)
	{
		if (myForm.sex[whichSexIndex].checked == true)
		{
			 whichSex = myForm.sex[whichSexIndex].value;
		}
	}
	
	var frequencyIndex = 0;
	var frequency;
	for (frequencyIndex = 0; frequencyIndex < myForm.freq.length; frequencyIndex++)
	{
		if (myForm.freq[frequencyIndex].checked == true)
		{
			frequency = myForm.freq[frequencyIndex].value;
		}
	}
	
	//variables carried over from contribution calculator to store DOB as a date
	var dateOfBirthDay = myForm.dobDay.options[myForm.dobDay.selectedIndex].value;
	var dateOfBirthMonth = myForm.dobMonth.options[myForm.dobMonth.selectedIndex].value;
	var dateOfBirthYear = myForm.dobYear.options[myForm.dobYear.selectedIndex].value;
	var dateOfBirth = new Date(dateOfBirthDay + " " + dateOfBirthMonth + " " + dateOfBirthYear);
	
	//variables to determine the retirement age and its value in days
	var selectedRetAge = myForm.sra.options[myForm.sra.selectedIndex].value;
	var selectedRetAgeDays = selectedRetAge*365.25;

	//variables to calculate the actual retirement date depending upon the SRA
	var retirementDate = new Date(dateOfBirthDay + " " + dateOfBirthMonth + " " + dateOfBirthYear);
	var dateOfBirthIndex = dateOfBirth.getDate();
	dateOfBirthIndex = dateOfBirthIndex + 1;
	retirementDate.setDate(dateOfBirthIndex + selectedRetAgeDays);
	
	//variables to calculate the current date and hence the maximum possible term
	var currentDate = new Date();
	var term = (retirementDate.valueOf() - currentDate.valueOf());
	term = ((((term/1000)/60)/60)/24)/365.25; //convert term from milliseconds to years
	
	//split term into years and months
	var termMonths = term;
	var termYears = Math.floor(term);
	termMonths = Math.floor(termMonths);
	termMonths = term - termMonths;
	termMonths = termMonths*12;
	termMonths = Math.floor(termMonths);
	
	//Calculate value of fund
	var fundStartYearValue = premium;
	var fundValue = 0;
	var termYearIndex = 0;
	var fundStartMonthValue = 0;
	var termMonthIndex = 0;
	
	//Call function to determine annuity rate
	var annuityRate = getAnnuityRate(dateOfBirthYear, whichSex, selectedRetAge);
	
	//Error handling for when user has selected an inappropriate retirement age, i.e., they're already at or beyond the age at which they wish to retire.
	if(annuityRate == 0)
	{
		alert("Please select a later\nretirement age");
		myForm.sra.focus();
	}
	else if(termYears < 0 && selectedRetAge <= 70)
	{
		alert("Please select a later\nretirement age");
		myForm.sra.focus();
	}
	else if(termYears < 0 && selectedRetAge == 75)
	{
		alert("Once you have reached 75\nyears of age, you can\nno longer purchase a pension.");
		myForm.sra.focus();
	}
	else if(termYears == 0 && termMonths < 1 && selectedRetAge <= 70)
	{
		alert("Please select a later\nretirement age");
		myForm.sra.focus();
	}
	else if(termYears == 0 && termMonths < 1 && selectedRetAge == 75)
	{
		alert("Once you have reached 75\nyears of age, you can\nno longer purchase a pension.");
		myForm.sra.focus();
	}
	else
	{
		if (frequency == "monthly")
		{
			for (termYearIndex = 0; termYearIndex < termYears; termYearIndex++)
			{
				fundValue = (contribution*accFactor) + (fundStartYearValue*ngr);
				if (fundValue >= 50000)
				{
					fundValue = fundValue*(1 + fvr);
				}
				fundStartYearValue = fundValue;
			}
			if (termYears == 0)
			{
				fundStartMonthValue = premium;
			}
			else
			{
				fundStartMonthValue = fundValue;
			}
			for (termMonthIndex = 0; termMonthIndex < termMonths; termMonthIndex++)
			{
				fundValue = (fundStartMonthValue + contribution) * (Math.pow(ngr,(1/12)));
				fundStartMonthValue = fundValue;
			}
		}
		else if (frequency == "yearly")
		{
			for (termYearIndex = 0; termYearIndex < termYears; termYearIndex++)
			{
				fundValue = (contribution*ngr) + (fundStartYearValue*ngr);
				if (fundValue >= 50000)
				{
					fundValue = fundValue*(1 + fvr);
				}
				fundStartYearValue = fundValue;
			}
		
			fundStartMonthValue = fundValue;
			fundValue = (fundStartMonthValue + contribution) * (Math.pow(ngr,(termMonths/12)));
		}
		fundValue = Math.round(fundValue * div) / div; //round value to nearest whole number
		myForm.retFund.value = formatNumber(fundValue);
		
		
	
		//Calculate potential pension using appropriate annuity rate
		var pensionValue = myForm.penPotential.value;
		pensionValue = (fundValue/annuityRate)/12;
		pensionValue = Math.round(pensionValue * div) / div; //round value to nearest whole number
		myForm.penPotential.value = formatNumber(pensionValue) + " per month";
		
		//Calculate today's value of potential pension using appropriate annuity rate
		var pensionValueToday;
		pensionValueToday = ((pensionValue*12)/(Math.pow((1 + rpi),(term))))/12;
		pensionValueToday = Math.round(pensionValueToday * div) / div; //round value to nearest whole number
		myForm.penToday.value = formatNumber(pensionValueToday) + " per month";
	}
}

//Format Number Function
//format figure as follows: 23,589,022
function formatNumber(numberToFormat)
{
	var splitRetFund = new String(numberToFormat);//makes the fund value a string
	var numberOfParts = 0;
	numberOfParts = splitRetFund.length;//determines number of elements in the fund value string
		
	var reversedString = "";
	var rereversedString = "";
	var indexCount;
	
	for (indexCount = numberOfParts - 1; indexCount >= 0; indexCount--)
	{
		reversedString = reversedString + splitRetFund.charAt(indexCount);//reverses the order of the fund value string
	}
	if (numberOfParts > 0 && numberOfParts <= 3)
	{
		return numberToFormat;
	}
	else if (numberOfParts > 3 && numberOfParts <= 6)
	{
		var mySubString = reversedString.substring(0,3);
		var mySubString2 = reversedString.substring(3,numberOfParts);
		var myFormattedNumber = mySubString + ',' + mySubString2;
		numberOfParts = myFormattedNumber.length;//determines number of elements in the formatted fund value string
		for (indexCount = numberOfParts; indexCount >= 0; indexCount--)
		{
			rereversedString = rereversedString + myFormattedNumber.charAt(indexCount);//reverses the order of the formatted fund value string
		}
		return rereversedString;
	}
	else if (numberOfParts > 6 && numberOfParts <= 9)
	{
		var mySubString = reversedString.substring(0,3);
		var mySubString2 = reversedString.substring(3,6);
		var mySubString3 = reversedString.substring(6,numberOfParts);
		var myFormattedNumber = mySubString + ',' + mySubString2 + ',' + mySubString3;
		numberOfParts = myFormattedNumber.length;//determines number of elements in the formatted fund value string
		for (indexCount = numberOfParts; indexCount >= 0; indexCount--)
		{
			rereversedString = rereversedString + myFormattedNumber.charAt(indexCount);//reverses the order of the formatted fund value string
		}
		return rereversedString;
	}
	else if (numberOfParts > 9 && numberOfParts <= 12)
	{
		var mySubString = reversedString.substring(0,3);
		var mySubString2 = reversedString.substring(3,6);
		var mySubString3 = reversedString.substring(6,9);
		var mySubString4 = reversedString.substring(9,numberOfParts);
		var myFormattedNumber = mySubString + ',' + mySubString2 + ',' + mySubString3 + ',' + mySubString4;
		numberOfParts = myFormattedNumber.length;//determines number of elements in the formatted fund value string
		for (indexCount = numberOfParts; indexCount >= 0; indexCount--)
		{
			rereversedString = rereversedString + myFormattedNumber.charAt(indexCount);//reverses the order of the formatted fund value string
		}
		return rereversedString;
	}
	else if (numberOfParts > 12 && numberOfParts <= 15)
	{
		var mySubString = reversedString.substring(0,3);
		var mySubString2 = reversedString.substring(3,6);
		var mySubString3 = reversedString.substring(6,9);
		var mySubString4 = reversedString.substring(9,12);
		var mySubString5 = reversedString.substring(12,numberOfParts);
		var myFormattedNumber = mySubString + ',' + mySubString2 + ',' + mySubString3 + ',' + mySubString4 + ',' + mySubString5;
		numberOfParts = myFormattedNumber.length;//determines number of elements in the formatted fund value string
		for (indexCount = numberOfParts; indexCount >= 0; indexCount--)
		{
			rereversedString = rereversedString + myFormattedNumber.charAt(indexCount);//reverses the order of the formatted fund value string
		}
		return rereversedString;
	}
}


//Error handling
function checkForm()
{
	var myForm = document.calcTargetPen;
	var dateOfBirthYear = myForm.dobYear.options[myForm.dobYear.selectedIndex].value;
	
	if(myForm.dobDay.options[myForm.dobDay.selectedIndex].value > 29 && myForm.dobMonth.options[myForm.dobMonth.selectedIndex].value == "Feb")
	{
		alert("Please check your birth date");
		myForm.dobDay.focus();
	}
	else if(myForm.dobDay.options[myForm.dobDay.selectedIndex].value == 29 && myForm.dobMonth.options[myForm.dobMonth.selectedIndex].value == "Feb" && isLeapYear(dateOfBirthYear) == false)
	{
		alert("Please check your birth date\nThis was not a Leap Year");
		myForm.dobDay.focus();
	}
	else if(myForm.dobDay.options[myForm.dobDay.selectedIndex].value > 30 && myForm.dobMonth.options[myForm.dobMonth.selectedIndex].value == "Apr")
	{
		alert("Please check your birth date");
		myForm.dobDay.focus();
	}
	else if(myForm.dobDay.options[myForm.dobDay.selectedIndex].value > 30 && myForm.dobMonth.options[myForm.dobMonth.selectedIndex].value == "Jun")
	{
		alert("Please check your birth date");
		myForm.dobDay.focus();
	}
	else if(myForm.dobDay.options[myForm.dobDay.selectedIndex].value > 30 && myForm.dobMonth.options[myForm.dobMonth.selectedIndex].value == "Sep")
	{
		alert("Please check your birth date");
		myForm.dobDay.focus();
	}
	else if(myForm.dobDay.options[myForm.dobDay.selectedIndex].value > 30 && myForm.dobMonth.options[myForm.dobMonth.selectedIndex].value == "Nov")
	{
		alert("Please check your birth date");
		myForm.dobDay.focus();
	}
	else
	{
		if(myForm.cont.value == "")
		{
			alert("Please enter a value\nfor your contribution");
			myForm.cont.focus();
		}
		else if(isNaN(myForm.cont.value))
		{
			alert("Please enter your contribution as a number\nomitting any spaces or commas.");
			myForm.cont.focus();
		}
		else if(myForm.prem.value == "")
		{
			myForm.prem.value = 0;
		}
		else if(isNaN(myForm.prem.value))
		{
			alert("Please enter your contribution as a number\nomitting any spaces or commas.");
			myForm.prem.focus();
		}
		else if (myForm.cont.value > 10000000)
		{
			alert("Please enter a lower\ncontribution");
			myForm.cont.focus();
		}
		else
		{
			function testForSpaces(text)
			{
			var spaceArray = /\s/gi;
			return !(spaceArray.test(text));
			}
			if (testForSpaces(myForm.cont.value) == false)
			{
				alert("Please enter your contribution as a number\nomitting any spaces or commas.");
				myForm.cont.focus();
			}
			else if (testForSpaces(myForm.prem.value) == false)
			{
				alert("Please enter your premium as a number\nomitting any spaces or commas.");
				myForm.prem.focus();
			}
			else
			{
				pensionTarget();
			}
		}
	}
}

function isLeapYear(yearToTest)
{
	if(((yearToTest % 4 == 0) && (yearToTest % 100 != 0)) || (yearToTest % 400 == 0))
	{
		return true;
	}
	else 
	{
		return false;
	}
}

function MM_openBrWindow(theURL,winName,features) {
  window.open(theURL,winName,features);
  return false;
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

  function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
  }
  MM_reloadPage(true);
  
  function writeJS() {
var str='';
str+='<a href="javascript:window.print()"><img src="..\/images\/print-off.gif" alt="print page" name="Image19" width="16" height="10" border="0" id="Image19" \/>print page<\/a>';
document.write(str);
}

function popupPage(url)
{
window.open(url,'smallWindow','location=no,scrollbars=yes,menubar=no,toolbar=yes,resizable=yes,left=75,top=75,width=590,height=400');
}

function popupPageAl(url)
{
alert("Scottish Equitable plc is authorised and regulated by the Financial Services Authority.  In leaving this site you may be moving to an unregulated website.");
window.open(url,'smallWindow','location=yes,scrollbars=yes,menubar=yes,toolbar=yes,resizable=yes,left=75,top=75,width=700,height=420');
}

function popupPageCl(url)
{
alert("You are about to view pages over a secure connection.\rThe site is hosted by Medibureau Ltd who are employed by Scottish Equitable and comply with the Data Protection Act 1998.");
window.open(url,'smallWindow','location=no,scrollbars=yes,menubar=yes,toolbar=yes,resizable=yes,left=75,top=75,width=800,height=420');
}