﻿

// JScript File
var lastnode;
var appname;
var currentinput = 0;
var t;
var evt;
var key;
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
var x2 = 100;
var screenwidth = 1280;
var screenheight = 768;
var i = 0;
var focuswhere = 0;
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

//===================================================================================================================


function doOnActionKey(Event) {
	var code = Event.keyCode || Event.which;
	if (code == 13 || code == 9) {
		var obj = $getEventTarget(Event);
		var action = obj.getAttribute('action');
		if (obj && action) {
			if (CheckRegEx(obj, obj.getAttribute('regex'))) {
				try {
					console.warn('evaling code! ' + action);
					eval(action);
					return $stopEvent(Event);
				}
				catch (e) {
					console.warn('error executing action attribute for ' + obj + ' ' + e);
				}
			}
		} 
	}
	//return false;
}

function xmlhttpPost(strURL, AlertMessage) {
	var xmlHttpReq = false;
	var self = this;
	// Mozilla/Safari
	if (window.XMLHttpRequest) {
		self.xmlHttpReq = new XMLHttpRequest();
	}
	// IE
	else if (window.ActiveXObject) {
		self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	self.xmlHttpReq.open('POST', strURL, true);
	self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	self.xmlHttpReq.onreadystatechange = function() {
		if (self.xmlHttpReq.readyState == 4) {
			if (self.xmlHttpReq.responseText != '0' && self.xmlHttpReq.responseText != '') {
				toggle("errorpop");
				toggle("errorpop2");
				$get("errortext").innerHTML = AlertMessage;
			}

		}
	}
	self.xmlHttpReq.send(mycommand());
}

function mycommand() {
	qstr = 'username=' + escape("");  // NOTE: no '?' before querystring
	return qstr;
}

function validateForm(sFormId, oValidate) {
	var oForm = document.getElementById(sFormId);
	if (!oForm) return 'Form (' + sFormId + ') not found.';
	if (!oForm.elements) return 'No elements found in form.';
	var results = {
		'form': oForm,
		'results': {},
		'conclusion': ''
	};
	for (var i = 0; i < oForm.elements.length; i++) {
		results.results[i] = oValidate(oForm.elements[i]);
	}
	return results;
}

function validateElement(oElement) {
	var result = {
		'result': true, /* Valid by default (elements we don't have a validation function for). */
		'message': 'untested'
	};
	if (oElement) {
		var id = (oElement.id) ? oElement.id : oElement.name;
		var value = trim(oElement.value)
		switch (id) {
			case 'name':
				result.result = value.length > 1;
				if (!result.result) result.message = 'Name must be longer than one letter.';
				break;
			case 'email':
				result.result = checkEmail2(value);
				if (!result.result) result.message = 'Email appears to be invalid.';
				break;
		}
	}
	else {
		result.result = false;
		result.message = 'Element not found.';
	}
	return result;
}


//--------------------------------------String functions---------------------------------------------------------
// checkPostCode, checkUKTelephone, checkEmail2, IsEmpty, IsNumeric
//--------------------------------------String functions---------------------------------------------------------
function isDate(year, month, day) {
	var retval = null;
	month--;  // javascript month range : 0- 11
	var tempDate = new Date(year, month, day);
	if ((getYear(tempDate.getYear()) == year) && (month == tempDate.getMonth()) && (day == tempDate.getDate())) {
		retval = true;
	}
	else {
		retval = false
	}
	return retval;
}
function Selectvalueinlist(listtoselectfrom, valuetoselect) {
	var list = eval("window.document.forms[0]." + listtoselectfrom);
	var optionCounter;
	for (optionCounter = 0; optionCounter < list.options.length; optionCounter++) {
		if (list.options[optionCounter].value.toLowerCase() == valuetoselect.toLowerCase()) {
			list.options[optionCounter].selected = true;
			break;
		}
	}
}

var checkUKTelephone = function() { return true; }




var lastquestionloaded;
var NumberOfQuestions = 40;
var NumberAnswered = 0;
var idArray = '';
function movecar(obj) {
	if (obj && $get("percentagecomplete")) {
		if ($get("dontmove").value == 0 && obj.id.indexOf("title") == -1) {
			var objname = obj.id.replace("img_no", "").replace("img_yes", "");
			if (idArray.indexOf(objname) == -1) {
				idArray = idArray + objname + ",";
				if (parseFloat(NumberAnswered) != parseFloat(NumberAnswered)) {
					NumberAnswered = 1;
				}
				var p = parseInt($get("PercentToMove").value);
				p = parseInt(parseInt($get("PercentLow").value) + p * NumberAnswered);
				if (p > $get("PercentHigh").value) {
					p = $get("PercentHigh").value
				}
				parent.fillProgress('element1', p);
				$get("percentagecomplete").innerHTML = p + '%';
				NumberAnswered = NumberAnswered + 1;
			}
		}
	}
}

function simplepopup(tablename, url) { $get(tablename).style.display = ''; $get(tablename + "-url").href = AppendURL(url);  }
function trim(stringToTrim) { if (stringToTrim) { return stringToTrim.replace(/^\s+|\s+$/g, ""); } }
function setAutoComplete() { var formelements = document.getElementsByTagName("form"); for (var i = 0; i < formelements.length; i++) { formelements[i].setAttribute("AUTOCOMPLETE", "OFF"); } }
function IsNumeric(sText) {
	var ValidChars = "0123456789.";
	var IsNumber = true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++) {
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;
}
function checkPostCode(toCheck) {
	var alpha1 = "[abcdefghijklmnoprstuwyz]";
	var alpha2 = "[abcdefghklmnopqrstuvwxy]";
	var alpha3 = "[abcdefghjkstuw]";
	var alpha4 = "[abehmnprvwxy]";
	var alpha5 = "[abdefghjlnpqrstuwxyz]";
	var pcexp = new Array();
	pcexp.push(new RegExp("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
	pcexp.push(new RegExp("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
	pcexp.push(new RegExp("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
	pcexp.push(/^(GIR)(\s*)(0AA)$/i);
	pcexp.push(/^(bfpo)(\s*)([0-9]{1,4})$/i);
	pcexp.push(/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
	var postCode = toCheck;
	var valid = false;
	for (var i = 0; i < pcexp.length; i++) {
		if (pcexp[i].test(postCode)) {
			pcexp[i].exec(postCode);
			postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
			postCode = postCode.replace(/C\/O\s*/, "c/o ");
			valid = true;
			break;
		}
	}
	if (valid) { return postCode; } else return false;
}

function jobstatus(selection, dontselect) {
	console.info('jobstatus', selection);
	if (window.name != 'scriptcontent') {
		var parent = window.self;
	}
	else {
		var parent = window.parent;
	}
	if (dontselect != 1) {
		parent.SelectInList('requestjobstatus', selection);
	}
	if (selection == 'Independent Means') {
		parent.$get('requestfulltimeoccupation').value = 'Independent Means'; parent.$get('requestfulltimejobabicode').value = 'I02'; parent.$get('requestbusinesstypeabicode').value = '186'; parent.$get('requestbusinesstype').value = 'Not In Employment';
		if (parent.$get('requestnoclaimsdiscount')) {
			parent.MoveToNextInputNamed('requestnoclaimsdiscount');
		}
		else {
			parent.MoveToNextInputNamed('requestrelationshiptomaindriver');
		}
	}
	else if (selection == 'Unemployed') {
		parent.$get('requestfulltimeoccupation').value = 'Unemployed'; parent.$get('requestfulltimejobabicode').value = 'U03'; parent.$get('requestbusinesstypeabicode').value = '747'; parent.$get('requestbusinesstype').value = 'Unemployed';
		if (parent.$get('requestnoclaimsdiscount')) {
			parent.MoveToNextInputNamed('requestnoclaimsdiscount');
		} else {
			parent.MoveToNextInputNamed('requestrelationshiptomaindriver');
		}
	}
	else if (selection == 'Not Employed Due To Disability') {
		parent.$get('requestfulltimeoccupation').value = 'Unemployed'; parent.$get('requestfulltimejobabicode').value = 'U03'; parent.$get('requestbusinesstypeabicode').value = '747'; parent.$get('requestbusinesstype').value = 'Unemployed';
		if (parent.$get('requestnoclaimsdiscount')) {
			parent.MoveToNextInputNamed('requestnoclaimsdiscount');
		} else {
			parent.MoveToNextInputNamed('requestrelationshiptomaindriver');
		}
	}
	else if (selection == 'Retired') {
		parent.$get('requestfulltimeoccupation').value = 'Retired'; parent.$get('requestfulltimejobabicode').value = 'R09'; parent.$get('requestbusinesstypeabicode').value = '186'; parent.$get('requestbusinesstype').value = 'Not In Employment';
		if (parent.$get('requestnoclaimsdiscount')) {
			parent.MoveToNextInputNamed('requestnoclaimsdiscount');
		}
		else {
			parent.MoveToNextInputNamed('requestrelationshiptomaindriver');
		}
	}
	else if (selection == 'Full Time Education Student') {
		//parent.$get('requestfulltimeoccupation').value = 'Student'; parent.$get('requestfulltimejobabicode').value = 'S44';
		parent.$get('requestbusinesstypeabicode').value = '186'; parent.$get('requestbusinesstype').value = 'Not In Employment';
		if (parent.$get('requestfulltimeoccupation')) {
			parent.MoveToNextInputNamed('requestfulltimeoccupation');
		}
	}
	else if (selection == 'Household Duties') {
		var title = parent.$get('requesttitle').selectedIndex;
		if (parent.$get('requesttitle').options[0].text == 'Select ->') {
			title--;
		}
		if (title == 0 || title == 4) {
			parent.$get('requestfulltimeoccupation').value = 'Househusband'; parent.$get('requestfulltimejobabicode').value = '163'; parent.$get('requestbusinesstypeabicode').value = '186'; parent.$get('requestbusinesstype').value = 'Not In Employment';
		}
		if (title == 1 || title == 2 || title == 3 || title == 5) {
			parent.$get('requestfulltimeoccupation').value = 'Housewife'; parent.$get('requestfulltimejobabicode').value = 'H09'; parent.$get('requestbusinesstypeabicode').value = '186'; parent.$get('requestbusinesstype').value = 'Not In Employment';
		}
		if (title == -1) {
			parent.$get('requestfulltimeoccupation').value = 'Housekeeper';
			parent.$get('requestfulltimejobabicode').value = 'H10';
			parent.$get('requestbusinesstype').value = 'Not In Employment';
			parent.$get('requestbusinesstypeabicode').value = '186';
			parent.MoveToNextInputNamed('requestfulltimeoccupation');
		}
		else {
			if (parent.$get('requestnoclaimsdiscount')) {
				parent.MoveToNextInputNamed('requestnoclaimsdiscount');
			}
			else {
				parent.MoveToNextInputNamed('requestrelationshiptomaindriver');
			}
		}
	}
	else {
		parent.MoveToNextInputNamed('requestfulltimeoccupation');
	}
}


var lastquestionloaded;
var NumberOfQuestions=40;
var NumberAnswered=0;
var idArray='';



function checkMobileTelephone(telephoneNumber) {
	return checkTelephone(telephoneNumber);
	/*
	var telnum = telephoneNumber + ' ';
	telnum.length = telnum.length - 1;
	var exp = /^(\+)[\s]*(.*)$/;
	if (exp.test(telnum) == true) {
		telNumberErrorNo = 2;
		return false;
	}
	while (telnum.indexOf(' ') != -1) {
		telnum = telnum.slice(0, telnum.indexOf(' ')) + telnum.slice(telnum.indexOf(' ') + 1)
	}
	while (telnum.indexOf('-') != -1) {
		telnum = telnum.slice(0, telnum.indexOf('-')) + telnum.slice(telnum.indexOf('-') + 1)
	}
	if (telnum.length < 10) {
		telNumberErrorNo = 3;
		return false;
	}
	if (telnum.charAt(0) != '0') {
		telNumberErrorNo = 4;
		return false;
	}
	if (telnum.charAt(0) != '0' && telnum.charAt(1) != '0') {
		telNumberErrorNo = 4;
		return false;
	}
	exp = /^(07)[0-9]+$/;
	if (exp.test(telnum) != true) {
		telNumberErrorNo = 5;
		return false;
	}
	return telnum;
	*/
}


function checkTelephone(telephoneNumber) {
	return telephoneNumber + '';
	// Convert into a string and check that we were provided with something
	var telnum = telephoneNumber + '';
	telnum.length = telnum.length - 1;
	// Don't allow country codes to be included (assumes a leading +)
	var exp = /^(\+)[\s]*(.*)$/;
	if (exp.test(telnum) == true) {
		telNumberErrorNo = 2;
		return false;
	}
	// Remove spaces from the telephone number to help validation
	while (telnum.indexOf(' ') != -1) {
		telnum = telnum.slice(0, telnum.indexOf(' ')) + telnum.slice(telnum.indexOf(' ') + 1)
	}
	// Remove hyphens from the telephone number to help validation
	while (telnum.indexOf('-') != -1) {
		telnum = telnum.slice(0, telnum.indexOf('-')) + telnum.slice(telnum.indexOf('-') + 1)
	}
	// Now check that all the characters are digits
	if (telnum.length < 10) {
		telNumberErrorNo = 3;
		return false;
	}
	// Now check that the first digit is 0
	if (telnum.charAt(0) != '0') {
		telNumberErrorNo = 4;
		return false;
	}
	if (telnum.charAt(0) != '0' && telnum.charAt(1) != '0') {
		telNumberErrorNo = 4;
		return false;
	}
	// Finally check that the telephone number is appropriate.
	//exp = /^(01|02|03|05|070|077|078|079)[0-9]+$/;
	exp = /^(01|02|03|05|07)[0-9]{7,9}$/
	if (exp.test(telnum) != true) {
		telNumberErrorNo = 5;
		return false;
	}
	// Telephone number seems to be valid - return the stripped telehone number  
	return telnum;
}
var telNumberErrorNo = 0;
var telNumberErrors = new Array();
telNumberErrors[0] = 'Valid UK telephone number';
telNumberErrors[1] = 'Telephone number not provided';
telNumberErrors[2] = 'UK telephone number without the country code, please';
telNumberErrors[3] = 'UK telephone numbers should contain 10 or 11 digits';
telNumberErrors[4] = 'The telephone number should start with a 0';
telNumberErrors[5] = 'The telephone number is either invalid or inappropriate';


function islongerthan0(subject) {
	var result;
	if (subject.length > 0) {
		result = true;
	}
	else {
		result = false;
	}
	return result;
}

function isValidPassword(subject) {
	var result = true;
	if (islongerthan0(subject) != true) {
		result = false;
	}
	if (subject.search(' ') > -1) {
		result = false;
	}
	if (subject.search('"') > -1) {
		result = false;
	}
	if (subject.search("'") > -1) {
		result = false;
	}
	if (subject.toLowerCase() == 'password') {
		alert('You cannot use "password" as a valid password.')
		result = false;
	}
	if (document.getElementById('dhx_combo_input')) {
		if (subject == document.getElementById('dhx_combo_input').value) {
			alert('Your password cannot match your password hint.')
			result = false;
		} 
	}
	return result;
}



function checkEmail2(atextfield) {
	if (/^([a-zA-Z0-9_\-\.!#$'\*\^`\|~\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/.test(atextfield)) {
		return true;
	}
	else {
		return false;
	}
}

function IsEmpty(aTextField) { if ((aTextField.value.length == 0) || (aTextField.value == null)) { return true; } else { return false; } }
function SubmitCallMeButtonClick(urlin) { if (document.forms[0]) { document.forms[0].action = urlin + "/callme.aspx?productcat=" + $get("productcategory").value + "&productguid=" + $get("productguid").value + "&path=" + document.location.pathname; document.forms[0].target = ""; document.forms[0].submit(); } }
function closeiframe() { if (parent.$get('hide1')) { parent.$get('hide1').click(); } }

function PCase(STRING) {
	return toProperCase(STRING);
}

function setopacity(objref) {
	if ($get(objref)) {
		if ($get(objref).style.filter == "alpha(opacity=100)" || $get(objref).style.filter == '') {
			$get(objref).style.filter = 'alpha(opacity=10)';
		}
		else {
			$get(objref).style.filter = 'alpha(opacity=100)';
		}
	}
}

function changeimage(objref, newimage) { if ($get(objref)) { $get(objref).src = newimage; } }

function removefrompage(objref) { if ($get(objref)) { $get(objref).style.display = 'none'; } }

sPage = sPath.substring(sPath.lastIndexOf('/') + 1);

function kH(e) {
	//console.group('kH')
	var pK = document.all ? window.event.keyCode : e.which;
	var obj = $getEventTarget(e);
	if (obj && obj.tagName && obj.tagName.toLowerCase() == 'textarea') {
		//console.info(obj.tagName);
		//console.groupEnd()
		return true;
	}
	if (pK == 13 && sPage != 'yourhelper.aspx') {
		//console.log('MoveToNext');
		MoveToNext();
		//console.groupEnd()
		return pK != 13;
	}
	else {
		if (pK == 9 && sPage == 'yourhelper.aspx' || pK == 13 && sPage == 'yourhelper.aspx') {
			//console.info($get("nextbutton"));
			//console.info($get("nextbutton").getAttribute('onclick'));
			try {
				$get("nextbutton").click();
			}
			catch (e) {
				try {
					eval($get("nextbutton").getAttribute('onclick'))
				}
				catch(e) {
					console.warn('nextbutton not processed (' + e + ')');
					return true;
				}
			}
			//console.groupEnd()
			return false;
		}
		else {
			//console.groupEnd()
			return pK;
		}
	}
	//if (sPage == 'yourhelper.aspx') { parent.focuswhere = 0; }
	//console.groupEnd()
}

//document.onkeydown = kH;
//if (document.layers) document.captureEvents(Event.KEYDOWN);

if (window.$addEvent) $addEvent(document, 'keydown', kH);

function kH_false() {
	MoveToNext();
	return false;
}

function getYear(d) { return (d < 1000) ? d + 1900 : d; }
function showAge(dob) {
	var today = new Date();
	var d = dob.split('/');
	var by = Number(d[2]); var bm = Number(d[1]) - 1; var bd = Number(d[0]);
	var bday = new Date(by, bm, bd)
	var age = 0; var dif = bday;
	while (dif < today) {
		var dif = new Date(by + age, bm, bd);
		age++;
	}
	age += -2;  //Was -1 but this caused the age today return incorrectly
	return age;
}

function populatelist(elementn, matchtextnotvalue) { }
function populatespecial(source) {
	if (window.name != 'scriptcontent') {
		var parent = window.self;
	}
	else {
		var parent = window.parent;
	}

	var val = parent.$get(source).value.replace(',', '');
	if (val != '') {
		var cval = $get('c' + val);
		if (cval) {
			cval.className = 'sideoptionsHoverSelected';
			cval.onmouseover = null;
			cval.onmouseout = null;
		}
		else {
			console.warn('populatespecial: could not $get c' + val);
		}
	}
}
function populateinput(des, source) {
	if (window.name != 'scriptcontent') {
		var parent = window.self;
	}
	else {
		var parent = window.parent;
	}

	if (parent.$get(source) && parent.$get(source).value != '') {
		$get(des).value = parent.$get(source).value;
	}
}

function setElementById(id, value, displaytext) {
	if ($get(id.replace('request', 'question'))) {
		$get(id.replace('request', 'question')).value = value;
	}
	else {
		if ($get(id)) {
			$get(id).value = value;
		}
	}
	if ($get(id + 'text') && displaytext != undefined) {
		$get(id + 'text').innerHTML = displaytext;
	}
	gotoblank();
}

function gotoblank() {
	if ($get('scriptcontent')) {
		$get('scriptcontent').src = AppendURL('/motorquoter/yourhelper.aspx?question=noquestion');
	}
}

function highlightnotentered(name) {
	try {
		resetlastnode();
		var obj = eval("document.forms[0]." + name);
		if (obj.className.indexOf('error') == -1) {
			obj.className = obj.className + 'error';
		}
	   } catch (e) { console.warn('highlightnotentered error:' + e); }
}

function resethighlight(item) {
   try {
		var obj = $get(item) || $get(item + '#');
		if (obj && obj.className.indexOf('error')) {
			obj.className = obj.className.replace('error', '');
		}
	} catch (e) {console.warn('resethighlight error:' + e);}
}

function gup(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.href); if (results == null) return ""; else return results[1]; }
function AppendURL(currenturl) {
	var retval = '';
	if (currenturl.indexOf("sessionGUID") == -1) {
		if (currenturl.toString().indexOf("?") == -1) {
			retval = currenturl + '?sessionGUID=' + gup("sessionGUID");
		}
		else {
			retval = currenturl + '&sessionGUID=' + gup("sessionGUID");
		}
	} else {
		retval = currenturl;
	}

	return retval;
}

var nextclick = 0;
//function ChangeFrame(src) { if ($get('flyerframe')) $get('flyerframe').src = AppendURL(src); else console.warn('flyerframe does not exist'); }

function gofocus(elementID) {
	console.group('gofocus (' + elementID + ')');
	if ( !(elementID && elementID.nodeType) ) var obj = $get(elementID, null, '#');
	else var obj = elementID;
	if (obj && obj.nodeType) {
		if (obj && obj.focus) {
			var passFocus = $att(obj, 'passFocus');
			if (passFocus) {
				console.info('passFocus: ' + passFocus);
				return gofocus(passFocus);
			}
			else if (obj.tagName.toLowerCase() == 'input' && obj.type.toLowerCase() == 'hidden') {
				obj = $get(elementID + '_yes');
				//console.info(obj);
				if (obj) {
					console.info('selectmeYesNo...', obj);
					selectmeYesNo(obj);
				}
				else console.warn('gofocus - cannot find target: (' + elementID + ')');
			}
			else {
				//console.info(obj.focus);
				console.info('focus...', obj);
				obj.focus();
			}
		}
		else {
			obj = $get(elementID + '_yes');
			if (obj) {
				console.info('selectmeYesNo...', obj);
				selectmeYesNo(obj);
			}
			else {
				obj = $get(elementID.substring(0, elementID.lastIndexOf('.')));
				console.info('focus...', obj);
				if (obj && obj.focus) {
					try {
						obj.focus();
					} catch (e) { };
				}
				else console.warn('gofocus - cannot find target or target does not support focus() : (' + elementID + ')');
			}
		} 
	}
	else console.warn('gofocus: no object or id');
	console.groupEnd();
}

function focusEasyFill(fromElement) { ///////////////////////////////////// maybe
	console.log('focusEasyFill (' + fromElement + ') ' + window.location.href + ' [' + window.frames['scriptcontent'] + ']');
	var efIframe;
	if (window.location.href.indexOf('yourhelper.aspx') >= 0) {
		// running from easyfill
		var inputs = document.getElementsByTagName('input');
		if (fromElement && fromElement.blur) fromElement.blur();
		for (var i = 0, input; input = inputs[i]; i++) {
			if (input.type == 'text' && input.focus) {
				console.debug(input);
				//window.setTimeout(function() {
					console.log('focusEasyFill --> ' + input.id);
					input.focus();
				//}, 1260);
			}
		}
	}
	else if (efIframe = window.frames['scriptcontent']) {
		// in lhs and have easyfill frame
		if (fromElement && fromElement.blur) fromElement.blur();
		if (efIframe.focusEasyFill) {
			efIframe.focusEasyFill(fromElement); // call this function in easyfill frame
		}
	}
}

window.onEasyfillReady = null;

function easyfillReady(frameWindow) {
	console.info('easyfillReady!', ((window.frameWindow && frameWindow.location && frameWindow.location.search) ? frameWindow.location.search : ''));
	if (window.onEasyfillReady && window.onEasyfillReady.apply) {
		window.onEasyfillReady(frameWindow);
	}
}


function MoveToNextInputNamed(elementID, setfocus) {
	if (setfocus != undefined) window.focuswhere = setfocus;
	console.debug('MoveToNextInputNamed: ' + elementID);
	$get('scriptcontent').src = 'YourHelper.aspx?question=noquestion';
	setTimeout(function() { gofocus(elementID); }, 150);
}
//-------------------------------------------------------------------------
function getElementsByClassName(oElm, strTagName, strClassName) {
	var arrElements = (strTagName == "*" && oElm.all) ? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	if (arrElements && arrElements.length) {
		strClassName = strClassName.replace(/\-/g, "\\-");
		var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
		var oElement;
		for (var i = 0; i < arrElements.length; i++) {
			oElement = arrElements[i];
			if (oRegExp.test(oElement.className)) {
				arrReturnElements.push(oElement);
			}
		} 
	}
	return (arrReturnElements)
}
//-------------------------------------------------------------------------
function getElementsByClassStart(str) {
	var moveobjs = document.forms[0];
	if (moveobjs && moveobjs.length) {
		var newobjs = new Array();
		for (var i = 0; i < moveobjs.length; i++) {
			if (moveobjs[i].className.substring(0, 4) == 'flat') {
				newobjs.push(moveobjs[i]);
			}
		}
		return newobjs;
	} 
}


function MoveToNext() {
	var inputs = '';
	if (inputs == '') {
		inputs = getElementsByClassStart("flat");
	}
	var p = 0;
	var Completed = 0;
	var rID;
	//console.group('MoveToNext');
	for (i = 0; i < inputs.length; i++) {
		//console.log(i);
		if (lastquestionloaded == inputs[i].id) {
			if (inputs[i + p]) {
			//console.log(i + ' + ' + p);
				for (p = 1; p < inputs.length; p++) {
					rID = returnrowID(inputs[i + p]);
					if (rID && rID.style && rID.style.display != 'none' && (inputs[i + p].id.indexOf('request') == 0 || inputs[i + p].id.indexOf('VanProposal.') == 0)) {
						//console.info(inputs[i + p]);
						inputs[i + p].focus();
						lastquestionloaded = inputs[i + p].id;
						Completed = 1;
						break;
					}
				}
			}
		}
		if (Completed == 1)	break;
	}
	console.groupEnd();
}

function returnrowID(inID) {
	mynode = inID;
	while (mynode != null && mynode.id != null && mynode.id.substring(0, 3) != 'row') {
		mynode = mynode.parentNode;
	}
	return mynode;
}

function MoveToNextInput(numbertomove) {
	var element = 0;
	element = parseInt(currentinput + numbertomove);
	var inputs = getElementsByClassStart("flat");
	for (i = 0; i < inputs.length; i++) {
		if (i == element) {
			inputs[i].focus();
		}
	}
	currentinput = parseInt(currentinput + numbertomove);
}
//-------------------------------------------------------------------------
function getAge(dateString, dateType) {
	var now = new Date();
	var today = new Date(now.getYear(), now.getMonth(), now.getDate());
	var yearNow = now.getFullYear();
	var monthNow = now.getMonth();
	var dateNow = now.getDate();

	if (dateType == 1)
		var dob = new Date(dateString.substring(0, 4),
	dateString.substring(4, 6) - 1,
	dateString.substring(6, 8));
	else if (dateType == 2)
		var dob = new Date(dateString.substring(0, 2),
	dateString.substring(2, 4) - 1,
	dateString.substring(4, 6));
	else if (dateType == 3) {
		var dobs = dateString.split('/');
		var dob = new Date(dobs[2], dobs[1], dobs[0]);
	}
	else if (dateType == 4)
		var dob = new Date(dateString.substring(6, 8),
	dateString.substring(3, 5) - 1,
	dateString.substring(0, 2));
	else
		return '';
	var yearDob = dob.getFullYear();
	var monthDob = dob.getMonth();
	var dateDob = dob.getDate();
	var monthAge = 0;
	var dateAge;
	yearAge = yearNow - yearDob;

	if (monthNow >= monthDob)
		monthAge = monthNow - monthDob;
	else {
		yearAge--;
		monthAge = 12 + monthNow - monthDob;
	}
	if (dateNow >= dateDob)
		dateAge = dateNow - dateDob;
	else {
		monthAge--;
		dateAge = 31 + dateNow - dateDob;
		if (monthAge < 0) {
			monthAge = 11;
			yearAge--;
		}
	}
	return '&nbsp;(Click now if your age is: <b>' + showAge(dateString) + ' years</b>)';
}
//-------------------------------------------------------------------------
function YourAge(year) {
	if (window.name != 'scriptcontent') {
		var parent = window.self;
	}
	else {
		var parent = window.parent;
	}

	$get('yourage').innerHTML = getAge(parent.$get('requestdob_day').options[parent.$get('requestdob_day').selectedIndex].value + '/' + parent.$get('requestdob_month').options[parent.$get('requestdob_month').selectedIndex].value + '/' + year, 3);
}
function toProperCase(s) { return s.toLowerCase().replace(/^(.)|\s(.)/g, function($1) { return $1.toUpperCase(); }); }
//-------------------------------------------------------------------------
var percount = 1;
var mytext = '<img src=/images/smltick.gif border=0>';
var imagetext = '<img src=/images/smltick.gif border=0>';
var linktext = 'Edit';

function startup() {
	// could add iPad fix here!
	if (_.DeviceType == 'tablet' || _.DeviceType == 'phone') {
		var $input = jQuery('input');
		if ($input.length) {
			$input.each(function(i, input) {
				if (input.readOnly) {
					input.readOnly = false;
					//console.log('readOnly: ' + input.id + ' - ' + input.readOnly);
					$addEvent(input, 'keydown', function(e) { console.log('keydown'); return $stopEvent(e); });
					$addEvent(input, 'keyup', function(e) { console.log('keyup'); return $stopEvent(e); });
					$addEvent(input, 'keypress', function(e) { console.log('keypress'); return $stopEvent(e); });
				}
			});
		}
	}
	
	var win = document.location.href;
	if (win.indexOf("lookup=true") > -1) {
		selectTerms();
	}
	else {
		if (win.indexOf("edit") == -1) {
			lastquestionloaded = window.yellowsnow || (($get('VanProposal.Proposer.Title')) ? 'VanProposal.Proposer.Title' : 'requesttitle');
			lastnode = $get("row1");
		}
	}
	appname = navigator.appName;
	if ($get('requestdob_day_hidden')) {
		checkforfunnydates($get('requestdob_day_hidden').value, $get('requestdob_month_hidden').value, $get('requestdob_year_hidden').value);
	}
	
	// initial focus
	var requestEdit, match = ((document.location.search) ? document.location.search.match(/(?:edit|question)=([^&]+)/i) : false);
	if (window.yellowsnow) {
		var yellowRow = $getParent($get(yellowsnow), 'tr');
		if (yellowRow) {
			var stopAt = yellowRow.id.replace('row', ''), row, i = 0;
			row = $get('row' + i);
			while (i < stopAt) {
				if (row) $addClass(row, 'greenout');
				row = $get('row' + ++i);
			}
			window.setTimeout(function () {
				jQuery('input, select, textarea', row).focus();
			}, 300);
		}
	}
	else if (match && match.length && match[1] && (requestEdit = $get(match[1])) && requestEdit.focus) {
		requestEdit.focus();
	}
	else if (window.selectFirstInputOnPage && selectFirstInputOnPage.call) {
		selectFirstInputOnPage();
	}
	else {
		gofocus(lastquestionloaded);
	}
}


var run = 1;
var ns = (navigator.appName.indexOf("Netscape") != -1);
var d = document;
var px = document.layers ? "" : "px";
//var posx; var posy;
//function getMouse(e) {
//	posx = 0; posy = 0;
//	var ev = (!e) ? window.event : e; //IE:Moz
//	if (ev.pageX) {//Moz
//		posx = ev.pageX + window.pageXOffset;
//		posy = ev.pageY + window.pageYOffset;
//	}
//	else if (ev.clientX) {//IE
//		posx = ev.clientX + document.body.scrollLeft;
//		posy = ev.clientY + document.body.scrollTop;
//	}
//	else { return false } //old browsers
//}
////document.onclick = getMouse


var po = 0;

function setOpacity(testObj, value) {
	testObj.style.opacity = value / 10;
	testObj.style.filter = 'alpha(opacity=' + value * 10 + ')';
}

//function detailsfoundpopup(email, userstatus, firstname, lastname) {
//	setOpacity($get("questions"), 5);
//	if ($get("flyerframe")) $get("flyerframe").src = '/motorquoter/popupscreens/reloadDetails.aspx?email=' + email + '&userstatus=' + userstatus + '&firstname=' + firstname + '&lastname=' + lastname;
//	else console.warn('flyerframe does not exist');
//	$get("popupnew").style.display = '';
//}
function submitbutton(obj) { obj.disabled = 'true'; obj.value = 'Please wait...' }
function submitbutton2(obj) { obj.disabled = 'true'; obj.value = 'Please wait...' }
function resetbuttonobj(obj, txt) { obj.disabled = false; obj.value = txt; }
function resetsubmitbutton() { $get('nextbutton').disabled = false; $get('nextbutton').value = 'Next Page >>'; }
function flipme(obj) { if (obj.src.indexOf('/yes_edit.gif') > -1 || obj.src.indexOf('/no_edit.gif') > -1) { obj.src = obj.src.replace('edit', 'edit_ani'); } }
function flipmeback(obj) { if (obj.src.indexOf('/yes_edit_ani.gif') > -1 || obj.src.indexOf('/no_edit_ani.gif') > -1) { obj.src = obj.src.replace('edit_ani', 'edit'); } }
var tl;
var x = 0, pos = 0;
var l;
var placeholder;
var placeholder2;
var txtholder2;
var alldone = 0;

var placeholder3;
var txtholder3;
var txtdelay = 15;

function ScrollTextBox(obj, txt, obj2, txt2, obj3, txt3) {
	if (txt.length <= 0) return false;
	placeholder = null;
	placeholder2 = null;
	txtholder2 = null;
	placeholder3 = null;
	txtholder3 = null;
	alldone = 0;

	x = pos = 0;
	
	placeholder = obj;
	tl = new textlist(txt);
	l = tl[0].length;

	if (obj2) {
		placeholder2 = obj2;
		txtholder2 = txt2;
	}
	if (obj3) {
		placeholder3 = obj3;
		txtholder3 = txt3;
	}
	texttickertxt();
}

function texttickertxt() {
	placeholder.value = tl[x].substring(0, pos) + "";
	if (pos++ == l) {
		alldone++;
		placeholder.value = tl[x];
		x = 0;
		pos = 0;
		l = 0;
		if (placeholder2 && alldone == 1) { tl = new textlist(txtholder2); l = tl[0].length; placeholder = placeholder2; setTimeout("texttickertxt()", txtdelay); }
		if (placeholder3 && alldone == 2) { tl = new textlist(txtholder3); l = tl[0].length; placeholder = placeholder3; setTimeout("texttickertxt()", txtdelay); }
	}
	else
		setTimeout("texttickertxt()", txtdelay);
}

var running = 0;
var lasttext = '';

function ScrollIn(obj, telnum) {
	placeholder = $get(obj);
	if (lasttext != telnum && running == 0) {
		lasttext = telnum;
		tl = new textlist(telnum);
		l = tl[0].length;
		running = 1;
		textticker();
	}
}

var max = 0;
function textlist() {
	max = textlist.arguments.length;
	if (max <= 0) this[i] = ' ';
	else {
		for (i = 0; i < max; i++) {
			this[i] = textlist.arguments[i];
		}
	}
}

function textticker() {
	placeholder.innerHTML = tl[x].substring(0, pos) + "";
	if (pos++ == l) {
		placeholder.innerHTML = tl[x];
		x = 0;
		pos = 0;
		running = 0;
		return;
		if (x == max) x = 0; l = tl[x].length;
	}
	else
		setTimeout("textticker()", txtdelay);
}


var temphours;
var maxheightin = 20;
function toggle(obj) { var el = $get(obj); if (el.style.display != 'none') { el.style.display = 'none'; } else { el.style.display = ''; } }

function GetQuestionText(questionname) {
	console.log('GetQuestionText(' + questionname + ')');
	var errortext = '';
	if (window.name != 'scriptcontent') {
		var parent = window.self;
	}
	else {
		var parent = window.parent;
	}
	var obj = parent.$get(questionname + 'text');
	if (obj) {
		if (obj.innerHTML.indexOf("<div") > -1) { errortext = obj.innerHTML.toString().substring(0, obj.innerHTML.toString().indexOf('<div')); } else {
			errortext = obj.innerHTML;
		}
		parent.selectmered(questionname.replace('request', ''), 0);
	}
	else {
		if (questionname.indexOf("abi") == -1) {
			//window.status = "alert(" + questionname + ")";
		}
	}
	//alert('GetQuestionText\n\n' + errortext);
	return errortext;
}


function checkfirstpage(onpageload) {

	// un-highlight
	if (window.error_inputs) {
		for (var i = 0; i < window.error_inputs.length; i++) {
			if (window.error_inputs[i]) $removeClass($getParent(window.error_inputs[i], 'tr', $get('questions')), 'error');
		}
	}

	window.error_inputs = [];

	var errorinfo = '';
	var g = 0;
	if ($get("rowcbt")) {
		if (!($get("rowcbt").style.visibility == '')) {
			if ($get("requestcbtdate_year").selectedIndex == 0 || $get("requestcbtdate_month").selectedIndex == 0 && $get("requestcbtdate_day").selectedIndex == 0) {
				errorinfo = "<p>You must enter your CBT pass date.</p>";
				window.error_inputs.push($get("requestcbtdate_day"));
			}
		}
	}
//	if ($get("requestlicencestartdate_age")) {
//		if ($get("requestlicencestartdate_age").innerHTML.indexOf("You must") > -1 || $get("requestlicencestartdate_age").innerHTML.indexOf("please select") > -1) {
//			errorinfo += "<p>The date you passed your test has not been selected, check you have selected your date of birth and when you passed your test.</p>";
//			window.error_inputs.push($get("requestcbtdate_day"));
//		}
//	}
	if ($get("requestlicencestartdate")) {
		if (!$get("requestlicencestartdate").value) {
			errorinfo += "<p>Please select number of years (or months) you have held your licence.</p>";
			window.error_inputs.push($get("requestyearsheldlicence"));
		}
	}

	if ($get("requestregistration2")) {
		if ($get("requestregistration2").value != '' && $get("requestregistration").value != '') {
			if ($get("requestregistration2").value == $get("requestregistration").value) {
				errorinfo += "<p>You cannot enter the same registration in both fields.</p>";
				window.error_inputs.push($get("requestregistration2"));
			}
		}
	}
	var temp_mobiletel = 0;
	var temp_landlinetel = 0;
	if ($F('requestmobiletel') != '') {
		temp_mobiletel = 1;
	}
	if ($F('requesttel') != '') {
		temp_landlinetel = 1;
	}
	if (temp_mobiletel == 1) {
		if (!checkMobileTelephone($get("requestmobiletel").value)) {
			errorinfo += "<p>The mobile telephone number " + $get("requestmobiletel").value + " is invalid, - " + telNumberErrors[telNumberErrorNo] + "</p>";
			window.error_inputs.push($get("requestmobiletel"));
		}
	}
	if (temp_landlinetel == 1) {
		if (!checkUKTelephone($get("requesttel").value)) {
			errorinfo += "<p>The alternative telephone number " + $get("requesttel").value + " is invalid, - " + telNumberErrors[telNumberErrorNo] + "</p>";
			window.error_inputs.push($get("requesttel"));
		}
	}
	if (temp_mobiletel != 1 && temp_landlinetel != 1) {
		errorinfo += "<p>You must supply a telephone number</p>";
		window.error_inputs.push($get("requestmobiletel"));
	}
	$get("requestemail").value = $trim($get("requestemail").value, ' ');
	if (!checkEmail2($get("requestemail").value)) {
		errorinfo += "<p>Your email address is invalid." + "</p>";
		window.error_inputs.push($get("requestemail"));
	}

	if ($get("vehicleMatchMessage").innerHTML.indexOf("No match found") != -1) {
		errorinfo += "<p>No vehicle match found, please amend registration or search by vehicle detail</p>";
		gofocus("requestregistration")
	}

	if (!checkPostCode($get("requestpostcode").value)) {
		errorinfo += "<p>Your postcode is invalid. " + $get("requestpostcode").value + "" + "</p>";
		window.error_inputs.push($get("requestpostcode"));
	}
	var inputs = getElementsByClassStart("flat");
	var tempinput = "";
	for (g = 0; g < inputs.length; g++) {
		if (inputs[g]) {
			if (inputs[g].value == '' && inputs[g].id.indexOf("2") < 0 && inputs[g].id.indexOf("requesttel") < 0 && inputs[g].id.indexOf("cbt") < 0 && inputs[g].id.indexOf("mobiletel") < 0 && inputs[g].id.indexOf("age") == -1 && inputs[g].id.indexOf("registration") == -1) {
				tempinput += PCase(errorformat(inputs[g].id.replace('request', ''))) + ", ";
				window.error_inputs.push(inputs[g]);
			}
		}
	}
	if ($get("vehicleMatchMessage").innerHTML.indexOf("No match found") != -1) {
		errorinfo += "<p>No vehicle match found, please amend registration or search by vehicle detail</p>";
		gofocus("requestregistration")
	}
	if (tempinput != '') {
		errorinfo += "<p>You have not answered:</p><p>" + tempinput + "</p>";
	};
	console.info('errorformat info:');
	console.log(errorinfo);

	// highlight
	if (window.error_inputs) {
		for (var i = 0; i < window.error_inputs.length; i++) {
			if (window.error_inputs[i]) {
				$addClass($getParent(window.error_inputs[i], 'tr', $get('questions')), 'error');
				//if (onpageload && window.error_inputs[i].focus && window.error_inputs[i].style.display != 'none') window.error_inputs[i].focus();
			}
		}
	}

	if (errorinfo == '') {
		window.errorinfo_length = 0;
		if ($get("errortext")) $get("errortext").innerHTML = "";
		toggle("errorpop");
		return true;
	}
	else {
		window.errorinfo_length = errorinfo.length;
		if (!onpageload) {
			toggle("errorpop");
			toggle("errorpop2");
		}
		if ($get("errortext")) $get("errortext").innerHTML = errorinfo;
		return false;
	}
}

function errorformat(s) {
	var retval = s;
	if (s == 'firstname')
		retval = 'First name';
	if (s == 'lastname')
		retval = 'Last name';
	if (s == 'email')
		retval = 'Email address';
	if (s.indexOf('dob') > -1)
		retval = 'Date of birth (' + s.toString().substring(s.indexOf('_') + 1) + ')';
	if (s.indexOf('renew') > -1)
		retval = 'Renewal date (' + s.toString().substring(s.indexOf('_') + 1) + ')';
	if (s.indexOf('status') > -1)
		retval = s.toString().replace('status', ' status');
	if (s == 'fulltimeoccupation')
		retval = 'Full time occupation';
	if (s.indexOf('type') > -1)
		retval = s.toString().replace('type', ' type');
	return retval;
}

function removeErrorHighlights() {
	var trs = $getTags('tr', $get('questions'));
	for (var t = 0, tr; tr = trs[t]; t++) {
		if (tr.id.match(/^row\d|^detail_\d/gi)) {
			$removeClass(tr, 'error');
		}
	}
}

function checkpage() {

	// un-highlight
	removeErrorHighlights();
	/*if (window.error_inputs) {
		for (var i = 0; i < window.error_inputs.length; i++) {
			if (window.error_inputs[i]) {
				$removeClass($getParent(window.error_inputs[i], 'tr', $get('questions')), 'error');
			}
		}
	}*/

	window.error_inputs = [];

	var errorinfo = '';
	if ($get("providerimg_yes")) {
		if ($get("providerimg_yes").src.indexOf("yes_on") > -1) {
			if ($get("providersummary").innerHTML == '') {
				errorinfo += "You have not provided details of your current insurer.  Please click yes on the question to provide details.<br /><br />";
				window.error_inputs.push($get("providersummary"));
			}
		}
	}
	if ($get("medicalconditionsimg_yes").src.indexOf("yes_on") > -1 && $get("medicalconditionssummary").innerHTML == '') {
		errorinfo += "You have not selected you have a medical condition but have not provided details. Please click no on the question to provide details or click select yes.<br/><br/>";
		window.error_inputs.push($get("medicalconditionsimg_yes"));
	}
	if ($get("vehiclekeptdaytimeimg_no")) {
		if ($get("vehiclekeptdaytimeimg_no").src.indexOf("no_on") > -1 && $get("vehiclekeptdaytimesummary").innerHTML == '') {
			errorinfo += "You have not selected where the vehicle will be kept during the day. Please click no on the question to provide details or click select yes.<br/><br/>";
			window.error_inputs.push($get("vehiclekeptdaytimeimg_no"));
		} 
	}
	if ($get("vehiclekeptovernightimg_no")) {
		if ($get("vehiclekeptovernightimg_no").src.indexOf("no_on") > -1 && $get('vehiclekeptovernightsummary').innerHTML == '') {
			errorinfo += "You have not selected where the vehicle is kept overnight. Please click no on the question to provide details or click select yes.<br/><br/>";
			window.error_inputs.push($get("vehiclekeptovernightimg_no"));
		} 
	}
	if ($get("vehicleuseimg_no")) {
		if ($get("vehicleuseimg_no").src.indexOf("no_on") > -1 && $get("vehicleusesummary").innerHTML == '') {
			errorinfo += "You have selected the vehicle is not used for social and domestic, BUT you have not selected another option. Please click no on the question to provide details or click yes.<br/><br/>";
			window.error_inputs.push($get("vehicleuseimg_no"));
		}
	}
	if ($get("additionaldriversofcarimg_no")) {
		if ($get("additionaldriversofcarimg_no").src.indexOf("no_on") > -1 && $get("additionaldriversofcarsummary").innerHTML == '') {
			errorinfo += "You have selected you are not the only user of the vehicle but not entered selected how many other users there are.<br>Please click no on the question to provide details or click yes.<br/><br/>";
			window.error_inputs.push($get("additionaldriversofcarimg_no"));
		}
	}
	if ($get("numberofaccidentsimg_yes").src.indexOf("yes_on") > -1 && $get("numberofaccidentssummary").innerHTML == '') {
		errorinfo += "You have selected you have <u>accidents</u> but you have not provided details of your accident.<br>Please click yes on the question to provide details or click no.<br/><br/>";
		window.error_inputs.push($get("numberofaccidentsimg_yes"));
	}
	if ($get("numberofconvictionsimg_yes").src.indexOf("yes_on") > -1 && $get("numberofconvictionssummary").innerHTML == '') {
		errorinfo += "You have clicked that you have <u>convictions</u> but you have not provided details of your conviction.<br>Please click yes on the question to provide details or click no.<br/><br/>";
		window.error_inputs.push($get("numberofconvictionsimg_yes"));
	}
	if ($get("parttimeoccupationimg_yes").src.indexOf("yes_on") > -1 && $get("parttimeoccupationsummary").innerHTML == '') {
		errorinfo += "You have clicked that you have a <u>part time job</u>, but you have not given details.<br>Please click yes on the question to provide details or click no to move on.<br/><br/>";
		window.error_inputs.push($get("parttimeoccupationimg_yes"));
	}
	if ($get("parttimeoccupationimg_yes").src.indexOf("yes_on") > -1 && $get("requestparttimejobbusinessdescription").value == '') {
		errorinfo += "You have clicked that you have a <u>part time job</u>, but you have not specified the <u>business type</u>.<br>Please click yes on the question to provide details or click no to move on.<br/><br/>";
		window.error_inputs.push($get("parttimeoccupationimg_yes"));
	} 
	if ($get("livedinukimg_no").src.indexOf("no_on") > -1 && $get("livedinuksummary").innerHTML == '') {
		errorinfo += "You have clicked that you have <u>not lived in the UK all your life</u> but not provided the date you moved to the UK.<br>Please click yes on the question to provide details or click no to move on.<br/><br/>";
		window.error_inputs.push($get("livedinukimg_no"));
	}
	if ($get("importedimg_yes")) {
		if ($get("importedimg_yes").src.indexOf("yes_on") > -1 && $get("importedsummary").innerHTML == '') {
			errorinfo += "You have selected that your <u>vehicle is imported</u> but you have not provided details.<br>Please click yes on the question to provide details or click no to move on.<br/><br/>";
			window.error_inputs.push($get("importedimg_yes"));
		} 
	}
	if ($get("ismodifiedimg_yes")) {
		if ($get("ismodifiedimg_yes").src.indexOf("yes_on") > -1 && $get("ismodifiedsummary").innerHTML == '') {
			errorinfo += "You have selected that your <u>vehicle is modified</u> but you have not provided details.<br>Please click yes on the question to provide details or click no to move on.<br/><br/>";
			window.error_inputs.push($get("ismodifiedimg_yes"));
		}
	}

	if ($get("carsecuritydevicesimg_yes") != null) {
		if ($get("carsecuritydevicesimg_yes").src.indexOf("yes_on") > -1 && $get("carsecuritydevicessummary").innerHTML == '') {
			errorinfo += "You have clicked that you have your vehicle has <u>security devices</u> but have not provided details.<br />Please click yes on the question to provide details or click no to move on.<br/><br/>"
			window.error_inputs.push($get("carsecuritydevicesimg_yes"));
		}
	}
	else if ($get("securitydevicesimg_yes") != null) {
		if ($get("securitydevicesimg_yes").src.indexOf("yes_on") > -1 && $get("securitydevicessummary").innerHTML == '') {
			errorinfo += "You have clicked that you have security devices but havent given any details. Please click yes on the question to provide details or click no to move on.<br/><br/>";
			window.error_inputs.push($get("securitydevicesimg_yes"));
		}
	}

	if ($get("advancedqualificationsimg_yes")) {
		if ($get("advancedqualificationsimg_yes").src.indexOf("yes_on") > -1 && $get("advancedqualificationssummary").innerHTML == '') {
			errorinfo += "You have clicked that you have your advanced riding qualifications but havent given any details. Please click yes on the question to provide details or click no to move on.<br/><br/>";
			window.error_inputs.push($get("advancedqualificationsimg_yes"));
		}
	}

	// highlight
	if (window.error_inputs) {
		for (var i = 0; i < window.error_inputs.length; i++) {
			if (window.error_inputs[i]) {
				$addClass($getParent(window.error_inputs[i], 'tr', $get('questions')), 'error');
				//if (onpageload && window.error_inputs[i].focus && window.error_inputs[i].style.display != 'none') window.error_inputs[i].focus();
			}
		}
	}

	if (errorinfo == '')
		return true;
	else {
		window.errorinfo_length = errorinfo.length;
		toggle("errorpop");
		toggle("errorpop2");
		$get("errortext").innerHTML = errorinfo;
		return false;
	}
}

var initial = -413;
var imageWidth = 580;
var eachPercent = (imageWidth / 2) / 100;
/************************************************************\
*
\************************************************************/
function setText(id, percent) {
	$get(id + 'Text').innerHTML = percent + "%";
}
/************************************************************\
*
\************************************************************/
function display(id, percentage, color) {
	if (window.location.href.indexOf("motorquoter") > -1)
	{ color = "1" }
	else if (window.location.href.indexOf("motorbikequoter") > -1)
	{ color = "2" }
	if (typeof color == "undefined") {
		color = "1";
	}
	var percentageWidth = eachPercent * percentage;
	var actualWidth = initial + percentageWidth;
	document.write('<img id="' + id + '" src="/images/percentImage.gif" class="percentImage' + color + '" style="background-position: ' + actualWidth + 'px 0pt;width:293px;height:20px"/>');
}
/************************************************************\
*
\************************************************************/
function emptyProgress(id) {
	var newProgress = initial + 'px';
	$get(id).style.backgroundPosition = newProgress + ' 0';
	setText(id, '0');
}
/************************************************************\
*
\************************************************************/
function getProgress(id) {
	var nowWidth = $get(id).style.backgroundPosition.split("px");
	return (Math.floor(100 + (nowWidth[0] / eachPercent)) + '%');

}
/************************************************************\
*
\************************************************************/
function setProgress(id, percentage) {
	var percentageWidth = eachPercent * percentage;
	var newProgress = eval(initial) + eval(percentageWidth) + 'px';
	$get(id).style.backgroundPosition = newProgress + ' 0';
	setText(id, percentage);
}
/************************************************************\
*
\************************************************************/
function plus(id, percentage) {
	var nowWidth = $get(id).style.backgroundPosition.split("px");
	var nowPercent = Math.floor(100 + (nowWidth[0] / eachPercent)) + eval(percentage);
	var percentageWidth = eachPercent * percentage;
	var actualWidth = eval(nowWidth[0]) + eval(percentageWidth);
	var newProgress = actualWidth + 'px';
	if (actualWidth >= 0 && percentage < 100) {
		var newProgress = 1 + 'px';
		$get(id).style.backgroundPosition = newProgress + ' 0';
	}
	else {
		$get(id).style.backgroundPosition = newProgress + ' 0';
	}
}
/************************************************************\
*
\************************************************************/
function minus(id, percentage) {
	var nowWidth = $get(id).style.backgroundPosition.split("px");
	var nowPercent = Math.floor(100 + (nowWidth[0] / eachPercent)) - eval(percentage);
	var percentageWidth = eachPercent * percentage;
	var actualWidth = eval(nowWidth[0]) - eval(percentageWidth);
	var newProgress = actualWidth + 'px';
	if (actualWidth <= -120) {
		var newProgress = -120 + 'px';
		$get(id).style.backgroundPosition = newProgress + ' 0';
		alert('empty');
	}
	else {
		$get(id).style.backgroundPosition = newProgress + ' 0';
	}
}
function fillProgress(id, endPercent) {
	var nowWidth = $get(id).style.backgroundPosition.split("px");
	startPercent = Math.ceil(100 + (nowWidth[0] / eachPercent)) + 1;
	var actualWidth = initial + (eachPercent * endPercent);
	if (startPercent <= endPercent && nowWidth[0] <= actualWidth) {
		plus(id, '1');
		setTimeout("fillProgress('" + id + "'," + endPercent + ")", 0);
	}
}
//--------------------------------------------------------------------
function SetLicenceStartDateQuestionText(fieldname, searchstring) {
	//YHL
	var lsd = $get('licencestartdate');
	if (lsd && lsd.value) lsd.value = '';
	UpdateYearsHeldLicence();
	return;

	//Set Additional Driver licence question text when the page loads.
	if (parent.$get('requestlicencestartdate_age')) {
		//if($get('requestlicencetype').options[$get('requestlicencetype').selectedIndex].text.indexOf('Provisional')>-1)
		if (searchForString(fieldname, searchstring) == true) {
			parent.$get('lsd').innerHTML = 'Age you obtained your <br />provisional licence.'; //'Age when you got<br>provisional licence.';
		}
		else {
			parent.$get('lsd').innerHTML = 'Age when you <br />passed driving test:';
		}
	}
	else {
		//if($get('requestlicencetype').options[$get('requestlicencetype').selectedIndex].text.indexOf('Provisional')>-1)
		if (searchForString(fieldname, searchstring) == true) {
			parent.$get('lsd').innerHTML = 'Date you obtained your <br />provisional licence.';
		}
		else {
			parent.$get('lsd').innerHTML = 'Date you passed <br />driving test:';
		}
	}
	//if (window.ProcessMotorCycleLicence) ProcessMotorCycleLicence(true);
}

function getDropDownBoxTextFromValue(fieldname) {
	//Returns the text selected for any given dropdown.
	return ($get(fieldname).options[$get(fieldname).selectedIndex].text);
}

function searchForString(fieldname, searchstring) {
	//Returns boolean depending whether the given string is found in the text selected on specified dropdown.
	if (getDropDownBoxTextFromValue(fieldname).indexOf(searchstring) > -1) { return true } else { return false };
}

//----------------------------

function ProcessVehicleResponse(obj, Vehicle, currentVtype) {
	console.log(obj);
	console.dir(Vehicle);
	if (obj && Vehicle && Vehicle.Manufacturer && Vehicle.Manufacturer.toString() != 'undefined'){
		obj.parentNode.style.display = '';
		var vtype = (Vehicle.VType) ? Vehicle.VType.toLowerCase() : '';
		if (vtype == '' || vtype != currentVtype) vtype += ' error';
		console.log(obj);
		obj.innerHTML = '<span class="vehiclematch ' + vtype + '">' + Vehicle.Manufacturer + ' ' + Vehicle.Model + '</span>';
	}
}

function CheckRegAjax(obj, vtype){
	if (obj) {
		obj.innerHTML = '';
		function successHandler(data) { ProcessVehicleResponse(obj, $fromJSON(data), vtype); }
		//function failureHandler(obj) { location.href = "?section="; }
		$postAJAX("/loginAjaxRequester.aspx", successHandler, "function=checkvehicle&reg=" + $get("requestregistration").value);
	}
}

function copyAddrress(copyfrom, copyto) {
	var obj = copyValue(copyfrom, copyto);
	obj = copyValue(copyfrom + '.Postcode', copyto + '.Postcode');
	obj = copyValue(copyfrom + '.Town', copyto + '.Town');
	obj = copyValue(copyfrom + '.County', copyto + '.County');
	obj = copyValue(copyfrom + '.Display', copyto + '.Display');
}

function copyValue(from, to) {
	var oFrom = $get(from) || $get('#' + from) || $get('##' + from);
	var oTo = $get(to) || $get('#' + to) || $get('##' + to);
	if (oTo) {
		oTo.value = (oFrom) ? oFrom.value : '';
	}
	return oTo;
}
function compareValue(from, to) {
	var oFrom = $get(from) || $get('#' + from) || $get('##' + from);
	var oTo = $get(to) || $get('#' + to) || $get('##' + to);
	if (oTo && oFrom && oFrom.value && oTo.value) {
		if (oFrom.value == oTo.value) return true;
		else return false;
	}
	return null;
}

function useSameAddress(tickbox, copyto, copyfrom, click) {
	var setTick = (click == undefined) ? compareValue(copyfrom, copyto) : tickbox.checked;
	if (setTick) { // Same
		tickbox.checked = true;
		var obj = $get('#KeptOvernightAtBusinessAddress');
		obj.value = 'same';
		// hidden
		obj = copyValue(copyfrom, copyto);
		// visible
		obj = $get(copyto + '.Postcode.LookUp') || $get('#' + copyto + '.Postcode.LookUp');
		if (obj) obj.style.display = 'none';
		obj = copyValue(copyfrom + '.Postcode', copyto + '.Postcode');
		if (obj) obj.disabled = 'disabled';
		obj = copyValue(copyfrom + '.Town', copyto + '.Town');
		if (obj) obj.disabled = 'disabled';
		obj = copyValue(copyfrom + '.County', copyto + '.County');
		if (obj) obj.disabled = 'disabled';
		obj = copyValue(copyfrom + '.Display', copyto + '.Display');
		if (obj) obj.disabled = 'disabled';
		if (click != undefined) {
			//MoveToNextInputNamed('nextbutton');
			var nxt = $get('nextbutton');
			//if (nxt) nxt.onclick.apply()
			if (nxt) selectme(nxt);
		}
	}
	else { // Diff
		tickbox.checked = false;
		var obj = $get('#KeptOvernightAtBusinessAddress');
		obj.value = 'different';
		// visible
		obj = $get(copyto + '.Postcode') || $get('#' + copyto + '.Postcode');
		if (obj) obj.disabled = '';
		obj = $get(copyto + '.Postcode.LookUp') || $get('#' + copyto + '.Postcode.LookUp');
		if (obj) obj.style.display = '';
		obj = $get(copyto + '.Town') || $get('#' + copyto + '.Town');
		if (obj) obj.disabled = '';
		obj = $get(copyto + '.County') || $get('#' + copyto + '.County');
		if (obj) obj.disabled = '';
		obj = $get(copyto + '.Display') || $get('#' + copyto + '.Display');
		if (obj) obj.disabled = '';
		if (click != undefined) MoveToNextInputNamed('VanProposal.InsuredItems[0].AddressKeptOvernight.Postcode');
	}
	return tickbox.checked;
}

////////// focusFirstEmptyQuestion ////////////
/* focuses on fist ERRORed field as specifed by checkfirstpage() */
function focusFirstEmptyQuestion() {
	//var inputs = $combineArrays($getTags('select', $get('questions')), $getTags('input', $get('questions')));
	var inputs = document.forms['quoteform'];
	var field = null;
	var fieldB = null;
	var requestEdit = null;
	if (inputs && inputs.length) {
		for (var i = 0, f; f = inputs[i]; i++) {
			if (f.id.indexOf('request') == 0 || f.id.indexOf('VanProposal') == 0) {
				if (!f.value && f.type != 'hidden' && f.style.display != 'none') {
					if (!fieldB) fieldB = f;
					if ($inArray(window.error_inputs, f) !== false) {
						field = f;
						break;
					}
				}
			}
		}
	}
	if (!field || !field.focus) field = fieldB;
	if (field && field.focus) {
		window.setTimeout(function() {
			field.focus()
		}, 300); // allows loading the correct easyfill
	}
	return field || { id: '' };
}
////////////////////////////////////////////////


function selectFirstInputOnPage(errors) {
	if (focusFirstEmptyQuestion && focusFirstEmptyQuestion.call) return focusFirstEmptyQuestion().id;
	else {
		errors = errors || window.error_inputs || [];
		if (window.jQuery) {
			var list = jQuery('select, input, textarea');
		}
		else {
			var texts = $getTags('textarea', $get('questions')) || [];
			var inputs = $getTags('input', $get('questions')) || [];
			var selects = $getTags('select', $get('questions')) || [];
			var list = $nodelistToArray(selects, inputs, texts);
		}
		var id = '';
		if (errors.length) {
			for (var i = 0; i < list.length; i++) {
				if ($inArray(errors, list[i]) && list[i].focus) {
					//list[i].focus();
					id = list[i].id;
					break;
				}
			}
		}
		else {
			for (var i = 0; i < list.length; i++) {
				if ($hasClass(list[i], 'error')) {
					//list[i].focus();
					id = list[i].id;
					break;
				}
			}
		}
		if (id == '' && list.length) id = id = list[0].id;
		$get(id).focus();
		return id;
	}
	
}

/*----------------------------------------------------*/
/* Keeps easyfill the same height as its parent td	*/
/*----------------------------------------------------*/
jQuery(document).ready(function() {
	if (window == window.top) {
		var element = window.parent.jQuery('.outerIframe');
		var iframe = jQuery('#scriptcontent');
		iframe.height(element.height());
		jQuery(element).bind('resize', function(e) {
			iframe.height(element.height());
		});
	}
});



function SetCustomer(customertype, url) {
	if (!url) url = "/generic/userarea/index.aspx";
	function successHandler2(data) { document.location.href = url; }
	function failureHandler2(data) { location.href = "?section="; }
	//YAHOO.util.Connect.asyncRequest("POST", "/loginAjaxRequester.aspx", { success: successHandler2, failure: failureHandler2 }, "function=" + customertype);
	$postAJAX(
		"/loginAjaxRequester.aspx",
		successHandler2,
		"function=" + customertype,
		failureHandler2
	);
}
function SetCustomerType(url, customertype) {
	function successHandler2(data) { document.location.href = url; }
	function failureHandler2(data) { document.location.href = url; }
	//YAHOO.util.Connect.asyncRequest("POST", "/loginAjaxRequester.aspx", { success: successHandler2, failure: failureHandler2 }, "function=" + customertype);
	$postAJAX(
		"/loginAjaxRequester.aspx",
		successHandler2,
		"function=" + customertype,
		failureHandler2
	);
}


// YHL //
/*****	How Long Have You Held Licence For	*****************************/
var driverString;
$addEvent(window, 'load', function() {
	var match = document.location.search.match(/additionaldriverid=(\d)/i);
	driverString = (match) ? 'AdditionalDrivers[' + (parseInt(match[1], 10) - 1) + ']' : 'MainDriver';
});

function YearsHeldLicenceOptions(DOB, MinAge, Today, MaxYearsAgo) {
	var returnList = [];
	if (DOB && DOB.getFullYear()) {
		Today = Today || new Date();
		MinAge = MinAge || 17;
		MaxYearsAgo = MaxYearsAgo || 10;
		console.log('YearsHeldLicenceOptions', DOB, MinAge, Today, MaxYearsAgo)
		if (DOB.age(Today) >= MinAge) {
			//var MinYear = MinAge + DOB.getFullYear();
			//var MaxYearsAgo = Today.getFullYear() - MinYear + 1;
			//if (MaxYearsAgo < 0) MaxYearsAgo = 0;
			//console.log(0 + ' years   (' + Today.toDateString() + ')	(aged ' + DOB.age(Today) + ')');
			returnList[0] = 'Less than a year';
			for (var x = 1; x <= MaxYearsAgo; x++) {
				optDate = new Date((Today.getFullYear() - x), Today.getMonth(), Today.getDate());
				// final option adjusted to fit birthday if min age very close!
				if (DOB.age(optDate) == MinAge - 1 && optDate.getMonth() == DOB.getMonth() /*&& Today.getMonth() == DOB.getMonth()*/) {
					optDate = new Date(optDate.getFullYear(), DOB.getMonth(), DOB.getDate());
				}
				if (DOB.age(optDate) >= MinAge) {
					if (x == MaxYearsAgo) {
						returnList[x] = x + ' years or more';
						//console.log(x + ' years or more	(' + optDate.toDateString() + ')	(aged ' + DOB.age(optDate) + ')');
						break;
					} else {
						returnList[x] = x + ' year' + ((x == 1) ? '' : 's');
						//console.log(x + ' years	(' + optDate.toDateString() + ')	(aged ' + DOB.age(optDate) + ')');
					}
				}

			}
		}
	}
	return returnList;
}

function MonthsHeldLicenceOptions(DOB, MinAge, Today) {
	var returnList = [];
	if (DOB && DOB.getFullYear()) {
		Today = Today || new Date();
		MinAge = MinAge || 17;
		if (DOB.age(Today) >= MinAge) {
			var MinYear = MinAge + DOB.getFullYear();
			if (MinYear > Today.getFullYear()) MinYear = Today.getFullYear();
			var MaxMonthsAgo = 11;
			//console.log(0 + ' months	(' + Today.toDateString() + ')	(aged ' + DOB.age(Today) + ')');
			returnList[0] = 'Less than a month';
			for (var x = 1, m; x <= MaxMonthsAgo; x++) {
				m = Today.getMonth() - x;
				if (m < 0) {
					optDate = new Date(Today.getFullYear() - 1, 12 - (-1 * m), Today.getDate());
				}
				else {
					optDate = new Date(Today.getFullYear(), m, Today.getDate());
				}
				if (DOB.age(optDate) >= MinAge) {
					returnList[x] = x + ' month' + ((x == 1) ? '' : 's');
					//console.log(x + ' months	(' + optDate.toDateString() + ')	(aged ' + DOB.age(optDate) + ')');
				}
				else {
					if (m < 0) {
						optDate = new Date(Today.getFullYear() - 1, 12 - (-1 * m), DOB.getDate());
					}
					else {
						optDate = new Date(Today.getFullYear(), m, DOB.getDate());
					}
					if (DOB.age(optDate) >= MinAge) {
						returnList[x] = x + ' month' + ((x == 1) ? '' : 's');
						console.log(x + ' months	(' + optDate.toDateString() + ')	(aged ' + DOB.age(optDate) + ')');
					}
				}
			}
		}
	}
	return returnList;
}


var MaxYearsHeldLicence = 10;
var MinLicenceStartAge = 17;
var messageElement;
var yearsHeldElement;
var monthsHeldElement;
var AfterYearsHeldLicence = function() { };

function UpdateYearsHeldLicence(dobY, dobM, dobD) {
	MinLicenceStartAge = (($hasClass(document.body, 'motorbikequoter')) ? getMinAgePassedLicence(/*for bike*/) : 17);
	MaxYearsHeldLicence = _.MaxYears || MaxYearsHeldLicence;
	messageElement = messageElement || $get('yhlSummary');
	yearsHeldElement = yearsHeldElement || $get('requestyearsheldlicence');
	monthsHeldElement = monthsHeldElement || $get('requestmonthsheldlicence');
	var message = 'Please specify your date of birth';
	// check DOB
	dobY = dobY || $getVal('requestdob_year');
	dobM = dobM || $getVal('requestdob_month') - 1;
	dobD = dobD || $getVal('requestdob_day');
	var DOB = Date.makeDate(dobY, dobM, dobD);
	if (DOB) {
		var today = new Date();
		var MinDate = (new Date(DOB.getFullYear() + MinLicenceStartAge, DOB.getMonth(), DOB.getDate()));
		console.info('Min Age:', MinLicenceStartAge);
		console.info('Min Date:', MinDate.dateString());
		console.info('Today:', today.dateString());
		console.info('Age @ Today:', DOB.age(today));
		console.info('Age @ MinDate:', DOB.age(MinDate));
		if (DOB.age(today) >= MinLicenceStartAge) {
			message = 'error generating list';
			var years = YearsHeldLicenceOptions(DOB, MinLicenceStartAge, today, MaxYearsHeldLicence);
			var months = MonthsHeldLicenceOptions(DOB, MinLicenceStartAge, today);
			if (years && years.length && months && months.length) {
				message = '';
				var selectedYear = null, selectedMonth = null;

				var lsd = new Date(Date.parse($getVal('licencestartdate')));
				console.log('lsd: ' + lsd + ' (' + $getVal('licencestartdate') + ')');
				if (lsd.isDate()) {
					console.log('load lsd');
					selectedYear = Math.floor(Math.abs(lsd.getMonthsAway()) / 12);
					if (selectedYear === 0) selectedMonth = Math.floor(Math.abs(lsd.getMonthsAway()));
					else if (selectedYear > MaxYearsHeldLicence) selectedYear = MaxYearsHeldLicence;
				}
				monthsHeldElement.style.display = 'none';

				removeAllOptions(yearsHeldElement);
				addOption(yearsHeldElement, 'Select ->', '', (selectedYear == null));
				for (var i = 0, y; y = years[i]; i++) {
					addOption(yearsHeldElement, y, i, (i == selectedYear));
				}
				removeAllOptions(monthsHeldElement);
				addOption(monthsHeldElement, 'Select ->', '', (selectedMonth == null));
				for (var i = 0, m; m = months[i]; i++) {
					addOption(monthsHeldElement, m, i, (i == selectedMonth));
				}
				if (selectedMonth !== null) {
					monthsHeldElement.style.display = '';
				}
				else {
					if (DOB.age(today) < MinLicenceStartAge) {
						message = 'Bellow minimum age to obtain licence.';
					} else {
						yearsHeldElement.style.display = '';
						if (years.length == 1) {
							yearsHeldElement.value = '0';
							selectedYearsHeld();
						}
						else {
							monthsHeldElement.style.display = 'none';
						}
						if (months.length == 1) {
							monthsHeldElement.value = '0';
							selectedMonthsHeld();
						}
					}
				}
			}
		}
		else {
			message = 'You must be at least ' + MinLicenceStartAge + ' for a valid licence.';
			yearsHeldElement.value = '';
			monthsHeldElement.value = '';
			yearsHeldElement.style.display = 'none';
			monthsHeldElement.style.display = 'none';
			$get('requestlicencestartdate').value = '';
			$get('licencestartdate').value = '';
		}
	}
	if (message) {
		console.log('YHL message: ' + message);
		messageElement.innerHTML = message;
		if (message.indexOf('You must be at least') == 0) {
			messageElement.style.display = '';
		}
		else messageElement.style.display = 'none';
	} else {
		messageElement.style.display = 'none';
		yearsHeldElement.style.display = '';
	}
	return !!DOB;
}

function selectedYearsHeld() {
	messageElement = messageElement || $get('yhlSummary');
	yearsHeldElement = yearsHeldElement || $get('requestyearsheldlicence');
	monthsHeldElement = monthsHeldElement || $get('requestmonthsheldlicence');
	var dobY = dobY || $getVal('requestdob_year');
	var dobM = dobM || $getVal('requestdob_month') - 1;
	var dobD = dobD || $getVal('requestdob_day');
	var DOB = Date.makeDate(dobY, dobM, dobD);
	var dateAtMinAge = DOB.add(MinLicenceStartAge, 'y');
	var DptAssumed = null, message = 'Please select how many full years you have held your licence.';
	if (yearsHeldElement.value) {
		var years = yearsHeldElement.value / 1;
		var today = new Date();
		console.log('selected years held: ' + years);
		if (years <= 0 /*|| dob.age(DptAssumed) == minAge*/) {
			monthsHeldElement.style.display = '';
			message = 'Please select how many full months you have held your licence.';
		}
		else {
			monthsHeldElement.style.display = 'none';
			//DptAssumed = Date.makeDate((new Date()).getFullYear() - years);
			DptAssumed = today.add(years * -1, 'y');

			// adjust for edge-case
			if (DOB.age(DptAssumed) < MinLicenceStartAge) {
				//console.log('diff in days between min age and assumed pass date: ' + DptAssumed.getDaysAway(dateAtMinAge));
				if (DptAssumed.getDaysAway(dateAtMinAge) < 0) {
					console.log('adjusting from ' + DptAssumed.dateString() + ' to ' + dateAtMinAge.dateString());
					DptAssumed = dateAtMinAge;
				} 
			}
			
			message = '';
			console.info('Assumed Pass Date: ' + DptAssumed.dateString() + ' @ age ' + DOB.age(DptAssumed) + ' (' + DOB.dateString() + ')');
		}
	}
	if (message) {
		console.log('YHL message: ' + message);
		messageElement.innerHTML = message;
		//messageElement.style.display = '';
		$get('requestmonthsheldlicence').value = '';
		$get('requestlicencestartdate').value = '';
		if (($get('requestyearsheldlicence')).value == '0') {
			$get('requestmonthsheldlicence').focus();
		}
		//selectedMonthsHeld();
	} else {
		//messageElement.style.display = 'none';
		if (DptAssumed) { // save
			saveAssumedLicenceStartDate(DptAssumed);
		}
	}
}
function selectedMonthsHeld() {
	messageElement = messageElement || $get('yhlSummary');
	yearsHeldElement = yearsHeldElement || $get('requestyearsheldlicence');
	monthsHeldElement = monthsHeldElement || $get('requestmonthsheldlicence');
	var dobY = dobY || $getVal('requestdob_year');
	var dobM = dobM || $getVal('requestdob_month') - 1;
	var dobD = dobD || $getVal('requestdob_day');
	var DOB = Date.makeDate(dobY, dobM, dobD);
	var dateAtMinAge = DOB.add(MinLicenceStartAge, 'y');
	var DptAssumed = null, message = 'Please select how many full months you have held your licence.';
	if (yearsHeldElement.value && monthsHeldElement.value) {
		var today = new Date();
		var years = yearsHeldElement.value / 1;
		var months = monthsHeldElement.value / 1;
		console.log('DOB: ' + DOB.dateString());
		console.log('selected years held: ' + years);
		console.log('selected months held: ' + months);
		console.log('min age: ' + MinLicenceStartAge + ' @ ' + dateAtMinAge.dateString() + '(' + today.getYearsAway(dateAtMinAge) + ' years / ' + today.getMonthsAway(dateAtMinAge) + ' months / ' + today.getDaysAway(dateAtMinAge) + ' days).');
		if (months == 0) {
			var DptAssumed = today.add(-1, 'm').add(1, 'd');
		}
		else var DptAssumed = today.add(years * -1, 'y').add(months * -1, 'm');
		// adjust for edge-case
		if (DOB.age(DptAssumed) < MinLicenceStartAge) {
			//console.log('diff in days between min age and assumed pass date: ' + DptAssumed.getDaysAway(dateAtMinAge));
			if (DptAssumed.getDaysAway(dateAtMinAge) < 0) {
				console.log('adjusting from ' + DptAssumed.dateString() + ' to ' + dateAtMinAge.dateString());
				DptAssumed = dateAtMinAge;
			}
		}
		
		if (!DptAssumed) message = 'Error creating date.';
		else {
			message = '';
			console.info('Assumed Pass Date: ' + DptAssumed.dateString() + '( @ age ' + DOB.age(DptAssumed) + ')');
		}
	}
	if (message) {
		console.log('YHL message: ' + message);
		messageElement.innerHTML = message;
		$get('requestlicencestartdate').value = '';
		//messageElement.style.display = '';
	} else {
		//messageElement.style.display = 'none';
		if (DptAssumed) { // save
			saveAssumedLicenceStartDate(DptAssumed);
		}
	}
}

function saveAssumedLicenceStartDate(DptAssumed) {
	console.log(DptAssumed.dateString());
	$get('requestlicencestartdate').value = DptAssumed.vbStringDate();
	if (window.AfterYearsHeldLicence && AfterYearsHeldLicence.call) AfterYearsHeldLicence(DptAssumed);
	MoveToNextInputNamed('requestregistration');
}

// end YHL //

//document.getElementById('scriptcontent').src = 'YourHelper.aspx?question=requestpostcodelookup&postcode=' + document.quoteform.requestpostcode.value + '&firstname=' + escape(document.quoteform.requestfirstname.value) + '&lastname=' + escape(document.quoteform.requestlastname.value);


function postcodeLookup() {
	var ef = $get('scriptcontent');
	if (ef) {
		var field = $get('requestpostcode') || $get('VanProposal.Business.Address.Postcode');
		field.focus();
		ef.src = 'yourhelper.aspx?question=noquestion';
		var url = document.location.href;
		field.value = $trim(field.value);
		window.setTimeout(function () {
			if (document.body.className.indexOf('commercialvehicle') >= 0) {
				ef.src = 'yourhelper.aspx?question=VanProposal.Business.Address&postcode=' + field.value;
			}
			else {
				ef.src = 'yourhelper.aspx?question=requestpostcodelookup&postcode=' + field.value + '&firstname=' + escape(document.quoteform.requestfirstname.value) + '&lastname=' + escape(document.quoteform.requestlastname.value);
			}
		}, 250);
		window.focuswhere = 1;
		window.onEasyfillReady = null;
	}
}



