var xmlhttp;
var step = 1, lstotal = 10, lscurrent = 3, valid, maxls = 10, maxloan = 10000000;
var params = new Array("propertyvalue", "mortgageamount", "mortgagetermyrs", "mortgagetermmts", "repaymentType", "interestonlyamt", "repaymentamount", "interestrate", "ownRateAmt", "cursavings", "regsavings", "avgsavingrate", "avgcuraccbal", "curtaxband", "priority");
var LumpSum = new Array();
var ErrorMessage = new Array();
var lsmonthlist = new Array("Month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var mortType= new Array(); mortType["repayment"]="repay"; mortType["intOnly"]="intOnly"; mortType["partAndPart"]="partPart";

var lsfreqlist = new Array( "One-off", "Quarterly", "Annually"); // "Monthly",
var newTable = "" , newPAPTable = "", newRateTable = "", ioa="", pap="", ownRate="", ir=0;

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

function ConstructParams() {
	var param="step="+step+"&lumpsumcount="+LumpSum.length+"&rate="+GetValue('rate')+"&audience="+GetValue('audience')+"&interestonlyamt="+ioa+"&repaymentamount="+pap;
	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")+"&mortgageType="+mortType[GetValue('repaymentType')];
		
		//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/graph09',
			'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/graph09',
			'wmode', 'transparent',
			'salign', '',
			'flashvars', param);
		return "<div class='borderline'></div>"+x;
	}
	return "";
}

function ProductYes() {
	SetValue("form","rate",r);
	DisplayFields();
	SetStep(3," showfields");
	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") {
		//console.log(data);
		/*if(GetObject("yourRate").checked == true) {
			r = GetValue("ownRateAmt");
		}
		else*/
		if(ownRate >0) {
			r = ownRate;	
		}
		else {
			r = data[0].getElementsByTagName('RATE')[0].firstChild.nodeValue;
		}			
		SetValue("form","rate",r);
		
		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));
	SetClass("results","cstep");
	//if(IntSaved > 1000) {
	if(IntSaved > 1) {	
		//SetClass("results","cstep");
		SetClass("products","cstep yes");
	}
	else {
		//SetClass("results","cstep");
		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 class='ddamore'>" + arr[i];
			if(sarr[i]!="Yes") 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);
		else if(GetObject("yourRate").checked == true) 
			SetValue("form","rate",GetValue("ownRateAmt"));
		
		//else
		//if(r > 0) {
		//SetValue("form","rate",r);
			DisplayFields();
			SetStep(2);
			if(r < 0) SetClass("products","cstep no");
		//}		
		
	}
}

