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 MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function MM_displayStatusMsg(msgStr) { //v1.0
  status=msgStr;
  document.MM_returnValue = true;
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


swidth = screen.width - 10
sheight = screen.height - 110
windowprops = "top=0,left=0,resizable=1,menubar=1,scrollbars=1" + ",width=" + swidth + ",height=" + sheight;

// function to open window centred on screen
function NewWindow(mypage, myname, w, h, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
win = window.open(mypage, myname, winprops)
if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}


// check Risk Assessment Quiz
function CheckForm() {
 var el = document.frmQuiz.elements;
 for(var i = 0 ; i < el.length ; ++i) {
  if(el[i].type == "radio") {
   var radiogroup = el[el[i].name]; // get the whole set of radio buttons.
   var itemchecked = false;
   for(var j = 0 ; j < radiogroup.length ; ++j) {
    if(radiogroup[j].checked) {
	 itemchecked = true;
	 break;
	}
   }
   if(!itemchecked) { 
    alert("Please answer Question "+el[i].name+".");
    if(el[i].focus)
     el[i].focus();
	return false;
   }
  }
 }
 return true;
} 


// format currenty
function currencyFormat(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) return true;  // Enter
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	len = fld.value.length;
	for(i = 0; i < len; i++)
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
		fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}


// calculation for Investment Worksheet
function isNumeric(s) {
	var temp=parseFloat(s)
	if (isNaN(temp)) {
		return false;
	}
	return true;
}

function getRound(value, decimal) {
    if (isNumeric(decimal) == false) {
        decimal = 0;
    }
    return Math.round(value * Math.pow(10, decimal)) / Math.pow(10, decimal);
}

function Sum() {
	var nIndex = 0;
	var hasValue = false;
	var nSum = 0;
	for (nIndex = 0; nIndex < Sum.arguments.length; nIndex++) {
		if (isNumeric(Sum.arguments[nIndex])) {
			nSum += parseFloat(Sum.arguments[nIndex]);
			hasValue = true;
		}
	}
	if (hasValue)
	return nSum;
	else
	return "";
}

function updateCashAssets() {
	with (document.frmPersonal) {
		TotalCash.value = Sum(CashOnHand.value, BankAccounts.value);
	}
	updateTotalAssets();
	return true;
}

function updateFixedIncome() {
	with (document.frmPersonal) {
		TotalFixed.value = Sum(FixedDeposits.value, Bonds.value, FixedOthers.value);
	}
	updateTotalAssets();
	return true;
}

function updateEquityAssets() {
	with (document.frmPersonal) {
		TotalEquity.value = Sum(Shares.value, UnitTrusts.value, EquityOthers.value );
	}
	updateTotalAssets();
	return true;
}

function updateEPFAssets() {
	with (document.frmPersonal) {
		TotalEPF.value = Sum(EPFCash.value);
	}
	updateTotalAssets();
	return true;
}

function updatePersonalAssets() {
	with (document.frmPersonal) {
		TotalProperties.value = Sum(Residence.value, InvestmentProp.value );
		TotalPersonal.value = Sum(PersonalCar.value, LifeInsurance.value, PersonalOthers.value );
	}
	updateTotalAssets();
	return true;
}

function updateIlliquidAssets() {
	with (document.frmPersonal) {
		TotalIlliquid.value = Sum(BusinessInt.value);
	}
	updateTotalAssets();
	return true;
}

function updateTotalAssets() {
	with (document.frmPersonal) {
		TotalAssets.value = Sum(TotalCash.value, TotalFixed.value, TotalEquity.value, TotalEPF.value, TotalProperties.value, TotalPersonal.value, TotalIlliquid.value);
	}
	updateNetWorth();
	return true;
}

function updateShortTermLiabilities() {
	with (document.frmPersonal) {
		TotalShortTerm.value = Sum(CreditCard.value, Overdraft.value,	CarLoans.value, ShortTermOthers.value);
	}
	updateTotalLiabilities();
	return true;
}

function updateLongTermLiabilities() {
	with (document.frmPersonal) {
		TotalLongTerm.value = Sum(HomeMortgage.value, MortgageOther.value, LongTermOther.value);
	}
	updateTotalLiabilities();
	return true;
}

function updateTotalLiabilities() {
	with (document.frmPersonal) {
		TotalLiabilities.value = Sum(TotalShortTerm.value, TotalLongTerm.value);
	}
	updateNetWorth();
	return true;
}

