var xmlhttp;
var step = 1, lstotal = 10, lscurrent = 3, valid, maxls = 10, maxloan = 10000000;
var params = new Array("propertyvalue", "mortgageamount", "mortgagetermyrs", "mortgagetermmts", "cursavings", "regsavings", "avgsavingrate", "avgcuraccbal", "curtaxband", "priority");
var LumpSum = new Array();
var lsmonthlist = new Array("Month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var lsfreqlist = new Array( "One-off", "Quarterly", "Annually"); // "Monthly",

function FormatValues(pre) {
	for(var i=0;i<params.length;i++) {
		id=pre+params[i];
		val=GetValue(id);
		if(val != "" && !isNaN(val)) SetValue("form",id,(val * 1));
	}
}

function ConstructParams() {
	var param="step="+step+"&lumpsumcount="+LumpSum.length+"&rate="+GetValue('rate')+"&audience="+GetValue('audience');
	for(var l=0;l<LumpSum.length;l++) {
		if(LumpSum[l][0] != "" && LumpSum[l][1] != "" && LumpSum[l][2] != "" && LumpSum[l][3]) {
			param+="&lsamount"+l+"="+LumpSum[l][0];
			param+="&lsmonth"+l+"="+LumpSum[l][1];
			param+="&lsyear"+l+"="+LumpSum[l][2];
			param+="&lsfrequency"+l+"="+LumpSum[l][3];
		}
	}
	for(var i=0;i<params.length;i++) param+="&"+params[i]+"="+GetValue(params[i]);
	return param;
}

function CalculateOffsetMortgage() {
	xmlhttp=null;
	if (window.XMLHttpRequest) {
		xmlhttp=new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	var url="/offsetcalculator/mortgagecalculator.html?time="+(new Date()).getTime();
	var parameters=ConstructParams();
	if(xmlhttp != null) {
		xmlhttp.onreadystatechange=DisplayResults;
		xmlhttp.open("POST",url,true);
		xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xmlhttp.setRequestHeader("Content-length",parameters.length);
		xmlhttp.setRequestHeader("Connection","close");
		xmlhttp.send(parameters);
	}
	else
		alert("Your browser does not support XMLHTTP.");
}

function GenerateFlashContent(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) {
	noflashmsg="No Flash";
	if (AC_FL_RunContent == 0) {
		alert("This page requires AC_RunActiveContent.js.");
	} else {
		param='normalVals='+arg1+'&termNormal='+arg2+'&offsetVals='+arg3+'&termOffset='+arg4;
		param+='&offsavingsVals='+arg5+'&reductionVals='+arg6+'&offpayVals='+arg7+'&monthlyPayment='+arg8+'&peakMonth='+arg9;
		param+='&loanamount='+GetValue('mortgageamount')+'&priority='+GetValue('priority')+"&audience="+GetValue("audience");

		//SetValue("span", "value", arg1+" : "+arg2+" : "+arg3+" : "+arg4+" : "+arg5+" : "+arg6+" : "+arg7+" : "+arg8);
		x = AC_FL_RunContent(
			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0',
			'width', '600',
			'height', '300',
			'src', '/offsetcalculator/swf/graph',
			'quality', 'high',
			'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
			'align', 'middle',
			'play', 'true',
			'loop', 'true',
			'scale', 'showall',
			'wmode', 'window',
			'devicefont', 'false',
			'id', 'graph',
			'bgcolor', '#ffffff',
			'name', 'bannerentry',
			'menu', 'true',
			'allowFullScreen', 'false',
			'allowScriptAccess','sameDomain',
			'movie', '/offsetcalculator/swf/graph',
			'wmode', 'transparent',
			'salign', '',
			'flashvars', param);
		return "<div class='borderline'></div>"+x;
	}
	return "";
}

function ProductYes() {
	SetValue("form","rate",r);
	DisplayFields();
	SetStep(3," hidefields");
	SetClass("results","cstep");
	SetClass("products","cstep yes");
}

function ProductNo() {
	ShowError("ermortgageamount");
	ShowError("lblLoanToValue2");
	SetClass("results","steps");
	SetClass("products","cstep no");
}

function DrawGraph(data) {
	if (typeof data[0].getElementsByTagName('RATE')[0] != "undefined") {
		r = data[0].getElementsByTagName('RATE')[0].firstChild.nodeValue;
		if(r > 0)
			ProductYes();
		else {
			ProductNo();
			return;
		}
	}
	else {
		ProductNo();
		return;
	}
	HideError("ermortgageamount");
	HideError("lblLoanToValue2");
	
	SetValue("span","result",data[0].getElementsByTagName('OFFSET_RESULT')[0].firstChild.nodeValue);
	nTerm="",oTerm="",mTerm="",osTerm="",opTerm="";

	if (typeof data[0].getElementsByTagName('NORMAL_TERM')[0] != "undefined") {
		for(i=0;i<data[0].getElementsByTagName('NORMAL_TERM')[0].childNodes.length;i++) {
			nTerm += (nTerm != "")?"|":"";
			if(typeof data[0].getElementsByTagName('NORMAL_TERM')[0].childNodes[i].firstChild != "undefined")
				nTerm += data[0].getElementsByTagName('NORMAL_TERM')[0].childNodes[i].firstChild.nodeValue
		}
	}

	if (typeof data[0].getElementsByTagName('OFFSET_TERM')[0] != "undefined") {
		for(i=0;i<data[0].getElementsByTagName('OFFSET_TERM')[0].childNodes.length;i++) {
			oTerm += (oTerm != "")?"|":"";
			if(typeof data[0].getElementsByTagName('OFFSET_TERM')[0].childNodes[i].firstChild != "undefined")
				oTerm += data[0].getElementsByTagName('OFFSET_TERM')[0].childNodes[i].firstChild.nodeValue
		}
	}

	if (typeof data[0].getElementsByTagName('REDUCTION_TERM')[0] != "undefined") {
		for(i=0;i<data[0].getElementsByTagName('REDUCTION_TERM')[0].childNodes.length;i++) {
			mTerm += (mTerm != "")?"|":"";
			if(typeof data[0].getElementsByTagName('REDUCTION_TERM')[0].childNodes[i].firstChild != "undefined")
				mTerm += data[0].getElementsByTagName('REDUCTION_TERM')[0].childNodes[i].firstChild.nodeValue
		}
	}

	if (typeof data[0].getElementsByTagName('OSAVINGS_TERM')[0] != "undefined") {
		for(i=0;i<data[0].getElementsByTagName('OSAVINGS_TERM')[0].childNodes.length;i++) {
			osTerm += (osTerm != "")?"|":"";
			if(typeof data[0].getElementsByTagName('OSAVINGS_TERM')[0].childNodes[i].firstChild != "undefined")
				osTerm += data[0].getElementsByTagName('OSAVINGS_TERM')[0].childNodes[i].firstChild.nodeValue
		}
	}

	if (typeof data[0].getElementsByTagName('OPAYMENT_TERM')[0] != "undefined") {
		for(i=0;i<data[0].getElementsByTagName('OPAYMENT_TERM')[0].childNodes.length;i++) {
			opTerm += (opTerm != "")?"|":"";
			if(typeof data[0].getElementsByTagName('OPAYMENT_TERM')[0].childNodes[i].firstChild != "undefined")
				opTerm += data[0].getElementsByTagName('OPAYMENT_TERM')[0].childNodes[i].firstChild.nodeValue
		}
	}

	if(data[0].getElementsByTagName('TOTAL_MONTHS')[0].firstChild)
		nMonths = data[0].getElementsByTagName('TOTAL_MONTHS')[0].firstChild.nodeValue;
	if(data[0].getElementsByTagName('OFFSET_MONTHS')[0].firstChild)
		oMonths = data[0].getElementsByTagName('OFFSET_MONTHS')[0].firstChild.nodeValue;
	if(data[0].getElementsByTagName('MONTHLY_PAYMENT')[0].firstChild)
		mPayment = data[0].getElementsByTagName('MONTHLY_PAYMENT')[0].firstChild.nodeValue;
	if(data[0].getElementsByTagName('PEAK_MONTH')[0].firstChild)
		peakMonth = data[0].getElementsByTagName('PEAK_MONTH')[0].firstChild.nodeValue;
	if(nMonths && oMonths && oTerm && nTerm && osTerm && mTerm && opTerm && mPayment)
		SetValue("span","flash" ,GenerateFlashContent(nTerm,nMonths,oTerm,oMonths,osTerm,mTerm,opTerm,mPayment,peakMonth));

	if(data[0].getElementsByTagName('STD_MORT_INT')[0].firstChild)
		StdMortgageInt = data[0].getElementsByTagName('STD_MORT_INT')[0].firstChild.nodeValue;
	if(data[0].getElementsByTagName('OFF_MORT_INT')[0].firstChild)
		OffMortgageInt = data[0].getElementsByTagName('OFF_MORT_INT')[0].firstChild.nodeValue;
	if(data[0].getElementsByTagName('SAVINGS_INT')[0].firstChild)
		SavingsInt = data[0].getElementsByTagName('SAVINGS_INT')[0].firstChild.nodeValue;
	if(data[0].getElementsByTagName('INT_BENEFIT')[0].firstChild)
		IntBenefit = data[0].getElementsByTagName('INT_BENEFIT')[0].firstChild.nodeValue;
	if(data[0].getElementsByTagName('INT_SAVED')[0].firstChild)
		IntSaved = data[0].getElementsByTagName('INT_SAVED')[0].firstChild.nodeValue;
	if(data[0].getElementsByTagName('INT_EARNED')[0].firstChild)
		IntEarned = data[0].getElementsByTagName('INT_EARNED')[0].firstChild.nodeValue;
	if(data[0].getElementsByTagName('ADDITION')[0].firstChild)
		Addition = data[0].getElementsByTagName('ADDITION')[0].firstChild.nodeValue;
	if(data[0].getElementsByTagName('EARLY_PAY')[0].firstChild)
		EarlyPay = data[0].getElementsByTagName('EARLY_PAY')[0].firstChild.nodeValue;

	var additions = new Array();
	var subadditions = new Array();
	if (typeof data[0].getElementsByTagName('ADDITIONS')[0] != "undefined") {
		for(i=0;i<data[0].getElementsByTagName('ADDITIONS')[0].childNodes.length;i++) {
			if(typeof data[0].getElementsByTagName('ADDITIONS')[0].childNodes[i].firstChild != "undefined")
				additions.push(data[0].getElementsByTagName('ADDITIONS')[0].childNodes[i].firstChild.nodeValue);
		}
	}
	if (typeof data[0].getElementsByTagName('SUBADDITIONS')[0] != "undefined") {
		for(i=0;i<data[0].getElementsByTagName('SUBADDITIONS')[0].childNodes.length;i++) {
			if(typeof data[0].getElementsByTagName('SUBADDITIONS')[0].childNodes[i].firstChild != "undefined")
				subadditions.push(data[0].getElementsByTagName('SUBADDITIONS')[0].childNodes[i].firstChild.nodeValue);
		}
	}
	SetValue("div","benefits",ConstructBenefits(additions,subadditions));
	if(IntSaved > 1000) {
		SetClass("results","cstep");
		SetClass("products","cstep yes");
	}
	else {
		SetClass("results","steps");
		SetClass("products","cstep no");
	}
}

function ShowAddition(o) {
	if(o.className != "") 
		o.className = "";
	else
		o.className = "more";
}

function ConstructBenefits(arr,sarr) {
	var t="<ul class='addition'>";
	for(var i=0;i<arr.length;i++)  {
		if(sarr[i] != "n/a") {
			t+="<li onclick='ShowAddition(this);'>" + arr[i];
			t+=ConstructInnerList(sarr[i]);
			t+="</li>";
		}
		else
			t+="<li class='dda'>" + arr[i] + "</li>";
	}
	t+="</ul>";
	return t;
}

function ConstructInnerList(arr) {
	return "<ul class='features'><li>"+arr+"</li></ul>";
}

function CheckRate(data) {
	if (typeof data[0].getElementsByTagName('RATE')[0] != "undefined") {
		r=data[0].getElementsByTagName('RATE')[0].firstChild.nodeValue;
		if(r > 0) {
			SetValue("form","rate",r);
			DisplayFields();
			SetStep(2);
		}
		else {
			if(GetValue('audience') == "INT")
				SetErrorMessage("emortgageamount","We do not currently have a product available for this loan to value.");
			else
				SetErrorMessage("emortgageamount","We do not currently have a product available for your loan to value.");
			SetClass("products","cstep no");
		}
	}
}

function DisplayResults() {
	if (xmlhttp.readyState==4) {
		if (xmlhttp.status==200) {
			//alert(xmlhttp.responseText);
			data=xmlhttp.responseXML.getElementsByTagName('OFFSET');
			if(data.length == 0 || (data[0].getElementsByTagName('STEP')[0].firstChild.nodeValue != step)) return;
			if(data[0].getElementsByTagName('ERROR')[0].firstChild) {
				alert(data[0].getElementsByTagName('ERROR')[0].firstChild.nodeValue);
				return;
			}
			switch(step) {
				case 3:
						DrawGraph(data);
					break;
				case 1:
						CheckRate(data);
					break;
			}
		} else
			alert("Problem retrieving data:" + xmlhttp.statusText);
	}
}

function SetStep(id,show) {
	HideLayer("help");
	SetClass("startagain","steps");
	if (typeof show == "undefined") show="";
	switch(id) {
		case 1:
			break;
		case 2:
				SetClass("startagain","cstep");
			break;
		case 3:
				SetClass("startagain","cstep");
			break;
		default:
			break;
	}
	SwapStep("step"+step,"step"+id,show);
	step=id;
}

function DisplayFields() {
	var propval= parseFloat(GetValue("propertyvalue"));
	var mortamt= parseFloat(GetValue("mortgageamount"));
	var loantoval=(mortamt/propval)*100;
	//for Step 1
	SetValue("span","lblLoanToValue1",FormatValue(loantoval,"percent"));
	SetValue("span","lblRate1","Woolwich "+FormatValue(GetValue("rate"),"percent"));
	SetValue("span","lblPropertyValue1",FormatValue(GetValue("propertyvalue"),"amount"));
	SetValue("span","lblMortgageAmount1",FormatValue(GetValue("mortgageamount"),"amount"));
	SetValue("span","lblTerm1",GetValue("mortgagetermyrs") + " y " + GetValue("mortgagetermmts") + " m");
	SetValue("span","lblRepaymentType1","Repayment");
	//for Step 2
	SetValue("span","lblLoanToValue2",FormatValue(loantoval,"percent"));
	SetValue("span","lblRate2","Woolwich "+FormatValue(GetValue("rate"),"percent"));
	SetValue("span","lblPropertyValue2",FormatValue(GetValue("propertyvalue"),"amount"));
	SetValue("span","lblMortgageAmount2",FormatValue(GetValue("mortgageamount"),"amount"));
	SetValue("span","lblTerm2",GetValue("mortgagetermyrs")+" y "+GetValue("mortgagetermmts")+" m");
	SetValue("span","lblRepaymentType2","Repayment");
	SetValue("span","lblCurSavings2",FormatValue(GetValue("cursavings"),"amount"));
	SetValue("span","lblRegSavings2",FormatValue(GetValue("regsavings"),"amount"));
	SetValue("span","lblAvgSavingRate2",FormatValue(GetValue("avgsavingrate"),"percent"));
	SetValue("span","lblAvgCurAccBal2",FormatValue(GetValue("avgcuraccbal"),"amount"));
	SetValue("span","lblTaxRate2",FormatValue(GetValue("curtaxband"),"nodecpercent"));
}

function Trim(str) { return str.replace(/^\s+|\s+$/g,''); }
function CheckEmpty(str) { str=Trim(str); return (str.length == 0) }
function CheckPattern(str,ptn) { var re=new RegExp(ptn,"g");return re.test(str); }

function CheckValue(val,min,max) { 
	if (typeof max == "undefined") max=999999999999;
	if(((val * 1) < (min * 1)) || ((val * 1) > (max * 1)))
		return false;
	else
		return true;
}

function CheckTerm(eyrs,emts,ayrs,equal) {
	if(typeof equal == "undefined") equal=true;
	val=(eyrs * 12)+(emts * 1);
	if(equal)
		return (val >= (ayrs*12));
	else
		return (val > (ayrs*12));
	return false;
}

function IsInsideTerm(lsyrs,lsmts,eyrs,emts) {
	val=(eyrs * 12)+(emts * 1);
	var lsDate=new Date(), termStart=new Date(), termEnd=new Date();
	termStart.setDate(1);
	termStart.setMonth(termStart.getMonth()+1);
	termEnd.setDate(1);
	termEnd.setMonth(termEnd.getMonth()+val);
	lsDate.setFullYear(lsyrs,lsmts-1,1);
	if(lsDate > termEnd || lsDate < termStart)
		return false;
	else
		return true;
}

function Step1Validation() {
	HideLayer("help");
	FormatValues("");
	valid=true;

	if(CheckEmpty(GetValue("propertyvalue")))
		SetErrorMessage("epropertyvalue","Please enter the property value.");
	else if(CheckPattern(GetValue("propertyvalue"),"[^0-9]"))
		SetErrorMessage("epropertyvalue","The value entered is not valid.");
	else if(!CheckPattern(GetValue("propertyvalue"),"^[0-9]{4,10}$"))
		SetErrorMessage("epropertyvalue","The value entered is too high/too low.");
	else
		HideError("epropertyvalue");

	if(CheckEmpty(GetValue("mortgageamount")))
		SetErrorMessage("emortgageamount","Please enter the amount borrowed.");
	else if(CheckPattern(GetValue("mortgageamount"),"[^0-9]"))
		SetErrorMessage("emortgageamount","The value entered is not valid.");
	else if(!CheckPattern(GetValue("mortgageamount"),"^[0-9]{4,10}$"))
		SetErrorMessage("emortgageamount","The value entered is too high/too low.");
	else if(!CheckValue(GetValue("mortgageamount"),5000,maxloan))
		SetErrorMessage("emortgageamount","The value entered is too high/too low.");
	else {
		var loantoval=(parseFloat(GetValue("mortgageamount"))/parseFloat(GetValue("propertyvalue")))*100;
		if(loantoval > GetValue("maxltv")) {
			if(GetValue("audience") == "INT")
				SetErrorMessage("emortgageamount","We do not currently have a product available for this loan to value.");
			else
				SetErrorMessage("emortgageamount","We do not currently have a product available for your loan to value.");
			SetClass("products","cstep no");
		}
		else {
			SetClass("products","steps");
			HideError("emortgageamount");
		}
	}

	if(CheckEmpty(GetValue("mortgagetermyrs")) || CheckEmpty(GetValue("mortgagetermmts")))
		SetErrorMessage("emortgageterm","Please enter the term of your mortgage.");
	else if(CheckPattern(GetValue("mortgagetermyrs"),"[^0-9]") || CheckPattern(GetValue("mortgagetermmts"),"[^0-9\s]"))
		SetErrorMessage("emortgageterm","The value entered is not valid.");
	else if(!CheckValue(GetValue("mortgagetermmts"),0,11))
		SetErrorMessage("emortgageterm","The value entered is too high/too low.");
	else if(!CheckTerm(GetValue("mortgagetermyrs"),GetValue("mortgagetermmts"),5,true))
		SetErrorMessage("emortgageterm","The minimum mortgage term should be 5 yrs.");
	else if(CheckTerm(GetValue("mortgagetermyrs"),GetValue("mortgagetermmts"),35,false))
		SetErrorMessage("emortgageterm","We do not offer mortgages for a term over 35 years.");
	else
		HideError("emortgageterm");

	return valid;
}

function Step1() {
	if(Step1Validation()) {
		SetClass("products","steps");
		HideError("mainerror1");
		CalculateOffsetMortgage();
	}
	else
		ShowError("mainerror1");
}

function Step2Validation() {
	HideLayer("help");
	FormatValues("");
	valid=true;

	if(!CheckPattern(GetValue("cursavings"),"^[0-9]{0,10}$"))
		SetErrorMessage("ecursavings","The value entered is not valid.");
	else
		HideError("ecursavings");

	if(!CheckPattern(GetValue("regsavings"),"^[0-9]{0,10}$"))
		SetErrorMessage("eregsavings","The value entered is not valid.");
	else
		HideError("eregsavings");

	if(CheckEmpty(GetValue("avgsavingrate")))
		SetErrorMessage("eavgsavingrate","Please enter the saving rate.");
	else if(!CheckPattern(GetValue("avgsavingrate"),"(^[0-9]{1,2}\.[0-9]{0,2}$)|^[0-9]{1,2}$"))
		SetErrorMessage("eavgsavingrate","The value entered is not valid.");
	else if(!CheckValue(GetValue("avgsavingrate"),0.01,99.99))
		SetErrorMessage("eavgsavingrate","The value entered is too hight/too low.");
	else if(!CheckValue(GetValue("avgsavingrate"),0.01,10)){
		if(GetValue("savratewarn") == "") {
			SetErrorMessage("eavgsavingrate","Please check this savings rate is correct. If yes, click next to proceed.");
			SetValue("form","savratewarn","1");
		}
	}
	else
		HideError("eavgsavingrate");

	if(CheckEmpty(GetValue("avgcuraccbal")))
		SetErrorMessage("eavgcuraccbal","Please enter an amount.");
	else if(CheckPattern(GetValue("avgcuraccbal"),"[^0-9]"))
		SetErrorMessage("eavgcuraccbal","The value entered is not valid.");
	else if(!CheckPattern(GetValue("avgcuraccbal"),"^[0-9]{1,9}$"))
		SetErrorMessage("eavgcuraccbal","The value entered is too high.");
	else if(!CheckValue(GetValue("avgsavingrate"),0))
		SetErrorMessage("eavgcuraccbal","The value must be greater than 0.");
	else
		HideError("eavgcuraccbal");

	if(CheckEmpty(GetValue("curtaxband")))
		SetErrorMessage("ecurtaxband","Please select one option.");
	else
		HideError("ecurtaxband");

	if(CheckEmpty(GetValue("priority")))
		SetErrorMessage("epriority","Please select one option.");
	else
		HideError("epriority");

	if(valid) SaveLumpSum();

	return valid;
}

function Step2() {
	if(Step2Validation()) {
		SetValue("form","savratewarn","");
		HideError("eravgsavingrate");
		HideError("mainerror2");
		SwapValues("","r");
		DisplayFields();
		SetStep(3," hidefields");
		SetValue("span","result","Please wait while the graph loads...");
		CalculateOffsetMortgage();
	}
	else {
		ShowError("mainerror2");
		return false;
	}
}

function ModifyStep3() {
	SwapValues("","r");
	DisplayFields();
	SetStep(3," showfields");
}

function Step3Validation() {
	HideLayer("help");
	FormatValues("r");
	valid=true;

	if(CheckEmpty(GetValue("rpropertyvalue")))
		ShowError("erpropertyvalue");
	else if(CheckPattern(GetValue("rpropertyvalue"),"[^0-9]"))
		ShowError("erpropertyvalue");
	else if(!CheckPattern(GetValue("rpropertyvalue"),"^[0-9]{4,10}$"))
		ShowError("erpropertyvalue");
	else
		HideError("erpropertyvalue");

	if(CheckEmpty(GetValue("rmortgageamount")))
		ShowError("ermortgageamount");
	else if(CheckPattern(GetValue("rmortgageamount"),"[^0-9]"))
		ShowError("ermortgageamount");
	else if(!CheckPattern(GetValue("rmortgageamount"),"^[0-9]{4,10}$"))
		ShowError("ermortgageamount");
	else if(!CheckValue(GetValue("rmortgageamount"),5000,maxloan))
		ShowError("ermortgageamount");
	else {
		var loantoval=(parseFloat(GetValue("rmortgageamount"))/parseFloat(GetValue("rpropertyvalue")))*100;
		SetValue("span","lblLoanToValue2",FormatValue(loantoval,"percent"));
		if(loantoval > GetValue("maxltv")) {
			ShowError("ermortgageamount");
			ShowError("lblLoanToValue2");
			SetClass("products","cstep no");
		}
		else {
			SetClass("products","steps");
			HideError("ermortgageamount");
			HideError("lblLoanToValue2");
		}
	}

	if(CheckEmpty(GetValue("rmortgagetermyrs")) && CheckEmpty(GetValue("rmortgagetermmts")))
		ShowError("ermortgageterm");
	else if(CheckPattern(GetValue("rmortgagetermyrs"),"[^0-9]") || CheckPattern(GetValue("rmortgagetermmts"),"[^0-9\s]"))
		ShowError("ermortgageterm");
	else if(!CheckValue(GetValue("rmortgagetermmts"),0,11))
		ShowError("ermortgageterm");
	else if(!CheckTerm(GetValue("rmortgagetermyrs"),GetValue("rmortgagetermmts"),5,true))
		ShowError("ermortgageterm");
	else if(CheckTerm(GetValue("rmortgagetermyrs"),GetValue("rmortgagetermmts"),35,false))
		ShowError("ermortgageterm");
	else
		HideError("ermortgageterm");

	if(CheckPattern(GetValue("rcursavings"),"[^0-9]"))
		ShowError("ercursavings");
	else
		HideError("ercursavings");

	if(CheckPattern(GetValue("rregsavings"),"[^0-9]"))
		ShowError("erregsavings");
	else
		HideError("erregsavings");

	if(CheckEmpty(GetValue("ravgsavingrate")))
		ShowError("eravgsavingrate");
	else if(!CheckPattern(GetValue("ravgsavingrate"),"(^[0-9]{1,2}\.[0-9]{0,2}$)|^[0-9]{1,2}$"))
		ShowError("eravgsavingrate");
	else if(!CheckValue(GetValue("ravgsavingrate"),0.01,99.99))
		ShowError("eravgsavingrate");
	else if(!CheckValue(GetValue("ravgsavingrate"),0.01,10)){
		if(GetValue("savratewarn") == "") {
			ShowError("eravgsavingrate");
			SetValue("form","savratewarn","1");
		}
	}
	else
		HideError("eravgsavingrate");

	if(CheckEmpty(GetValue("ravgcuraccbal")))
		ShowError("eravgcuraccbal");
	else if(CheckPattern(GetValue("ravgcuraccbal"),"[^0-9]"))
		ShowError("eravgcuraccbal");
	else if(!CheckPattern(GetValue("ravgcuraccbal"),"^[0-9]{1,9}$"))
		ShowError("eravgcuraccbal");
	else if(!CheckValue(GetValue("ravgsavingrate"),0))
		ShowError("eravgcuraccbal");
	else
		HideError("eravgcuraccbal");

	if(CheckEmpty(GetValue("rcurtaxband")))
		ShowError("ercurtaxband");
	else
		HideError("ercurtaxband");

	if(CheckEmpty(GetValue("rpriority")))
		ShowError("erpriority");
	else
		HideError("erpriority");

	if(valid) SaveLumpSum();

	return valid;
}

function Step3() {
	SetClass("results","cstep");
	SetClass("products","steps");
	SetValue("span","result","Please wait while the graph loads...");
	SetValue("span","flash","");
	if(Step3Validation()) {
		HideError("mainerror3");
		SetValue("form","savratewarn","");
		HideError("eravgsavingrate");
		SwapValues("r","");
		DisplayFields();		
		CalculateOffsetMortgage();
		return true;
	}
	else {
		ShowError("mainerror3");
		return false;
	}
}

function SwapValues(from,to) {
	for(var i=0; i < params.length; i++) SetValue("form",to+params[i],GetValue(from+params[i]));
}

function FormatValue(value,format) {
	switch(format) {
		case "nodecpercent" :
				value=parseFloat(value);
				return value.toFixed(0)+"%";
			break;
		case "percent" :
				value=parseFloat(value);
				return value.toFixed(2)+"%";
			break;
		case "amount" :
				return "&pound; "+formatCurrency(value);
			break;
		default :
				return value;
			break;
	}
}

function SetValue(tag,id,value) {
	switch(tag) {
		case "div"  :
		case "span" :
				if(GetObject(id)) GetObject(id).innerHTML=value;
			break;
		case "form" :
				SetFormElementValue(id,value);
			break;
		default:
				if(GetObject(id)) GetObject(id).value=value;
			break;
	}
}

function GetValue(id) {
	if (GetFormElementValue(id))
		return GetFormElementValue(id);
	else if(GetObject(id))
		return GetObject(id).value;
	else
		return "";
}

function GetObject(id) {
	return (document.all)?document.all[id]:document.getElementById(id);
}

function GetFormElementValue(id) {
	var ret_val=null;
	if (document.offsetDetailsForm.elements[id] != undefined) {
		if(document.offsetDetailsForm.elements[id].value != undefined)
			ret_val=document.offsetDetailsForm.elements[id].value;
		else if (document.offsetDetailsForm.elements[id].length != undefined) {
			for (var i=0; i < document.offsetDetailsForm.elements[id].length; i++) {
				if (document.offsetDetailsForm.elements[id][i].checked)
					ret_val=document.offsetDetailsForm.elements[id][i].value;
			}
		}
	}
	return ret_val;
}

function SetFormElementValue(id,val) {
	if (document.offsetDetailsForm.elements[id] != undefined) {
		if(document.offsetDetailsForm.elements[id].value != undefined)
			document.offsetDetailsForm.elements[id].value=val;
		else if (document.offsetDetailsForm.elements[id].length != undefined) {
			for (var i=0; i < document.offsetDetailsForm.elements[id].length; i++) {
				if (document.offsetDetailsForm.elements[id][i].value == val)
					document.offsetDetailsForm.elements[id][i].checked=true;
			}
		}
	}
}

function SwapStep(current,next,show) {
	if (typeof show == "undefined") show="";
	SetClass(current,"steps");
	SetClass(next,"cstep"+show);
}

function SetClass(id,classname) {
	if(GetObject(id)) GetObject(id).className=classname;
}

function LumpSumShow(e_event) {
	if(typeof e_event == "undefined") e_event=null;
	CreateLumpSumTable();
	if(e_event)
		ShowLayer(e_event,"lumpsum",3);
	else
		GetObject("lumpsum").style.display="block";
}

function LumpSumCreation() {
	if(LumpSum.length < lscurrent) {
		for(var x=LumpSum.length;x<lscurrent;x++) LumpSumAddRow(x);
	}
}

function LumpSumClose() {
	SaveLumpSum();
	if(valid) HideLayer('lumpsum');
}

function CreateLumpSumTable() {
	LumpSumCreation();
	var newTable="<table id='lstable'><thead><td>Amount:</td><td>Month:</td><td>Year:</td><td>Frequency:</td><td></td></thead><tbody>";
	for(var l=0;l<LumpSum.length;l++) {
		newTable+="<tr>";
		newTable+="<td>"+CreateLSControls("lsamount",l,LumpSum[l][0])+"</td>";
		newTable+="<td>"+CreateLSControls("lsmonth",l,LumpSum[l][1])+"</td>";
		newTable+="<td>"+CreateLSControls("lsyear",l,LumpSum[l][2])+"</td>";
		newTable+="<td>"+CreateLSControls("lsfrequency",l,LumpSum[l][3])+"</td>";
		newTable+="<td>&nbsp;<a href='#' class='lslink' onclick='LumpSumRemove(\""+l+"\");return false;'>X Remove</a></td>";
		newTable+="</tr>";
	}
	newTable+="<tr>";
	newTable+="<td colspan='5'>";
	if(LumpSum.length < maxls)
		newTable+="+ <a href='#' class='lslink' onclick='LumpSumNewRow();return false;' title='Add new payment now'>Add new payment now</a>";
	newTable+="</td>";
	newTable+="</tr>";
	newTable+="<tr>";
	newTable+="<td colspan='5'>";
	newTable+="<div class='lsformButtons'><a href='#' onclick='SaveLumpSum();return false;' title='Save changes'>";
	newTable+="<img alt='Save changes' src='/offsetcalculator/images/btn-save-changes.gif' /></a>";
	newTable+="</div>";
	newTable+="</td>";
	newTable+="</tr>";
	newTable+="</tbody></table>";
	SetValue("div","lumpsumtable",newTable);
}

function CreateLSControls(type,id,value) {
	var ret="";
	switch(type) {
		case "lsamount":
				ret="<div id='elsamount"+id+"'><input type='text' maxlength='10' id='lsamount"+id+"' name='lsamount"+id+"' value='"+value+"' /></div>";
			break;
		case "lsmonth":
				ret ="<div id='elsmonth"+id+"'><select id='lsmonth"+id+"' name='lsmonth"+id+"'>";
				for(var ml=0;ml<lsmonthlist.length;ml++) {
					ret+="<option value='"+ml+"' ";
					if(ml == value) ret+="selected='selected' ";
					ret+=">"+lsmonthlist[ml]+"</option>";
				}
				ret+="</select></div>";
			break;
		case "lsyear":
				ret ="<div id='elsyear"+id+"'><select id='lsyear"+id+"' name='lsyear"+id+"'>";
				var d=new Date();
				var start=d.getFullYear() * 1;
				var end=((d.getFullYear()*1)+36);
				ret+="<option value=''>YYYY</option>";
				for(var y=start; y <= end; y++) {
					ret+="<option value='"+y+"' ";
					if(y == value) ret+="selected='selected' ";
					ret+=">"+y+"</option>";
				}
				ret+="</select></div>";
			break;
		case "lsfrequency":
			ret ="<div id='elsfrequency"+id+"'><select id='lsfrequency"+id+"' name='lsfrequency"+id+"'>";
				for(var fl=0; fl < lsfreqlist.length; fl++) {
					ret+="<option value='"+lsfreqlist[fl]+"' ";
					if(lsfreqlist[fl] == value) ret+="selected='selected' ";
					ret+=">"+lsfreqlist[fl]+"</option>";
				}
				ret+="</select></div>";
			break;
	}
	return ret;
}

function LumpSumAddRow(id,val1,val2,val3,val4) {
	if (typeof val1 == "undefined") val1="";
	if (typeof val2 == "undefined") val2="";
	if (typeof val3 == "undefined") val3="";
	if (typeof val4 == "undefined") val4="";
	LumpSum[id]=new Array(val1,val2,val3,val4);
}

function LumpSumNewRow() {
	SaveLumpSumRows();
	if(lscurrent < maxls)
		LumpSumAddRow(lscurrent++);
	CreateLumpSumTable();
}

function LumpSumRemove(id) {
	var tLumpSum=new Array();
	for(var l=0; l < LumpSum.length; l++) {
		if(l != id) tLumpSum.push(LumpSum[l]);
	}
	LumpSum=new Array();
	for(var l=0; l < tLumpSum.length; l++) {
		LumpSum.push(tLumpSum[l]);
	}
	if(lscurrent > 3) lscurrent--;
	CreateLumpSumTable();
}

function SaveLumpSum() {
	valid=true;
	if(LumpSum.length == 0) return;
	SaveLumpSumRows();
	var errmsg="";
	for(var l=0; l < LumpSum.length; l++) {
		if(LumpSum[l][0] != "" || LumpSum[l][1] != "0" || LumpSum[l][2] != "") {
			if(CheckEmpty(LumpSum[l][0])) {
				errmsg+="Please enter an amount.<br />";
				ShowError("elsamount"+l);
			}
			else if(CheckPattern(LumpSum[l][0],"[^0-9]")) {
				errmsg+="The value entered is not valid.<br />";
				ShowError("elsamount"+l);
			}
			else if(!CheckPattern(LumpSum[l][0],"^[0-9]{1,10}")) {
				errmsg+="The value entered is too high.<br />";
				ShowError("elsamount"+l);
			}
			else if(!CheckValue(LumpSum[l][0],1)) {
				errmsg+="The value entered is not valid.<br />";
				ShowError("elsamount"+l);
			}
			else
				HideError("elsamount"+l);

			if(!CheckValue(LumpSum[l][1],1)) {
				errmsg+="Please select a Month.<br />";
				ShowError("elsmonth"+l);
			}
			else
				HideError("elsmonth"+l);

			if(CheckEmpty(LumpSum[l][2])) {
				errmsg+="Please select a Year.<br />";
				ShowError("elsyear"+l);
			}
			else
				HideError("elsyear"+l);

			if(!CheckEmpty(LumpSum[l][2]) && CheckValue(LumpSum[l][1])) {
				yrs="mortgagetermyrs";
				mts="mortgagetermmts";
				if(step > 2) {
					yrs="r"+yrs;
					mts="r"+mts;
				}
				if(!IsInsideTerm(LumpSum[l][2],LumpSum[l][1],GetValue(yrs),GetValue(mts))) {
					errmsg+="You have added a lump sum either before your loan would start or after your selected term would end. Please change your lump sum entry.";
					ShowError("elsmonth"+l);
					ShowError("elsyear"+l);
				}
				else {
					HideError("elsmonth"+l);
					HideError("elsyear"+l);
				}
			}

			if(CheckEmpty(LumpSum[l][3])) {
				errmsg+="Please select a frequency.<br />";
				ShowError("elsfrequency"+l);
			}
			else
				HideError("elsfrequency"+l);
		} else {
			HideError("elsamount"+l);
			HideError("elsmonth"+l);
			HideError("elsyear"+l);
			HideError("elsfrequency"+l);
		}
		if(errmsg != "")
			break;
	}
	if(valid) {
		HideError("mainerrorls");
		HideLayer('lumpsum');
	}
	else {
		SetErrorMessage("mainerrorls",errmsg);
		ShowError("mainerrorls");
		LumpSumShow();
	}
}

function SaveLumpSumRows() {
	for(var l=0; l < lscurrent; l++) {
		val=GetValue('lsamount'+l);
		if(val != "" && !isNaN(val))
			SetValue("form",'lsamount'+l,val);
		LumpSumAddRow(l,GetValue('lsamount'+l),GetValue('lsmonth'+l),GetValue('lsyear'+l),GetValue('lsfrequency'+l));
	}
}

function ShowHelp(e_event,tipitems,type) {
	if(typeof type == "undefined") type=1;
	var valArray=new Array();
	var index=null;
	var valclose=null;

	if(GetValue("audience") == "INT") {
		valArray[1] ="This is the value your client thinks that the property they wish to secure a mortgage on is worth.";
		valArray[2] ="This is the amount your client would like to borrow.";
		valArray[3] ="This is the period over which your client would like to repay their mortgage, in years and months. Minimum 5 years. Maximum 35 years.";
		valArray[4] ="This is the total amount (to the nearest &pound;1) your client already has in savings and plan to offset against their mortgage.";
		valArray[5] ="This is the total amount (to nearest &pound;1) your client plans to add to their offset savings account(s) on a monthly basis.";
		valArray[6] ="This is the average savings interest rate your client earns on their total savings balance.";
		valArray[7] ="This is the average balance remaining in your client's current account after their monthly expenses have been paid.";
		valArray[8] ="This is the total amount to the nearest &pound;1 and the frequency your client plans to add any lump sums to their offset savings account(s), if any. For example, if they are expecting a bonus or a pension payout.";
		valArray[9] ="Please select your current income tax band. For joint applications, select the tax band of the highest earner."
		valArray[10]="Please choose whether your client would like to use the interest saved with their offset to reduce their mortgage term, or to reduce their monthly repayments."
		valArray[11]="This is the value of your client's mortgage expressed as a percentage of the total value of their property.";
		valArray[12]="This is the best Woolwich offset mortgage rate which may be available to your client based on their Loan to Value";
		valArray[13]="This calculator uses a repayment basis calculation only, however part &amp; part or interest only options may be available from Woolwich.";
	}
	else {
		valArray[1] ="This is the value you think that the property you wish to secure a mortgage on is worth.";
		valArray[2] ="This is the amount you would like to borrow.";
		valArray[3] ="This is the period over which you would like to repay your mortgage, in years and months. Minimum 5 years. Maximum 35 years.";
		valArray[4] ="This is the total amount (to the nearest &pound;1) you already have in savings and plan to offset against your mortgage.";
		valArray[5] ="This is the total amount (to nearest &pound;1) you plan to add to your offset savings account(s) on a monthly basis.";
		valArray[6] ="This is the average savings interest rate you earn on your total savings balance.";
		valArray[7] ="This is the average balance remaining in your account after your monthly expenses have been paid.";
		valArray[8] ="This is the total amount to the nearest &pound;1 and the frequency you plan to add any lump sums to your offset savings account(s), if any. For example, if you are expecting a bonus or a pension payout.";
		valArray[9] ="Please select your current income tax band. For joint applications, select the tax band of the highest earner."
		valArray[10]="Please choose whether you would like to use the interest saved with your offset to reduce your mortgage term, or to reduce your monthly repayments."
		valArray[11]="This is the value of your mortgage expressed as a percentage of the total value of your property.";
		valArray[12]="This is the best Woolwich offset mortgage rate which may be available to you based on your Loan to Value.";
		valArray[13]="This calculator uses a repayment basis calculation only, however part &amp; part or interest options may be available from Woolwich. Subject to application";
	}
	idname=GetObject("tiptext");//document.getElementById("tiptext");
	idname.innerHTML=valArray[tipitems];//+valclose;
	ShowLayer(e_event,"help",type);
	return false;
}

function ShowLayer(e_event,id,help) {
	if(!e_event && window.event) e_event=window.event;
	if (e_event && window.event) {
		window.n_mouseY=e_event.clientY+document.body.scrollLeft+document.documentElement.scrollTop;
		window.n_mouseX=e_event.clientX+document.body.scrollLeft+document.documentElement.scrollLeft;
	} else {
		window.n_mouseY=e_event.pageY;
		window.n_mouseX=e_event.pageX;
	}
	layer=GetObject(id);
	layer.style.display="block";
	if(help == 1) {
		layer.style.top=(window.n_mouseY-layer.offsetHeight-10)+"px";
		layer.style.left=(window.n_mouseX-20)+"px";
	}
	else if(help == 2) {
		layer.style.top=(window.n_mouseY-layer.offsetHeight-10)+"px";
		layer.style.left=(window.n_mouseX-10-layer.offsetWidth)+"px";
	}
	else {
		layer.style.top=(window.n_mouseY+10)+"px";
		layer.style.left=(window.n_mouseX-175)+"px";
	}
}

function HideLayer(id) { GetObject(id).style.display="none"; }

function ShowError(id,cls) {
	if(typeof cls == "undefined") cls="showError";
	valid=false;
	GetObject(id).className=cls;
}

function HideError(id) { GetObject(id).className=""; }

function SetErrorMessage(id,msg,opt) {
	if(typeof opt == "undefined") opt="showError";
	o=GetObject(id).getElementsByTagName('div');
	for(var e=0; e < o.length; e++) {
		if(o[e].className == "error") {
			o[e].innerHTML=msg;
			ShowError(id,opt);
		}
	}
}

function ShowAssumption(){
	HideLayer("help");
	if(GetObject('assumptions').className != "steps")
		GetObject('assumptions').className="steps";
	else
		GetObject('assumptions').className="cstep";
}

function popUpWindow(strURL,strName,strProperties) {
	if (window.focus)
		window.open(strURL,strName,strProperties);
	else
		alert("This site uses JavaScript - please allow your browser to run this script");
}

function formatCurrency(num) {
	if(isNaN(num)) num=0;
	sign=(num == (num=Math.abs(num)));
	num=Math.floor(num*100+0.50000000001);
	num=Math.floor(num/100).toString();
	for (var i=0; i < Math.floor((num.length-(1+i))/3); i++)
		num=num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
	return (num);
}