function DisplayResults() {
	if (xmlhttp.readyState==4) {
		if (xmlhttp.status==200) {
			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) {
	HideAllLayer(2);
	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;
	var repaymentype = GetValue("repaymentType");
	if(GetObject("yourRate").checked == true)
		var ownrateamt = GetValue("ownRateAmt");
	else
		var ownrateamt = 0;
		
	//for Step 1
	SetValue("span","lblLoanToValue1",Math.round(loantoval)+"%");
	
	if( ownrateamt > 0 )
		SetValue("span","lblRate1",FormatValue(GetValue("rate"),"percent"));
	else
		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");
	if(repaymentype == "repayment")
		SetValue("span","lblRepaymentType1","Repayment");
	else if(repaymentype == "intOnly")
		SetValue("span","lblRepaymentType1","Interest only");
	else if(repaymentype == "partAndPart")
		SetValue("span","lblRepaymentType1","Part and Part");
	//for Step 2
	SetValue("span","lblLoanToValue2",Math.round(loantoval)+"%");
	if(ownRate>0)
		SetValue("span","lblRate2",FormatValue(ownRate,"percent"));
	else if( GetValue("lowRate")!=GetValue("rate") )	
		SetValue("span","lblRate2",FormatValue(GetValue("rate"),"percent"));
	else	
		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) { 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() {
	HideAllLayer(1);
	FormatValues("");
	GetErrorMessage();
	valid=true;
	
	if(CheckEmpty(GetValue("propertyvalue")))
		SetErrorMessage("epropertyvalue",ErrorMessage[1]);
	else if(CheckPattern(GetValue("propertyvalue"),"[^0-9]"))
		SetErrorMessage("epropertyvalue","Please enter a number without character or spaces.");
	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",ErrorMessage[2]);
	else if(CheckPattern(GetValue("mortgageamount"),"[^0-9]"))
		SetErrorMessage("emortgageamount","Please enter a number without character or spaces.");
	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 		
		HideError("emortgageamount");
	
		
	if(GetValue("repaymentType") == "partAndPart") {
		//if( CheckEmpty(GetValue("interestonlyamt")) || CheckEmpty(GetValue("repaymentamount")) ){
			if(CheckEmpty(GetValue("interestonlyamt")))
				SetErrorMessage("einterestonlyamt", "Please enter your Interest only amount.");
			else if(CheckPattern(GetValue("interestonlyamt"), "[^0-9]"))
				SetErrorMessage("einterestonlyamt", "Please enter a number without character or spaces.");
			else if(!CheckPattern(GetValue("interestonlyamt"), "^[0-9]{4,10}$"))
				SetErrorMessage("einterestonlyamt", "The value entered is too high/too low.");
			else
				HideError("einterestonlyamt");	
			
			if(CheckEmpty(GetValue("repaymentamount")))
				SetErrorMessage("erepaymentamount", "Please enter your repayment amount.");
			else if(CheckPattern(GetValue("repaymentamount"), "[^0-9]"))
				SetErrorMessage("erepaymentamount", "Please enter a number without character or spaces.");
			else if(!CheckPattern(GetValue("repaymentamount"), "^[0-9]{4,10}$"))
				SetErrorMessage("erepaymentamount", "The value entered is too high/too low.");
			else
				HideError("erepaymentamount");	
				
		//}		
	}	
	
	if(CheckEmpty(GetValue("mortgagetermyrs")) || CheckEmpty(GetValue("mortgagetermmts")))
		SetErrorMessage("emortgageterm",ErrorMessage[4]);
	else if(CheckPattern(GetValue("mortgagetermyrs"),"[^0-9]") || CheckPattern(GetValue("mortgagetermmts"),"[^0-9\s]"))
		SetErrorMessage("emortgageterm","For this illustration, we'll only provide results on mortgage terms between 5 and 35 years.");
	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","For this illustration, we'll only provide results on mortgage terms between 5 and 35 years.");
	else if(CheckTerm(GetValue("mortgagetermyrs"),GetValue("mortgagetermmts"),35,false))
		SetErrorMessage("emortgageterm","For this illustration, we'll only provide results on mortgage terms between 5 and 35 years.");
	else
		HideError("emortgageterm");

	if( GetObject("ownRateAmt").disabled == false){
		if(CheckEmpty(GetValue("ownRateAmt")))
			SetErrorMessage("einterestyourratediv",ErrorMessage[5]);
		else if (CheckPattern(GetValue("ownRateAmt"), "[^0-9\.]"))
			SetErrorMessage("einterestyourratediv","Please enter a valid number without character or spaces.");
		else if(!CheckPattern(GetValue("ownRateAmt"),"(^[0-9]{1,2}\.[0-9]{0,2}$)|^[0-9]{1,2}$"))
			SetErrorMessage("einterestyourratediv","Please enter a valid interest rate.");
		else if(!CheckValue(GetValue("ownRateAmt"),0.01,99.99))
			SetErrorMessage("einterestyourratediv","The value entered is too high/too low.");		
		else
			HideError("einterestyourratediv");				
	}
	
	return valid;
}

function Step1() {
	if(Step1Validation()) {
		SetClass("products","steps");
		HideError("mainerror1");
		CalculateOffsetMortgage();
		if(GetValue("repaymentType") == "partAndPart") {
			ioa = GetValue("interestonlyamt");
			pap	= GetValue("repaymentamount");
		}
		//if(GetValue("yourRate")==2 && GetValue("ownRateAmt")>0)
		if( GetObject("yourRate").checked == true && GetValue("ownRateAmt")>0 )
			ownRate = GetValue("ownRateAmt");
		else 
			ownRate = 0;		
	}
	else
		ShowError("mainerror1");
}

function Step2Validation() {
	HideAllLayer(2);
	FormatValues("");
	valid=true;

	if(!CheckPattern(GetValue("cursavings"),"^[0-9]{0,10}$"))
		SetErrorMessage("ecursavings","Please enter a number without character or spaces.");
	else
		HideError("ecursavings");

	if(!CheckPattern(GetValue("regsavings"),"^[0-9]{0,10}$"))
		SetErrorMessage("eregsavings","Please enter a number without character or spaces.");
	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","Please enter a valid number without character or spaces.");
	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","Please enter a number without character or spaces.");
	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 current account value cannot be less 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," showfields");
		SetValue("span","result","Please wait while the graph loads...");
		if(GetValue("repaymentType") == "partAndPart") SetClass("eamendPartAndPart","rowcontainer srepay");
		if(GetValue("rpriority")==2) {
			SetClass("Rad1","radio2_tabslefton");
			SetClass("Rad2","radio2_tabsrightoff");	
		}
		CalculateOffsetMortgage();
	}
	else {
		ShowError("mainerror2");
		return false;
	}
}

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

function Step3Validation() {
	HideAllLayer(1);
	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 {
		 HideError("ermortgageamount");  	
		/*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(GetValue("rrepaymentType") == "partAndPart"){
		if(!CheckEmpty( GetValue("rinterestonlyamt"))) ioa = GetValue("rinterestonlyamt");
		if(!CheckEmpty( GetValue("rrepaymentamount"))) pap	= GetValue("rrepaymentamount");
		
		if(CheckEmpty(ioa) && CheckEmpty(pap) ){
			PartnadPartShow("");
			ShowError("srinterestonlyamt");
			ShowError("srrepaymentamount");	
		} 
		else if(GetObject("lumpsum").style.display== "block"){
			SavePAP();
			if(valid){
				HideError("srinterestonlyamt");
				HideError("srrepaymentamount");
				GetObject("lumpsum").style.display="none";
			}
		}		
	} else {
		SetValue("", "rinterestonlyamt", "");
		SetValue("", "rrepaymentamount", "");	
	}
	if(valid) {
		if(GetObject("wonRatePop").style.display== "block"){
			SaveRate();			
		}
	}
	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","");
		if(ioa!="" && pap!="") {
			SetValue("form","interestonlyamt",ioa);
			SetValue("form","repaymentamount",pap);	
		}		
		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) {
	try{ //for IE-6 design issue - dropdown overlap
		GetObject("curtaxband").style.visibility = "hidden";
		GetObject("rcurtaxband").style.visibility = "hidden";
	}catch( excep ){ }
	if(typeof e_event == "undefined") e_event=null;
	CreateLumpSumTable(e_event);
	SetValue("span","lumpsumHead","Add a lump sum");
	SetValue("div","lumpsumClose",'<a href="#" onclick="LumpSumClose();return false;">Close</a>');
	if(e_event==1)
		ShowLayer("","lumpsum",9);
	else
		ShowLayer("","lumpsum",10);
	/*if(e_event)
		ShowLayer(e_event,"lumpsum",9);
	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(s) {
	LumpSumCreation();
	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("+s+");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(s) {
	valid=true;
	try{ //for IE-6 design issue - dropdown overlap
		GetObject("curtaxband").style.visibility = "visible";
		GetObject("rcurtaxband").style.visibility = "visible";
	}catch( excep ){ }
	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(s);
	}
}

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,aid,dis) {
	if(typeof type == "undefined") type=1;
	if(typeof aid == "undefined") aid="";
	else aid=(dis=='m')?aid+"#"+dis:aid;
	
	HideAllLayer(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 their property is currently worth.";
		valArray[2] ="This is the amount your client would like to borrow. Minimum mortgage amount from Woolwich is £5000.";
		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 £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 would normally earn on their total savings balance if they were not offset against their mortgage.";
		valArray[7] ="This is the average balance in your client's current account(s).";
		valArray[8] ="This is any Future Additional Savings your client is expecting to offset their mortgage with e.g. a bonus, inheritance or a pension payout. Please enter the total amount to the nearest £1000 and the frequency your client plans to add them.";
		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]="Loan To Value (LTV). This is the ratio of borrowing against the value of your client's property e.g. If their property value is £100,000 and mortgage amount is £50,000, LTV will be 50%.";
		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.";
		valArray[14]="Repayment types are the different ways your client can pay their mortgage. With a <b>Repayment only mortgage</b>, your client's monthly payments cover both interest and capital at the same time. At the end of their mortgage term the amount your client borrowed including interest is paid in full, provided they make all their repayments on time. With an <b>Interest Only mortgage</b>, your client's monthly payments only cover the interest on the mortgage. Their mortgage balance remains constant and it's down to them how they choose to repay the full amount. At the end of the mortgage term, the amount your client borrowed will need to be repaid in full, so they will need a suitable repayment vehicle in place to do this.<br><b>Part Interest and Part Repayment</b> is a combination of interest only and repayment only. Please confirm how much of your client's mortgage you would like on each type of repayment. The two amounts must add up to the total mortgage amount.";
		valArray[15]="Part Interest and Part Repayment is a combination of interest only and repayment only. Please confirm how much of your client's mortgage you would like on each type of repayment. The two amounts must add up to the total mortgage amount.";
		valArray[16]="Part Interest and Part Repayment is a combination of interest only and repayment only. Please confirm how much of your client's mortgage you would like on each type of repayment. The two amounts must add up to the total mortgage amount.";
		valArray[17]="This interest rate is the lowest Woolwich Offset mortgage rate which is currently available to your client based on their LTV. Your client can choose to enter their own preferred rate for illustration purpose only but we may not have a mortgage available at this rate.";
		valArray[18]="You can choose to enter your client's preferred interest rate for illustration purpose only but we may not have a mortgage available at this rate.";
		valArray[19]="Repayment types are the different ways your client can pay their mortgage. <b>With a Repayment only mortgage</b>, your client's monthly payments cover both interest and capital at the same time. At the end of their mortgage term the amount your client borrowed including interest is paid in full, provided they make all their repayments on time. With an <b>Interest Only mortgage</b>, your client's monthly payments only cover the interest on the mortgage. Their mortgage balance remains constant and it's down to them how they choose to repay the full amount. At the end of the mortgage term, the amount your client borrowed will need to be repaid in full, so they will need a suitable repayment vehicle in place to do this.<br/><b>Part Interest and Part Repayment</b> is a combination of interest only and repayment only. Please confirm how much of your client's mortgage you would like on each type of repayment. The two amounts must add up to the total mortgage amount.";
		valArray[20]="You can choose to enter your own preferred interest rate for illustration purpose only but we may not have a mortgage available at this rate.";
		valArray[21]="This is the average savings interest rate you would normally earn on your total savings balance if they were not offset.";
	}
	else {
		valArray[1] ="This is how much you think that your property is currently worth.";
		valArray[2] ="This is the amount you would like to borrow. Minimum mortgage amount from Woolwich is £5000";
		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 any future additional savings you are expecting to offset your mortgage with e.g. a bonus, inheritance or a pension payout. Please enter the total amount to the nearest &pound;1000 and the frequency you plan to add them.";
		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]="Loan To Value (LTV). This is the ratio of borrowing against value of your property value e.g. If your property value is &pound;100,000 and mortgage amount is &pound;50,000, LTV will be 50%";
		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";
		valArray[14]="Repayment types are the different ways you can pay your mortgage off. <b>With a Repayment mortgage</b>, your monthly payments cover both interest and capital at the same time. At the end of your mortgage term the amount you borrowed including interest is paid in full, provided you make all your repayments on time. <b>With an Interest Only mortgage</b>, your monthly payments only cover the interest on the mortgage. Your mortgage balance remains constant and it's up to you how you choose to repay the full amount. At the end of the mortgage term, the amount you borrowed will need to be repaid in full, so you will need a suitable repayment vehicle in place to do this.<br><b>Part Interest and Part Repayment</b> is a combination of interest only and repayment only. Please confirm how much of the mortgage amount you require on each type of repayment. The two amounts must add up to the total mortgage amount.";
		valArray[15]="Part Interest and Part Repayment is a combination of interest only and repayment only. Please confirm how much of the mortgage amount you require on each type of repayment. The two amounts must add up to the total mortgage amount.";
		valArray[16]="Part Interest and Part Repayment is a combination of interest only and repayment only. Please confirm how much of the mortgage amount you require on each type of repayment. The two amounts must add up to the total mortgage amount.";
		valArray[17]="This interest rate is the lowest Woolwich offset mortgage rate which is currently available to you based on the ratio of borrowing against the value of your property. You can choose below to enter your own preferred rate for illustration purpose only but we may not have a mortgage available at this rate.";
		valArray[18]="You can choose to enter your own preferred interest rate for illustration purpose only but we may not have a mortgage available at this rate.";
		valArray[19]="Repayment types are the different ways you can pay your mortgage off. <b>With a Repayment mortgage</b>, your monthly payments cover both interest and capital at the same time. At the end of your mortgage term the amount you borrowed including interest is paid in full, provided you make all your repayments on time. <b>With an Interest Only mortgage</b>, your monthly payments only cover the interest on the mortgage. Your mortgage balance remains constant and it's up to you how you choose to repay the full amount. At the end of the mortgage term, the amount you borrowed will need to be repaid in full, so you will need a suitable alternative repayment vehicle in place to do this.<br/><b>Part Interest and Part Repayment</b> is a combination of interest only and repayment only. Please confirm how much of the mortgage amount you require on each type of repayment. The two amounts must add up to the total mortgage amount.";
		valArray[20]="You can choose to enter your own preferred interest rate for illustration purpose only but we may not have a mortgage available at this rate.";
		valArray[21]="This is the average savings interest rate you would normally earn on your total savings balance if they were not offset.";
	}
	if( (tipitems==14) || (tipitems==19) ){
		idname=GetObject("tiptextR");
		dname = "helpext";
		if(tipitems==19) GetObject("rcurtaxband").style.visibility = "hidden"; //for IE 6issue
	}
	else if( (tipitems==15) || (tipitems==16) ){
		idname=GetObject("tiptext");//document.getElementById("tiptext");
		dname = "help";	
		GetObject("rcurtaxband").style.visibility = "hidden"; //for IE 6issue
	}
	else{
		idname=GetObject("tiptext");//document.getElementById("tiptext");
		dname = "help";	
		GetObject("rcurtaxband").style.visibility = "visible"; //for IE 6issue
	}
	idname.innerHTML=valArray[tipitems];//+valclose;
	ShowLayer(e_event,dname,type,aid);
	return false;
}


function ShowLayer(e_event,id,help,aid) {
	if(typeof aid == "undefined") aid="";
	
	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) {
		if(aid !="") {
			var arr=aid.split("#");
			pos = getPos(document.getElementById(arr[0]));
			if(arr[1]=="m"){
				layer.style.top=(pos[1]-layer.offsetHeight+27)+"px";
				layer.style.left=(pos[0]+155)+"px";	
			}
			else{	
				layer.style.top=(pos[1]-layer.offsetHeight-3)+"px";
				layer.style.left=(pos[0]+5)+"px";	
			}
		} 
		else {			
			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 if(help == 4) {
		HideAllLayer(2);
		pos = getPos(GetObject("repaymenttypediv"));
		layer.style.top=(pos[1]-50)+"px";
		layer.style.left=(pos[0]+420)+"px";
	}
	else if(help == 5) {
		HideAllLayer(2);
		layer.style.top=399+"px";
		layer.style.left=663+"px";
	}
	else if(help == 6) {
		HideAllLayer(2);
		pos = getPos(GetObject("mainerrorls"));
		layer.style.top=(pos[1]-layer.offsetHeight+50)+"px";
		layer.style.left=(pos[0]+265)+"px";		
	}
	else if(help == 7) {
		pos = getPos(GetObject("ownrateamend"));
		layer.style.top=(pos[1]+15)+"px";
		layer.style.left=pos[0]+"px";	
	}
	else if(help == 8) {
		pos = getPos(GetObject("amendPartAndPart"));
		layer.style.top=(pos[1]+15)+"px";
		layer.style.left=pos[0]+"px";	
	}
	else if(help == 9) {
		pos = getPos(GetObject("lumpsumLink1"));
		layer.style.top=(pos[1]+15)+"px";
		layer.style.left=(pos[0]-20)+"px";	
	}
	else if(help == 10) {
		pos = getPos(GetObject("lumpsumLink2"));
		layer.style.top=(pos[1]+25)+"px";
		layer.style.left=(pos[0]-110)+"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";
	//if(id=="helpext")
	GetObject("rcurtaxband").style.visibility = "visible"; //for IE 6issue
}

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(){
	HideAllLayer(2);
	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);
}

function showHideAmnt(did){
	
	if(did==1){
		id=GetValue('repaymentType');
		if(id=="partAndPart"){
			SetClass("interestonlyAmnt","formRow formRowExt srepay");
			SetClass("repaymentamountAmnt","formRow formRowExt srepay");		
		} else {
			SetValue("form", "interestonlyamt", "");	
			SetValue("form", "repaymentamount", "");		
			ioa = "";
			pap = "";
			SetClass("interestonlyAmnt","formRow formRowExt hrepay");
			SetClass("repaymentamountAmnt","formRow formRowExt hrepay");		
		}
	}
	else if(did==2){
		id=GetValue("rrepaymentType");
		if(id=="partAndPart")
			SetClass("eamendPartAndPart","rowcontainer srepay");				
		else{
			ioa = "";
			pap = "";
			SetClass("eamendPartAndPart","rowcontainer hrepay");
			//HideError("srinterestonlyamt");
			//HideError("srrepaymentamount");
			GetObject("lumpsum").style.display="none";
			HideError("mainerror3");
		}
	}
}

function validatePrptAmt(propVal,errorDiv){
	valid=true;
	
	if(CheckPattern(propVal,"[^0-9]"))
		SetErrorMessage(errorDiv,"Please enter a number without character or spaces.");
	else if(!CheckPattern(propVal,"^[0-9]{4,10}$"))
		SetErrorMessage(errorDiv,"The value entered is too high/too low.");
	else
		HideError(errorDiv);
		
	return valid;	
}

function validateMortAmt(mortAmt, errorDiv){	
	valid=true;
	
	if(CheckPattern(mortAmt,"[^0-9]"))
		SetErrorMessage(errorDiv,"Please enter a number without character or spaces.");
	else if(!CheckPattern(mortAmt,"^[0-9]{4,10}$"))
		SetErrorMessage(errorDiv,"The value entered is too high/too low.");
	else if(!CheckValue(mortAmt,5000,maxloan))
		SetErrorMessage(errorDiv,"The value entered is too high/too low.");
	else 
		HideError(errorDiv);
		
	return valid;	
}

function validateIntnly(IntOnlyAmt,IntOnlyeDiv,ma){
	valid=true;
	
	if(CheckPattern(IntOnlyAmt,"[^0-9]"))
		SetErrorMessage(IntOnlyeDiv,"Please enter a number without character or spaces.");
	else if(!CheckPattern(IntOnlyAmt,"^[0-9]{4,10}$"))
		SetErrorMessage(IntOnlyeDiv,"The value entered is too high/too low.");	
	else if(IntOnlyAmt > Math.abs(ma))	
		SetErrorMessage(IntOnlyeDiv,"Please enter a number less than the mortgage amount.");	
	else 
		HideError(IntOnlyeDiv);
		
	return valid;	
}

function validatePayment(repayAmt,repayeDiv,ma ){
	valid=true;
	
	if(CheckPattern(repayAmt,"[^0-9]"))
		SetErrorMessage(repayeDiv,"Please enter a number without character or spaces.");
	else if(!CheckPattern(repayAmt,"^[0-9]{4,10}$"))
		SetErrorMessage(repayeDiv,"The value entered is too high/too low.");
	else if(repayAmt > Math.abs(ma))
		SetErrorMessage(repayeDiv,"Please enter a number less than the mortgage amount.");
	else 
		HideError(repayeDiv);
		
	return valid;	
}

function valMortgageIO(){
	FormatValues("");
	var mortAmt		= GetValue("mortgageamount");
	var IntOnlyAmt	= GetValue("interestonlyamt");
	var repayAmt	= GetValue("repaymentamount");
	var diff 		= 0;
	
	if( !CheckEmpty(mortAmt) && !CheckEmpty(IntOnlyAmt) ) {	
		if( validateMortAmt(mortAmt,"emortgageamount") && validateIntnly(IntOnlyAmt,"einterestonlyamt",mortAmt) ) {
			HideError("mainerror1");
			if(repayAmt>0){
				diff =	mortAmt-IntOnlyAmt-repayAmt;
				if(Math.abs(diff) >0) {
					idname=GetObject("paymentText");
					idname.innerHTML="The Interest Only and Repayment Amounts do not add up to the Mortgage Amount you have entered.<br />Please note the Repayment amount has been adjusted to add up to the Mortgage Amount.";
					ShowLayer("","payment",4);
				}	
			}
			HideError("erepaymentamount");	
			SetValue("form", "repaymentamount", (mortAmt-IntOnlyAmt));		 
		} else ShowError("mainerror1");
	}
}

function valMortgageR(){
	FormatValues("");
	var mortAmt		= GetValue("mortgageamount");
	var IntOnlyAmt	= GetValue("interestonlyamt");
	var repayAmt	= GetValue("repaymentamount");
	var diff		= 0;
	
	
	if( !CheckEmpty(mortAmt) && !CheckEmpty(repayAmt) ) {
		if( validateMortAmt(mortAmt,"emortgageamount") && validatePayment(repayAmt,"erepaymentamount",mortAmt) ) {
			HideError("mainerror1");
			if( (mortAmt-repayAmt)>0){
				diff =	mortAmt-IntOnlyAmt-repayAmt;
				SetValue("", "interestonlyamt", (mortAmt-repayAmt));				
			} else {
				diff = 0;
				SetValue("", "interestonlyamt", IntOnlyAmt);	
			}
			if(Math.abs(diff) >0) {
				idname=GetObject("paymentText");
				idname.innerHTML="The Interest Only and Repayment Amounts do not add up to the Mortgage Amount you have entered.<br />Please note the Interest only amount has been adjusted to add up to the Mortgage Amount.";
				ShowLayer("","payment",4);
			} 
			return false;
		} else ShowError("mainerror1");	
	}
}

function valMortgage(){
	FormatValues("");
	var mortAmt		= GetValue("mortgageamount");
	var IntOnlyAmt	= GetValue("interestonlyamt");
	var repayAmt	= GetValue("repaymentamount");
	var diff = 0;
	valLoanToVal();
	
	if( !CheckEmpty(IntOnlyAmt) && !CheckEmpty(repayAmt) ) {
		diff =	mortAmt-IntOnlyAmt-repayAmt;	
		SetValue("", "repaymentamount", (mortAmt-IntOnlyAmt));
		if(Math.abs(diff) >0) {
			idname=GetObject("paymentText");//document.getElementById("tiptext");
			idname.innerHTML="The Interest Only and Repayment Amounts do not add up to the Mortgage Amount you have entered.<br />Please note the Repayment amount has been adjusted to add up to the Mortgage Amount.";
			ShowLayer("","payment",4);
		}
	}
	
}

function getPos(id){
	var pos_x = id.offsetLeft;
	var pos_y = id.offsetTop;
	var ins   = 0;
	while(id.offsetParent){
		pos_x = pos_x+id.offsetParent.offsetLeft;
		pos_y = pos_y+id.offsetParent.offsetTop;
		ins=1;
		if(id==document.getElementsByTagName('body')[0]){break}
		else{id=id.offsetParent;}
	}
	return [pos_x,pos_y];
}

function valLoanToVal(){
	FormatValues("");
	GetErrorMessage();
	var propVal	= GetValue("propertyvalue");
	var mortAmt	= GetValue("mortgageamount");
	var loantoval = 0;
	idname=GetObject("interestRateText");
	
	if( !CheckEmpty(propVal) && !CheckEmpty(mortAmt) ) {
		if( validatePrptAmt(propVal,"epropertyvalue") && validateMortAmt(mortAmt,"emortgageamount") ) {
			HideError("mainerror1");
			loantoval=(mortAmt/propVal)*100;
			if(loantoval <= GetValue("maxltv")) {
				HideLayer("payment");
				swapIntRate(2,null);								
			} else if(loantoval > GetValue("maxltv")){
				swapIntRate(1,"high");							
			}
			CalculateInstantRate();
			//console.log(ir);
			//alert(ir+'HHH');
			
			/*if(loantoval <= GetValue("maxltv")) {
				idname.innerHTML="<strong>"+GetValue("lowRate")+"%</strong> - This is the lowest Woolwich offset mortgage rate which is currently available based on your LTV";
				HideLayer("payment");
				swapIntRate(2,null);								
			} else if(loantoval > GetValue("maxltv")){
				idname.innerHTML=" There is no Woolwich offset mortgage rate currently available based on your LTV";	
				swapIntRate(1,"high");							
			} */
		}else ShowError("mainerror1");	
	} else {
		idname.innerHTML=" The lowest Woolwich offset mortgage rate which is currently available based on your LTV";
		swapIntRate(2,null);	
	}
}