function updateNetWorth() {
	with (document.frmPersonal) {
		if (isNumeric(TotalAssets.value) && isNumeric(TotalLiabilities.value))
		NetWorth.value = parseFloat(TotalAssets.value) - parseFloat(TotalLiabilities.value);
		else if (isNumeric(TotalAssets.value))
		NetWorth.value = TotalAssets.value;
		else if (isNumeric(TotalLiabilities.value))
		NetWorth.value = - parseFloat(TotalLiabilities.value);;
	}
	return true;
}


function updateIncome() {
	with (document.frmPersonal) {
		TotalIncome.value = Sum(NetSalary.value, Rental.value,	Dividend.value, OtherIncome.value);
	}
	updateCashFlow();
	return true;
}

function updateExpenses() {
	with (document.frmPersonal) {
		TotalExpenses.value = Sum(Utilities.value, Food.value,	Clothing.value, Housing.value, Transport.value, Health.value,	Savings.value, Recreation.value, Miscellaneous.value);
	}
	updateCashFlow();
	return true;
}

function updateCashFlow() {
	with (document.frmPersonal) {
		MonthlyIncome.value = "";
		if (isNumeric(TotalIncome.value) && isNumeric(TotalExpenses.value))
			MonthlyIncome.value = TotalIncome.value - TotalExpenses.value;
		else if (isNumeric(TotalIncome.value))
			MonthlyIncome.value = TotalIncome.value
		else if (isNumeric(TotalExpenses.value))
			MonthlyIncome.value = - parseFloat(TotalExpenses.value);
	}
	return true;
}


// check Feedback/Requisition Form
function chkFeedback() {
	if (document.frmFeedback.Name.value.length <= 0) {
		alert ("Please enter your NAME.");
		document.frmFeedback.Name.focus ();
		return false;
	}
}

// check email address validity
function emailCheck(emailStr) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		alert("E-mail address seems incorrect (check @ and .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("The username contains invalid characters.");
			return false;
		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("The domain name contains invalid characters.");
			return false;
		}
	}
	
	// See if "user" is valid 
	if (user.match(userPat)==null) {
		alert("The username does not seem to be valid.");
		return false;
	}
	
	// IP address (as opposed to a symbolic
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Destination IP address is invalid !");
				return false;
			}
		}
		return true;
	}
	
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			alert("The domain name does not seem to be valid.");
			return false;
		}
	}
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("E-mail address must end in a well-known domain or two letter country.");
		return false;
	}
	
	if (len<2) {
		alert("Hostname is missing !");
		return false;
	}
	
	return true;
}


// calculations for Education Worksheet
function isInRange(value, lower, upper) {
	if ((parseFloat(value) >= parseFloat(lower)) && (parseFloat(value) <= parseFloat(upper)))
		return true;
	else
		return false;
}

function getInflationRate(rate, year) {
    if (isNumeric(rate) == false)
        return 0;
    if (isNumeric(year) == false)
        return 0;
	rate = rate / 100;
    return getRound(Math.pow( 1 + rate, year), 2);
}

function getSavFactors(rate, year){
    if (isNumeric(rate) == false)
        return 0;
    if (isNumeric(year) == false)
        return 0;
    rate = rate / 100 ;
    return getRound((Math.pow( 1 + rate, year ) - 1) / rate, 2);
}

function updateEducationCost(obj) {
    document.frmEducation.EducationCost.value = obj.value;
    recalculateAll();
    return true;
}

function updateExchangeValue() {
    var EducationCost = document.frmEducation.EducationCost.value;
    var ExchangeRate = document.frmEducation.ExchangeRate.value;
    var TodaysRinggit = 0;
	document.frmEducation.TodaysRinggit.value = "";
    if (isNumeric(EducationCost) && isNumeric(ExchangeRate)) {
    	TodaysRinggit = EducationCost * ExchangeRate;
    	if (isNumeric(TodaysRinggit))
    		document.frmEducation.TodaysRinggit.value = getRound(TodaysRinggit, 2);
    }
    return true;
}

function updateFutureRinggit() {
	var CollegeYears = document.frmEducation.CollegeYears.value;
	var TodaysRinggit = document.frmEducation.TodaysRinggit.value;
	var InflationRate = document.frmEducation.InflationRate.value;
	var FutureRinggit = "";
	document.frmEducation.FutureRinggit.value = "";
	if (isNumeric(InflationRate) && isNumeric(TodaysRinggit) && isNumeric(CollegeYears)) {
		FutureRinggit = TodaysRinggit * getInflationRate(InflationRate, CollegeYears);
		if (isNumeric(FutureRinggit))
			document.frmEducation.FutureRinggit.value = getRound(FutureRinggit,2);
	}
	return true;
}