function swapIntRate(id,LTAval){
	if(id==1) {
		e_event=null;		
		SetClass("yourrateLablDiv","leftColumn leftColExt sVisible");
		GetObject("interestrateDef").checked = false;		
		GetObject("yourRate").checked = true;				
		GetObject("ownRateAmt").disabled = false;				
		SetClass("ownRateAmt","enableClr");
		if(LTAval=="high"){
		   GetObject("interestrateDef").disabled = true;
		   SetClass("formButtonsDiv","formButtons hrepay");
		   SetClass("formButtonsDivCont","formButtons srepay");
		   popName=GetObject("paymentText");
		   popName.innerHTML = ErrorMessage[3];
		   ShowLayer("","payment",5);
		}
		
	} else if(id==2) {
		HideError("einterestyourratediv");	
		GetObject("interestrateDef").disabled = false;
		GetObject("interestrateDef").checked = true;
		SetClass("yourrateLablDiv","leftColumn leftColExt hVisibile");				
		GetObject("yourRate").checked = false;				
		GetObject("ownRateAmt").disabled = true;				
		SetClass("ownRateAmt","disableClr");
		SetClass("formButtonsDiv","formButtons srepay");
		SetClass("formButtonsDivCont","formButtons hrepay");	
	}
	
}

function PartnadPartShow(e_event) {
	if(typeof e_event == "undefined") e_event=null;
	CreatePAPTable();
	SetValue("", "rinterestonlyamt", ioa);
	SetValue("", "rrepaymentamount", pap);
	SetValue("span","lumpsumHead","Add Part and part portions");
	SetValue("div","lumpsumClose",'<a href="#" onclick="PAPClose();return false;">Close</a>');
	ShowLayer(e_event,"lumpsum",8);
	//if(e_event)
	//	ShowLayer(e_event,"lumpsum",3);
	//else
		
		//GetObject("lumpsum").style.display="block";
}

function PAPClose(){ 
	if(valid) HideLayer('lumpsum');
}

function CreatePAPTable(){
	newPAPTable='<table id="lstable"><tbody><tr><td class="tdWidth">Interest Only Amount</td><td><a href="#help15" class="help" title="Click here to view help text" onclick="ShowHelp(event,15,1);return false;"><img src="/offsetcalculator/images/help.png" alt="Click here to view help text" /></a></td><td><div id="srinterestonlyamt"><input type="text" name="rinterestonlyamt" id="rinterestonlyamt" value="" onblur="valrMortgageIO();return false;" /></div></td><td></td></tr>';
	newPAPTable+='<tr><td class="tdWidth">Repayment Only Amount</td><td><a href="#help16" class="help" title="Click here to view help text" onclick="ShowHelp(event,16,1);return false;"><img src="/offsetcalculator/images/help.png" alt="Click here to view help text" /></a></td><td><div id="srrepaymentamount"><input type="text" name="rrepaymentamount" id="rrepaymentamount" value=""   onblur="valrMortgageR();return false;" /></div></td><td></td></tr>';
	newPAPTable+="<tr><td colspan='3'>";
	newPAPTable+="<div class='lsformButtons'><a href='#' onclick='SavePAP();return false;' title='Save changes'>";
	newPAPTable+="<img alt='Save changes' src='/offsetcalculator/images/btn-save-changes.gif' /></a>";
	newPAPTable+="</div>";
	newPAPTable+="</td></tr>";
	newPAPTable+="</tbody></table>";
	SetValue("div","lumpsumtable",newPAPTable);	
}