function updateSavings() {
	var CollegeYears = document.frmEducation.CollegeYears.value;
	var EstimatedRate = document.frmEducation.EstimatedRate.value;
	var AnnualSavings = document.frmEducation.AnnualSavings.value;
	var FutureRinggit = document.frmEducation.FutureRinggit.value;
	if (isNumeric(EstimatedRate) == false || isNumeric(FutureRinggit) == false || isNumeric(CollegeYears) == false) {
		document.frmEducation.AnnualSavings.value = "";
		document.frmEducation.TotalSavings.value = "";
		document.frmEducation.MonthlySavings.value = "";
		return false;
	}
	annualsaving = parseFloat(FutureRinggit) / getSavFactors(EstimatedRate, CollegeYears);
	document.frmEducation.AnnualSavings.value = getRound(annualsaving, 2);
	document.frmEducation.MonthlySavings.value = getRound(annualsaving / 12, 2);
	document.frmEducation.TotalSavings.value = getRound(parseFloat(FutureRinggit) / getInflationRate( EstimatedRate, CollegeYears), 2);
	return true;
}

function recalculateAll() {
	if (isNumeric(document.frmEducation.InflationRate.value))
		if (isInRange(document.frmEducation.InflationRate.value, 0, 100) == false) {
			window.status = "Inflation Rate must in between 0 to 100";
			document.frmEducation.InflationRate.value = "";
			document.frmEducation.InflationRate.focus();
			alert(window.status);
			return false;
		}
	if (isNumeric(document.frmEducation.EstimatedRate.value))
		if (isInRange(document.frmEducation.EstimatedRate.value, 0, 100) == false) {
			document.frmEducation.EstimatedRate.value = "";
			window.status = "Estimate Rate of Return must in between 0 to 100";
			document.frmEducation.EstimatedRate.focus();
			alert(window.status);
			return false;
		}
	updateExchangeValue();
	updateFutureRinggit();
	updateSavings();
	return true;
}


// calculations for Education Worksheet

function getFutureMonthlyIncome(sMonthlyIncome , nYrToRetire){
    if (isNumeric(sMonthlyIncome) == false || isNumeric(nYrToRetire) == false)
		return "";
	return getRound(sMonthlyIncome * getInflationRate(4, nYrToRetire),2);
}

function getFutureAnnualIncome(sMonthlyIncome , nYrToRetire){
    if (isNumeric(sMonthlyIncome) == false || isNumeric(nYrToRetire) == false)
		return "";
	return getRound(sMonthlyIncome * getInflationRate(4, nYrToRetire)*12,2);
}

function getTotalAssests(sMonthlyIncome , nYrToRetire){
    if (isNumeric(sMonthlyIncome) == false || isNumeric(nYrToRetire) == false)
		return "";
	return getRound(sMonthlyIncome * getInflationRate(4, nYrToRetire) * 12 * 12.5,2) ;
}

function getInvestmentValue(nInvAmt , nInvRate ,nYrToRetire){
    if (isNumeric(nInvAmt) == false || isNumeric(nInvRate) == false || isNumeric(nYrToRetire) == false)
    	return "";
	return getRound(nInvAmt * getInflationRate(nInvRate,nYrToRetire),2);
}

function getEPFContribution(epfAnn,rate ,year){
	if(isNumeric(epfAnn) == false || isNumeric(rate) == false || isNumeric(year) == false)
		return "";
	return getRound(epfAnn * getSavFactors(rate, year),2);
}

function getTotalInvestmentValue(){
	var TotalInvset = 0;
	if(isNumeric(document.frmLifestyle.EPFValue.value) == true)
		TotalInvset = TotalInvset + parseFloat(document.frmLifestyle.EPFValue.value);
	if(isNumeric(document.frmLifestyle.FDValue.value) == true)
		TotalInvset = TotalInvset + parseFloat(document.frmLifestyle.FDValue.value);
	if(isNumeric(document.frmLifestyle.BondValue.value) == true)
		TotalInvset = TotalInvset + parseFloat(document.frmLifestyle.BondValue.value);
	if(isNumeric(document.frmLifestyle.InsuranceValue.value) == true)
		TotalInvset = TotalInvset + parseFloat(document.frmLifestyle.InsuranceValue.value);
	if(isNumeric(document.frmLifestyle.PropertyValue.value) == true)
		TotalInvset = TotalInvset + parseFloat(document.frmLifestyle.PropertyValue.value);
	if(isNumeric(document.frmLifestyle.UnitTrustValue.value) == true)
		TotalInvset = TotalInvset + parseFloat(document.frmLifestyle.UnitTrustValue.value);
	if(isNumeric(document.frmLifestyle.SharesValue.value) == true)
		TotalInvset = TotalInvset + parseFloat(document.frmLifestyle.SharesValue.value);
	if(isNumeric(document.frmLifestyle.OthersValue.value) == true)
		TotalInvset = TotalInvset + parseFloat(document.frmLifestyle.OthersValue.value);
	return getRound(TotalInvset,2);
}