function SavePAP(){
	HideLayer("payment");
	valid=true;
	var errmsg="";
	ioa = GetValue("rinterestonlyamt");
	pap	= GetValue("rrepaymentamount");
	var mortAmt		= GetValue("rmortgageamount");
	if( validateIntnly(ioa,"mainerrorls",mortAmt) && validatePayment(pap,"mainerrorls",mortAmt) ){
		HideError("mainerrorls");
		HideLayer('lumpsum');
	} else if(!valid) {
		valid = false;
		ShowLayer("","lumpsum",8);
	}
	return valid;
	
}

function valrMortgage(){
	var mortAmt		= GetValue("rmortgageamount");
	//var IntOnlyAmt	= GetValue("rinterestonlyamt");
	//var repayAmt	= GetValue("rrepaymentamount");
	var diff = 0;
	var tag = valrLoanToVal();
	if( !CheckEmpty(ioa) && !CheckEmpty(pap) ) {
		if(GetValue("rrepaymentType") == "partAndPart"){
			diff =	mortAmt-ioa-pap;
			if(diff!=0) pap = mortAmt-ioa;
			if(tag && (diff!=0) ) PartnadPartShow("");
			SetValue("", "rinterestonlyamt", ioa);	
			SetValue("", "rrepaymentamount", (mortAmt-ioa));		
			if(Math.abs(diff) >0) {
				idname=GetObject("paymentText");//document.getElementById("tiptext");
				idname.innerHTML="The Interest Only and Repayment Amounts do not add up to the Mortgage Amount you have entered.<br />Please note the Repayment amount has been adjusted to add up to the Mortgage Amount.";
				if(tag) ShowLayer("","payment",6);
				else HideLayer("payment");
			}
		}
	}	
}

function valrMortgageIO(){
	var mortAmt		= GetValue("rmortgageamount");
	var IntOnlyAmt	= GetValue("rinterestonlyamt");
	var repayAmt	= GetValue("rrepaymentamount");
	var diff 		= 0;
	
	if( !CheckEmpty(mortAmt) && !CheckEmpty(IntOnlyAmt) ) {	
		if( validateMortAmt(mortAmt,"ermortgageamount") && validateIntnly(IntOnlyAmt,"mainerrorls",mortAmt) ) {
			HideError("mainerrorls");
			if(repayAmt>0){
				diff =	mortAmt-IntOnlyAmt-repayAmt;
				if(Math.abs(diff) >0) {
					idname=GetObject("paymentText");
					idname.innerHTML="The Interest Only and Repayment Amounts do not add up to the Mortgage Amount you have entered.<br />Please note the Repayment amount has been adjusted to add up to the Mortgage Amount.";
					ShowLayer("","payment",6);
				}	
			}
			SetValue("", "rinterestonlyamt", IntOnlyAmt);	
			SetValue("", "rrepaymentamount", (mortAmt-IntOnlyAmt));		
					 
		} else ShowError("mainerrorls");
	}
}


function valrMortgageR(){
	var mortAmt		= GetValue("rmortgageamount");
	var IntOnlyAmt	= GetValue("rinterestonlyamt");
	var repayAmt	= GetValue("rrepaymentamount");
	var diff		= 0;
	
	
	if( !CheckEmpty(mortAmt) && !CheckEmpty(repayAmt) ) {
		if( validateMortAmt(mortAmt,"ermortgageamount") && validatePayment(repayAmt,"mainerrorls",mortAmt) ) {
			HideError("mainerrorls");
			if( (mortAmt-repayAmt)>0){
				diff =	mortAmt-IntOnlyAmt-repayAmt;
				SetValue("", "rrepaymentamount", repayAmt);	
				SetValue("", "rinterestonlyamt", (mortAmt-repayAmt));				
			} else {
				diff = 0;
				SetValue("", "rrepaymentamount", repayAmt);
				SetValue("", "rinterestonlyamt", IntOnlyAmt);	
			}
			if(Math.abs(diff) >0) {
				idname=GetObject("paymentText");
				idname.innerHTML="The Interest Only and Repayment Amounts do not add up to the Mortgage Amount you have entered.<br />Please note the Interest only amount has been adjusted to add up to the Mortgage Amount.";
				ShowLayer("","payment",6);
			}
			return false;
		} else ShowError("mainerrorls");	
	}
}