function getFutureValue(nAsset , nInvest , nEpf){
	var nSave = 0;
	if(isNumeric(nAsset) == true)
		nSave = nAsset;
	if(isNumeric(nInvest) == true)
		nSave = nSave - nInvest;
	if(isNumeric(nEpf) == true)
		nSave = nSave - nEpf;
	return getRound(nSave,2);
}

function getRequiredAnnualSavings(nFutureSavings , rate , year){
	if( isNumeric(nFutureSavings)== false || isNumeric(rate)== false || isNumeric(year)== false)
		return "";
	return getRound(nFutureSavings / getSavFactors(rate, year),2);
}

function getRequiredMonthlySavings(nFutureSavings , rate , year){
	if( isNumeric(nFutureSavings)== false || isNumeric(rate)== false || isNumeric(year)== false)
		return "";
	return getRound(nFutureSavings / (getSavFactors(rate, year)*12),2);
}

function updatePage() {
	var nMonthlyIncome = document.frmLifestyle.RetireIncome.value;
	var nRetireYr = document.frmLifestyle.RetireYear.value;
	var nResult = "";

	//Calculate the assests
	nResult = getFutureMonthlyIncome(nMonthlyIncome , nRetireYr);
	document.frmLifestyle.FutureMonthlyIncome.value = nResult;

	nResult = getFutureAnnualIncome(nMonthlyIncome , nRetireYr);
	document.frmLifestyle.FutureAnnualIncome.value = nResult;

	nResult = getTotalAssests(nMonthlyIncome , nRetireYr);
	document.frmLifestyle.TotalAssets.value = nResult;

	document.frmLifestyle.TotalAssetsValue.value = document.frmLifestyle.TotalAssets.value;


	//Calculate the investment
	nResult = getInvestmentValue(document.frmLifestyle.EPF.value , document.frmLifestyle.EPFRate.value , nRetireYr);
	document.frmLifestyle.EPFValue.value = nResult;

	nResult = getInvestmentValue(document.frmLifestyle.FD.value , document.frmLifestyle.FDRate.value , nRetireYr);
	document.frmLifestyle.FDValue.value = nResult;

	nResult = getInvestmentValue(document.frmLifestyle.Bond.value , document.frmLifestyle.BondRate.value , nRetireYr);
	document.frmLifestyle.BondValue.value = nResult;

	nResult = getInvestmentValue(document.frmLifestyle.Insurance.value , document.frmLifestyle.InsuranceRate.value , nRetireYr);
	document.frmLifestyle.InsuranceValue.value = nResult;

	nResult = getInvestmentValue(document.frmLifestyle.Property.value , document.frmLifestyle.PropertyRate.value , nRetireYr);
	document.frmLifestyle.PropertyValue.value = nResult;

	nResult = getInvestmentValue(document.frmLifestyle.UnitTrust.value , document.frmLifestyle.UnitTrustRate.value , nRetireYr);
	document.frmLifestyle.UnitTrustValue.value = nResult;

	nResult = getInvestmentValue(document.frmLifestyle.Shares.value , document.frmLifestyle.SharesRate.value , nRetireYr);
	document.frmLifestyle.SharesValue.value = nResult;

	nResult = getInvestmentValue(document.frmLifestyle.Others.value , document.frmLifestyle.OthersRate.value , nRetireYr);
	document.frmLifestyle.OthersValue.value = nResult;

	document.frmLifestyle.TotalInvestment.value = getTotalInvestmentValue();
	document.frmLifestyle.EPFContribution.value = getEPFContribution(document.frmLifestyle.AnnualEPF.value,document.frmLifestyle.EPFReturnRate.value,nRetireYr);
	document.frmLifestyle.TotalInvestmentValue.value = document.frmLifestyle.TotalInvestment.value;
	document.frmLifestyle.FutureValue.value = getFutureValue(document.frmLifestyle.TotalAssetsValue.value,document.frmLifestyle.TotalInvestmentValue.value,document.frmLifestyle.EPFContribution.value);
	document.frmLifestyle.RequiredAnnualSavings.value = getRequiredAnnualSavings(document.frmLifestyle.FutureValue.value , document.frmLifestyle.EstimatedReturnRate.value , nRetireYr);
	document.frmLifestyle.RequiredMonthlySavings.value = getRequiredMonthlySavings(document.frmLifestyle.FutureValue.value , document.frmLifestyle.EstimatedReturnRate.value , nRetireYr);
}