function CreateRateTable(){
	newRateTable='<table id="lstable"><tbody><tr><td class="tdWidth">Input your own rate:</td><td><input type="text" name="rownRateAmt" id="rownRateAmt" onkeydown="return checkRateDecimal(event,this.value);"  value="" size="5" maxlength="5" />%</td><td></td></tr>';
	newRateTable+="<tr><td colspan='3'>";
	newRateTable+="<div class='lsformButtons'><a href='#' onclick='SaveRate();return false;' title='Save changes'>";
	newRateTable+="<img alt='Save changes' src='/offsetcalculator/images/btn-save-changes.gif' /></a>";
	newRateTable+="</div>";
	newRateTable+="</td></tr>";
	newRateTable+="</tbody></table>";
	SetValue("div","wonRatePoptable",newRateTable);	
}

function ownrateShow(e_event){
	try{ //for IE-6 design issue - dropdown overlap
		GetObject("rcurtaxband").style.visibility = "hidden";
		GetObject("rrepaymentType").style.visibility = "hidden";
	}catch( excep ){ }
	if(typeof e_event == "undefined") e_event=null;
	CreateRateTable();
	SetValue("","rownRateAmt",ownRate);
	SetValue("span","wonRatePopHead","Enter your own rate");
	SetValue("div","wonRatePopClose",'<a href="#" onclick="RateClose();return false;">Close</a>');
	ShowLayer(e_event,"wonRatePop",7);	
}

function RateClose(){ 
	try{ //for IE-6 design issue - dropdown overlap
		GetObject("rcurtaxband").style.visibility = "visible";
		GetObject("rrepaymentType").style.visibility = "visible";
	}catch( excep ){ }
	if(valid) HideLayer('wonRatePop');
}

function SaveRate(){
	valid=true;
	var errmsg="";
	
	ownRate			= GetValue("rownRateAmt");
	var repayAmt	= GetValue("rrepaymentamount");
	var propVal		= GetValue("rpropertyvalue");
	var mortAmt		= GetValue("rmortgageamount");
	
	if( CheckEmpty(ownRate)) { 
		loantoval=(mortAmt/propVal)*100;	
		if(loantoval < GetValue("maxltv")){
			HideLayer('wonRatePop'); 
			return;
		}else valid= false;	
	}
	else if(CheckPattern(ownRate, "[^0-9\.]")){
		SetErrorMessage("wonRatePoperrorls","Please enter a valid number without character or spaces.");
		valid= false;	
	}
	else if(!CheckPattern(ownRate,"(^[0-9]{1,2}\.[0-9]{0,2}$)|^[0-9]{1,2}$")){
		SetErrorMessage("wonRatePoperrorls","Please enter a valid interest rate.");
		valid= false;	
	}
	else if(!CheckValue(ownRate,0.01,99.99)){
		SetErrorMessage("wonRatePoperrorls","The value entered is too high/too low.");
		valid= false;	
	}
	
	if (!valid){
		ShowError("wonRatePoperrorls");
		ShowLayer("","wonRatePop",7);		
	}
	else{
		HideError("wonRatePoperrorls");
		SetValue("span","lblRate2",FormatValue(ownRate,"percent"));	
		SetValue("form","rate",ownRate);
		HideLayer('wonRatePop');
		try{ //for IE-6 design issue - dropdown overlap
			GetObject("rcurtaxband").style.visibility = "visible";
			GetObject("rrepaymentType").style.visibility = "visible";
		}catch( excep ){ }
	}
}

function valrLoanToVal(){
	var propVal	= GetValue("rpropertyvalue");
	var mortAmt	= GetValue("rmortgageamount");
	var loantoval = 0;
	idname=GetObject("interestRateText");
	
	if( !CheckEmpty(propVal) && !CheckEmpty(mortAmt) ) {
		if( validatePrptAmt(propVal,"erpropertyvalue") && validateMortAmt(mortAmt,"ermortgageamount") ) {
			HideError("wonRatePoperrorls");
			loantoval=(mortAmt/propVal)*100;	
			if(loantoval > GetValue("maxltv")){
				SetErrorMessage("wonRatePoperrorls",ErrorMessage[6]);	
				ownrateShow("");
				return false;
			} else {
				 HideLayer('wonRatePop'); 
				 return true;
			}
				 /*else {SetValue("span","lblRate2","Woolwich "+FormatValue(GetValue("rate"),"percent"));}*/
		}else ShowError("mainerror1");	
	} 
	 return true;
}

function loadGrp(){
	if(GetValue("rpriority")==1) {
		SetClass("Rad1","radiotabslefton");
		SetClass("Rad2","radiotabsrightoff");
	} 
	else {
		SetClass("Rad1","radio2_tabslefton");
		SetClass("Rad2","radio2_tabsrightoff");	
	}
	return Step3();	
}

function GetErrorMessage(){
	//Error messages for customer and intermediaries.
	if(GetValue("audience") == "INT") {
		ErrorMessage[1] = "Please enter your client's current property value.";
		ErrorMessage[2] = "Please enter your client's mortgage amount";
		ErrorMessage[3] = "We currently do not offer an offset product with this LTV. If you're able to, please reduce the mortgage amount required using your client's savings.<br />If you're happy with your input, please enter an alternative interest rate and click option to \"continue with illustration anyway\".";
		ErrorMessage[4] = "Please enter the term of your client's mortgage.";
		ErrorMessage[5] = "You have opted to enter an alternative interest rate, please enter your client's interest rate.";
		ErrorMessage[6] = "We currently do not offer an offset product with this LTV. If you're able to, please reduce the mortgage amount required using your client's savings.<br />If you're happy with your input, please enter an alternative interest rate and click option to \"Save changes\".";
	} else {
		ErrorMessage[1] = "Please enter your current property value.";
		ErrorMessage[2] = "Please enter your mortgage amount.";
		ErrorMessage[3] = "We currently do not offer an offset product with this ratio of borrowing against your property value. If you're able to, please reduce the mortgage amount required using your savings.<br />If you're happy with your entries, please enter an alternative interest rate and click option to \"continue with illustration anyway\".";
		ErrorMessage[4] = "Please enter the term of your mortgage.";
		ErrorMessage[5] = "You have opted to enter an alternative interest rate, please enter your interest rate.";
		ErrorMessage[6] = "We currently do not offer an offset product with this ratio of borrowing against your property value.  If you're able to, please reduce the mortgage amount required using your savings.<br />If you're happy with your entries, please enter an alternative interest rate and click option to \"Save changes\".";
	}
}

function HideAllLayer(id){
	if(id==1){
		HideLayer("help");
		HideLayer("helpext");
		HideLayer("payment");
	} else {
		HideLayer("help");
		HideLayer("helpext");
	}
}
function checkRateDecimal(e,val){
	
	if (!e) var e = window.event; 
    if (e.keyCode) code = e.keyCode; 
    else if (e.which) code = e.which;   
	
	//val = GetValue("ownRateAmt");
	if(typeof val == "undefined") val="";
	else {
		if (code != 8 && code != 46 && code !=37 && code !=39) {
			var pos = val.indexOf(".");
			if( pos >= 0) {
				var s = (val.substring(pos));
				var a = val.substring(0,pos);
				if( s.length <=2) 					
					 return true;
				else return false;
			}
		}
	}
	return true;
}
function CalculateInstantRate(){
	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= DisplayInstant;
		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 DisplayInstant() {
	if (xmlhttp.readyState==4) {
		if (xmlhttp.status==200) {
			data=xmlhttp.responseXML.getElementsByTagName('OFFSET');
			if (typeof data[0].getElementsByTagName('RATE')[0] != "undefined") {
				ir=data[0].getElementsByTagName('RATE')[0].firstChild.nodeValue;								
			}
			
			loantoval=(GetValue("mortgageamount")/GetValue("propertyvalue"))*100;
			if(loantoval <= GetValue("maxltv")) {
				idname.innerHTML="<strong>"+ir+"%</strong> - This is the lowest Woolwich offset mortgage rate which is currently available based on your LTV";
				HideLayer("payment");
				swapIntRate(2,null);								
			} else if(loantoval > GetValue("maxltv")){
				idname.innerHTML=" There is no Woolwich offset mortgage rate currently available based on your LTV";	
				swapIntRate(1,"high");							
			}
			
		} else
			alert("Problem retrieving data:" + xmlhttp.statusText);
	}
}

