function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

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

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

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

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

function MM_jumpMenuGo(selName,targ,restore){ //v3.0
  var selObj = MM_findObj(selName); if (selObj) MM_jumpMenu(targ,selObj,restore);
}

function MM_validateForm() { //v4.0 modified
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name;nm=nm.replace(/_/g,' '); if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_showHideLayers_display() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers_display.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'block':(v=='hide')?'none':v; }
    obj.display=v; }
}

function MM_showHideLayers2() { //v6.0
	var i,p,v,obj,args=MM_showHideLayers2.arguments;
	for (i=0; i<(args.length-2); i+=3) {
		if ((obj=MM_findObj(args[i]))!=null) {
			v=args[i+2];
			v2=args[i+2];
		}
		if (obj.style) {
			obj=obj.style;
			v=(v=='show')?'visible':(v=='hide')?'hidden':v;
			v2=(v2=='show')?'block':(v2=='hide')?'none':v2;
		}
		obj.visibility=v;
		obj.display=v2;
	}
}

function confirmemail() {
	if (document.MM_returnValue && (document.contactform.subscribe[0].checked == false && document.contactform.subscribe[1].checked == false)) {
		alert("Please complete:\n- Do you wish to receive regular email updates?");
		document.MM_returnValue = false;
	}
}

function check_section1(maximum) {
	//return; // switched off
	var checked = 0;
	var n;
	for (n = 1; n <= maximum; n++) {
		if (eval("document.contactform.s" + n + "[0].checked")) {
			checked++;
		}
	}
	if (checked != maximum) {
		MM_showHideLayers('section2Layer','','hide');
		MM_showHideLayers_display('section2Layer','','hide');
	} else {
		MM_showHideLayers('section2Layer','','show');
		MM_showHideLayers_display('section2Layer','','show');
		$(document).ready(function(){
			$.scrollTo('#section2Layer', 500);
		});
	}
}

function check_section1_no() {
	alert('Sorry, you do not meet the eligibility criteria of this product.');
}

//http://www.somacon.com/p143.php
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

/*function disableCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].disabled = true;
		}
	}
}*/

function setSelectedValue(selectObj, newValue) {
	if (!selectObj)
		return;
	var selectLength = selectObj.length;
	if(selectLength == undefined) {
		selectObj.value = newValue.toString();
		return;
	}
	for (var i = 0; i < selectObj.length; i++) {
		selectObj[i].selected = false;
		if (selectObj[i].value == newValue.toString()) {
			selectObj[i].selected = true;
		}
	}
}

/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Manzi Olivier :: http://www.imanzi.com/ */

// calculate the ASCII code of the given character
function CalcKeyCode(aChar) {
  var character = aChar.substring(0,1);
  var code = aChar.charCodeAt(0);
  return code;
}

function checkNumber(val) {
  var strPass = val.value;
  var strLength = strPass.length;
  var lchar = val.value.charAt((strLength) - 1);
  var cCode = CalcKeyCode(lchar);

  /* Check if the keyed in character is a number
     do you want alphabetic UPPERCASE only ?
     or lower case only just check their respective
     codes and replace the 48 and 57 */

  //if (cCode < 48 || cCode > 57 ) {
  if ( !((cCode >= 48 && cCode <= 57) || cCode == 46) ) {
    var myNumber = val.value.substring(0, (strLength) - 1);
    val.value = myNumber;
  }
  return false;
}

function app_dateform(f) { //not used
	eval('var d = ' + f + '_d.options[' + f + '_d.selectedIndex].value;');
	eval('var m = ' + f + '_m.options[' + f + '_m.selectedIndex].value;');
	eval('var y = ' + f + '_y.options[' + f + '_y.selectedIndex].value;');
	if (d + '' != '' && m + '' != '' && y + '' != '') {
		eval(f + '.value = ' + f + '_d.options[' + f + '_d.selectedIndex].value + \'/\' + ' + f + '_m.options[' + f + '_m.selectedIndex].value + \'/\' + ' + f + '_y.options[' + f + '_y.selectedIndex].value;');
	}
		//eval('alert(' + f + '.value);');
}

function update_bti_vri_owned_length_select(formfield, newused, month, year, limit) {
	var month_text = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
	if (limit == null) { //optional default
		var limit = (newused == 'Used' ? 7 : 13);
	}
	//var month = <? echo date('m') - 1; ?>;
	//var year= <? echo date('Y'); ?>;
	//eval('var o = document.' + formfield + ';');
	var o = formfield;
	if (newused == 'Used') {
		var start = 0;
	} else {
		var start = -1;
		month++;
		if (month > 11) {
			month = 0;
			year++;
		}
	}
	for (n = o.length; n >= 0; n--) {
		o[n] = null;
	}
	for (n = start; n < limit; n++) {
		o[o.length] = new Option(month_text[month] + ' ' + year, n, (n == 0 ? true : false), (n == 0 ? true : false));
		month--;
		if (month < 0) {
			month = 11;
			year--;
		}
	}
}

/*function pcaFastAddressBegin(postcode, building)
   { //, language, style, account_code, license_code, machine_id, options
      var language = 'english';
	  var style = 'simple';
	  var account_code = 'alexa11126'; 
	  var license_code = 'rc39-uh17-bx54-hk86';
	  var machine_id = '';
	  var options = '';      
	  
	  var scriptTag = document.getElementById("pcaScriptTag");
      var headTag = document.getElementsByTagName("head").item(0);
      var strUrl = "";

      //Build the url
      strUrl = "https://services.postcodeanywhere.co.uk/inline.aspx?";
      strUrl += "&action=fetch";
      strUrl += "&postcode=" + escape(postcode);
      strUrl += "&building=" + escape(building);
      strUrl += "&language=" + escape(language);
      strUrl += "&style=" + escape(style);
      strUrl += "&account_code=" + escape(account_code);
      strUrl += "&license_code=" + escape(license_code);
      strUrl += "&machine_id=" + escape(machine_id);
      strUrl += "&options=" + escape(options);
      strUrl += "&callback=pcaFastAddressEnd";

      //Make the request
      if (scriptTag) 
         {
            headTag.removeChild(scriptTag);
         }
      scriptTag = document.createElement("script");
      scriptTag.src = strUrl;
      scriptTag.type = "text/javascript";
      scriptTag.id = "pcaScript";
      headTag.appendChild(scriptTag);
   }

function pcaFastAddressEnd()
   {
      //Test for an error
      if (pcaIsError)
         {
            //Show the error message
            alert(pcaErrorMessage);
         }
      else
         {
            //Check if there were any items found
            if (pcaRecordCount==0)
               {
                  alert("Sorry, no matching items found");
               }
            else
               {
                  //document.getElementById("Company_name").value=pca_organisation_name[0];
                  document.getElementById("Address_1").value=pca_line1[0];
                  document.getElementById("Address_2").value=pca_line2[0];
                  document.getElementById("Address_3").value=pca_line3[0];
                  document.getElementById("Address_4").value=pca_post_town[0];
                  //document.getElementById("county").value=pca_county[0];
                  document.getElementById("Postcode").value=pca_postcode[0];
               }
         }
   }*/

// postcodeanywhere start
var pca_account_code='alexa11126';
var pca_license_code='rc39-uh17-bx54-hk86';
var pca_machine_id='';
var pca_request_type;
var pca_parameters;

function lookupAddress()
{

	document.getElementById("addressLayer").style.display = 'block';

	if (document.getElementById("divExhausted").style.display != 'block')
	{
		if (trim(document.getElementById('Postcode').value).length > 4)
		{
			pca_request_type = 'by_postcode';
			pca_parameters = '&postcode=' + escape(trim(document.getElementById('Postcode').value));
		}
		else if (trim(document.getElementById('Postcode').value).length > 1)
		{
			pca_request_type = 'by_outcode';
			pca_parameters = '&outcode=' + escape(trim(document.getElementById('Postcode').value));
		}
		
		pcaLookupBegin();
	}
	
}

function selectItem()
{
	switch(pca_request_type)
	{
		case 'by_streetkey':
			pca_parameters = '&streetkey=' + escape(document.getElementById("lstAddresses").value);
			pcaLookupBegin();
			break;
		case 'by_localitykey':
			pca_parameters = '&localitykey='  + escape(document.getElementById("lstAddresses").value);
			pcaLookupBegin();
			break;
		default: pcaFetchBegin();
	}
}

function pcaLookupBegin()
{
	var scriptTag = document.getElementById("pcaScriptTag");
	var headTag = document.getElementsByTagName("head").item(0);
	var strUrl = "";

	//document.getElementById("divInstructions").style.display = 'none';
	document.getElementById("divLoading").style.display = 'block';
	document.getElementById("divList").style.display = 'none';
	//document.getElementById("divResult").style.display = 'none';
	document.getElementById("divNoItems").style.display = 'none';

	//Build the url
	strUrl = 'https://services.postcodeanywhere.co.uk/inline.aspx?';
	if (pca_request_type == 'cleanse')
	{
		strUrl += '&action=cleanse';
	}
	else
	{
		strUrl += '&action=lookup';
		strUrl += '&type=' + pca_request_type;
	}
	strUrl += pca_parameters;
	strUrl += '&account_code=' + escape(pca_account_code);
	strUrl += '&license_code=' + escape(pca_license_code);
	strUrl += '&callback=pcaLookupEnd';

	//Make the request
	if (scriptTag)
	{
		//The following 2 lines perform the same function and should be interchangeable
		headTag.removeChild(scriptTag);
		//scriptTag.parentNode.removeChild(scriptTag);
	}
	scriptTag = document.createElement("script");
	scriptTag.src = strUrl
	scriptTag.type = "text/javascript";
	scriptTag.id = "pcaScriptTag";
	headTag.appendChild(scriptTag);
}

function pcaLookupEnd()
{
	clearResultsList();
	document.getElementById("divLoading").style.display = 'none';

	//Test for an error
	if (pcaIsError)
	{
		//Show the error message
		if (pcaErrorNumber == 8 || pcaErrorNumber == 4)
		{
			document.getElementById("divExhausted").style.display = 'block';
		}
		else document.getElementById("divNoItems").style.display = 'block';
		//alert(pcaErrorMessage);
	}
	else
	{
		//Check if there were any items found
		if (pcaRecordCount==0)
		{
			/*if (pca_request_type == 'by_streetfiltered' && trim(document.getElementById('txtStreet').value) != '')
			{
				pca_request_type = 'by_street';
				pca_parameters = '&street=' + escape(trim(document.getElementById('txtStreet').value)) + '&town=' + escape(trim(document.getElementById('txtTown').value));
				pcaLookupBegin();
			}
			else*/ document.getElementById("divNoItems").style.display = 'block';
		}
		else
		{
			
			for (i=0; i<pca_id.length; i++)
			{
				document.getElementById("lstAddresses").options[document.getElementById("lstAddresses").length] = new Option(pca_description[i], pca_id[i]);
			}
			
			document.getElementById("divList").style.display = 'block';
			document.getElementById("lstAddresses").focus();
			document.getElementById("lstAddresses").selectedIndex = 0;
			document.getElementById("lstAddresses").scrollIntoView();
			
			//Check the lookup type to set the follow up type
			if (pca_request_type == 'by_outcode')
			{
				pca_request_type = 'by_localitykey';
			}
			else if (pca_request_type == 'by_street' || pca_request_type == 'by_localitykey')
			{
				pca_request_type = 'by_streetkey';
			}
			else pca_request_type = 'fetch';
			
			if (pcaRecordCount==1)
			{
				selectItem();
			}
			
		}
	}
}

function pcaFetchBegin()
{
	var address_id = document.getElementById("lstAddresses").value;
	var scriptTag = document.getElementById("pcaScriptTag");
	var headTag = document.getElementsByTagName("head").item(0);
	var strUrl = "";

	//Build the url
	strUrl = "https://services.postcodeanywhere.co.uk/inline.aspx?";
	strUrl += "&action=fetch";
	strUrl += "&id=" + escape(address_id);
	strUrl += "&account_code=" + escape(pca_account_code);
	strUrl += "&license_code=" + escape(pca_license_code);
	strUrl += "&machine_id=" + escape(pca_machine_id);
	strUrl += "&callback=pcaFetchEnd";

	//Make the request
	if (scriptTag)
	{
		//The following 2 lines perform the same function and should be interchangeable
		headTag.removeChild(scriptTag);
		//scriptTag.parentNode.removeChild(scriptTag);
	}
	scriptTag = document.createElement("script");
	scriptTag.src = strUrl
	scriptTag.type = "text/javascript";
	scriptTag.id = "pcaScriptTag";
	headTag.appendChild(scriptTag);
}

function pcaFetchEnd()
{
	//Hide the list
	document.getElementById("divList").style.display = 'none';
	//document.getElementById("divResult").style.display = 'block';
	
	if (pcaIsError)
	{
		//Show the error message
		alert(pcaErrorMessage);
	}
	else
	{
		//Check if there were any items found
		if (pcaRecordCount==0)
		{
			document.getElementById("divNoItems").style.display = 'block';
		}
		else
		{
			
			//Clear the results first
			if (document.getElementById("Company_name")) {
				document.getElementById("Company_name").value = '';
			}
			document.getElementById("Address_1").value = '';
			document.getElementById("Address_2").value = '';
			document.getElementById("Town").value = '';
			document.getElementById("County").value = '';
			document.getElementById("Postcode").value = '';

			if (pca_organisation_name[0] != '')
			{
				if (document.getElementById("Company_name")) {
					document.getElementById("Company_name").value = pca_organisation_name[0];
				}
			}
			if (pca_line1[0] != '')
			{
				document.getElementById("Address_1").value = pca_line1[0];
			}
			if (pca_line2[0] != '')
			{
				document.getElementById("Address_2").value = pca_line2[0];
			}
			/*if (pca_line3[0] != '')
			{
				document.getElementById("").value = pca_line3[0];
			}
			if (pca_line4[0] != '')
			{
				document.getElementById("").value = pca_line4[0];
			}
			if (pca_line5[0] != '')
			{
				document.getElementById("").value = pca_line5[0];
			}*/
			if (pca_post_town[0] != '')
			{
				document.getElementById("Town").value = pca_post_town[0];
				if (pca_county[0] == '') {
					document.getElementById("County").value = pca_post_town[0];
				}
			}
			if (pca_county[0] != '')
			{
				document.getElementById("County").value = pca_county[0];
			}
			if (pca_postcode[0] != '')
			{
				document.getElementById("Postcode").value = pca_postcode[0];
			}
		}
	}
}

function clearResultsList()
{
	for (i=document.getElementById("lstAddresses").options.length-1; i>=0; i--)
	{
	  document.getElementById("lstAddresses").options[i] = null;
	}
}

function trim(stringToTrim)
{
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function showAddress()
{
	document.getElementById("addressLayer").style.display = 'block';
}
// postcodeanywhere end

function valid_make(v) {
	var valid = true;
	var make = '';
	$.ajax({
		type: 'POST',
		url: '../javascript/ajax_action_retail.php?action=disallowedmakes',
		dataType: 'json',
		data: 'make=' + escape(v),
		async: false,
		success: function(data){
			if (data.valid == false) {
				valid = false;
				make = data.make;
			}
		}
	});
	if (!valid) {
		document.contactform.elements['Make'].focus();
		alert('Sorry, we are unable to offer cover for ' + make + '.');
	}
	return valid;
}

function years_between(date1, date2) {
	//http://www.mcfedries.com/JavaScript/DaysBetween.asp
	//var one_day = 1000 * 60 * 60 * 24;
	var one_year = 1000 * 60 * 60 * 24 * 365;
	var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();
	var difference_ms = Math.abs(date1_ms - date2_ms);
	return parseInt(difference_ms/one_year);//Math.round
}

function valid_reg_date(v, limit) {
	var date_parts = v.split('/');
	var d = parseInt(date_parts[0], 10);
	var m = parseInt(date_parts[1], 10);
	var y = parseInt(date_parts[2], 10);
	var now = new Date();
	var date1 = new Date(now.getFullYear() - limit, now.getMonth(), now.getDate());
	var date2 = new Date(y, m - 1, d);
	var valid = (date1 <= date2);
	//alert(v + '|' + d + '|' + m + '|' + y + '|' + date1 + '|' + date2 + '|' + valid);
	if (!valid) {
		document.contactform.elements['Date_registered_d'].focus();
		alert('The vehicle registration date must be under ' + limit + ' years.');
	}
	return valid;
}

function valid_purchase_date(v, limit, v_focus) {
	var date_parts = v.split('/');
	var d = parseInt(date_parts[0], 10);
	var m = parseInt(date_parts[1], 10);
	var y = parseInt(date_parts[2], 10);
	var now = new Date();
	var date1 = new Date(now.getFullYear(), now.getMonth(), now.getDate() - limit);
	var date2 = new Date(y, m - 1, d);
	var valid = (date1 <= date2);
	//alert(v + '|' + d + '|' + m + '|' + y + '|' + date1 + '|' + date2 + '|' + valid);
	if (!valid) {
		document.contactform.elements[v_focus].focus();
		alert('The vehicle must have been purchased within the last ' + limit + ' days.');
	}
	return valid;
}

function valid_purchase_date_avg(v, start_limit, limit_years, v_focus, private_sale) {
	var valid = true;

	var date_parts = v.split('/');
	var d = parseInt(date_parts[0], 10);
	var m = parseInt(date_parts[1], 10);
	var y = parseInt(date_parts[2], 10);
	var now = new Date();
	var date1 = new Date(now.getFullYear() - limit_years, now.getMonth(), now.getDate());
	var date2 = new Date(y, m - 1, d);
	var this_valid = (date1 <= date2);
	//alert(v + '|' + d + '|' + m + '|' + y + '|' + date1 + '|' + date2 + '|' + this_valid);
	if (!this_valid) {
		var valid = false;
		document.contactform.elements[v_focus].focus();
		alert('The vehicle must have been purchased within the last ' + limit_years + ' years.');
	}
	
	if (private_sale == 0) {
		var now = new Date();
		var date1 = new Date(now.getFullYear(), now.getMonth(), now.getDate() - start_limit);
		var date2 = new Date(y, m - 1, d);
		var this_valid = (date1 >= date2);
		//alert(v + '|' + d + '|' + m + '|' + y + '|' + date1 + '|' + date2 + '|' + this_valid);
		if (!this_valid) {
			var valid = false;
			document.contactform.elements[v_focus].focus();
			alert('The vehicle must have been purchased more than ' + start_limit + ' days ago or bought privately.');
		}
	}

	return valid;
}

function valid_start_date(v) {
	var date_parts = v.split('/');
	var d = parseInt(date_parts[0], 10);
	var m = parseInt(date_parts[1], 10);
	var y = parseInt(date_parts[2], 10);
	var now = new Date();
	var date1 = new Date(now.getFullYear(), now.getMonth(), now.getDate());
	var date2 = new Date(y, m - 1, d);
	var valid = (date1 <= date2);
	//alert(v + '|' + d + '|' + m + '|' + y + '|' + date1 + '|' + date2 + '|' + valid);
	if (!valid) {
		document.contactform.elements['Date_you_would_like_the_insurance_to_start_d'].focus();
		alert('The insurance start date must be the current date or later.');
	}
	return valid;
}

function valid_declaration() {
	if (document.contactform.Customer_Declaration.checked == true) {
		return true;
	} else {
		document.contactform.elements['Customer_Declaration'].focus();
		alert('All declarations must be acknowledged.');
		return false;
	}
}

function valid_email() {
	var ret = true;
	var val = document.contactform.elements['email'].value;
	if (document.contactform.noemail.checked == false) {
		var p = val.indexOf('@');
		if (p < 1 || p == (val.length - 1)) {
			alert('Email must contain an e-mail address.');
			document.contactform.elements['email'].focus();
			var ret = false;
		}
	}
	if (ret && document.contactform.noemail.checked == true) {
		document.contactform.elements['email'].value = '';
		ret = true;
	}
	return ret;
}

function lookupVRM() {
	var reg_no = document.getElementById("Registration_number").value;
	var vrm = '';
	var make = '';
	var model = '';
	var reg_date = '';
	document.getElementById("find_vrm").value = "Searching...";
	document.getElementById("find_vrm").disabled = true;
	$.ajax({
		async: false,
		type: "GET",
		url: "../scripts/vrm_search.php",
		data: "vrm=" + escape(reg_no) + "&nocache=" + (new Date()).valueOf(),
		success: function(result){
			//alert(xml);
			var fields = result.split('|');
			vrm = fields[0] + '';
			make = fields[1] + '';
			model = fields[2] + '';
			reg_date = fields[3] + '';
			if (vrm == '') {
				//alert('Sorry, the registration number could not be found. Please refine your search and try again.');
				//alert('Sorry, the registration number could not be found. Please try again or complete Make, Model and Date Registered.');
				alert('Your vehicle details are not currently logged on the DVLA system, please input manually.');
				//document.getElementById("Date_registered_d").readOnly = false;
				//document.getElementById("Date_registered_m").readOnly = false;
				//document.getElementById("Date_registered_y").readOnly = false;
			} else if (vrm == 'MAXLIMIT') {
				//alert('Sorry, the maximum amount of searches has been reached for your IP address. Please try again later or complete Make, Model and Date Registered.');
				alert('Sorry, the maximum amount of searches has been reached for your IP address, please input manually.');
				//document.getElementById("Date_registered_d").readOnly = false;
				//document.getElementById("Date_registered_m").readOnly = false;
				//document.getElementById("Date_registered_y").readOnly = false;
			} else {
				document.getElementById("Registration_number").value = vrm;
				document.getElementById("Make").value = make;
				document.getElementById("Model").value = model;

				if (reg_date != '') {
					var date_parts = reg_date.split('-');
					var d = date_parts[0] + '';
					var m = date_parts[1] + '';
					var y = date_parts[2] + '';
					/*if (d.length < 2)
						d = '0' + d;
					if (m.length < 2)
						m = '0' + m;*/
					document.getElementById("Date_registered").value = d + '/' + m + '/' + y;
					setSelectedValue(document.getElementById("Date_registered_d"), d);
					setSelectedValue(document.getElementById("Date_registered_m"), m);
					setSelectedValue(document.getElementById("Date_registered_y"), y);
					//document.getElementById("Date_registered_d").readOnly = true;
					//document.getElementById("Date_registered_m").readOnly = true;
					//document.getElementById("Date_registered_y").readOnly = true;
				} else {
					//document.getElementById("Date_registered_d").readOnly = false;
					//document.getElementById("Date_registered_m").readOnly = false;
					//document.getElementById("Date_registered_y").readOnly = false;
				}
			}
		}
	});
	document.getElementById("find_vrm").value = 'Find Make/Model';
	document.getElementById("find_vrm").disabled = false;
}

function productinfo_tabs(prods) {
	//$(document).ready(function(){
		for (var n = 1; n <= 19; n++) {
			if ($("#info_tab" + n).is(":visible")) {
				$('#info_tab' + n).hide();
			}
			for (var i = 1; i <= productinfo_tabs.arguments.length; i++) {
				if (n == productinfo_tabs.arguments[i - 1]) {
					if ($("#info_tab" + n).is(":hidden")) {
						$('#info_tab' + n).show();
					}
				}
			}
		}
	//});
}

function productinfo_toggle(prod) {
	$(document).ready(function(){
		var images = new Array('info_small_bpg_tab.gif', 'info_small_financegap_tab.gif', 'info_small_contractgap_tab.gif', 'info_small_commercialgap_tab.gif', 'info_small_fleetgap_tab.gif', 'info_small_motorhomegap_tab.gif', 'info_small_motorcyclegap_tab.gif', 'info_small_btiplus_tab.gif', 'info_small_vri_tab.gif', 'info_small_avg_tab.gif', 'info_small_caravanswarranty_tab.gif', 'info_small_motorhomeswarranty_tab.gif', 'info_small_scootergap_tab.gif', 'info_small_ccp_tab.gif', 'info_small_btiplus_tab.gif', 'info_small_financegap_tab.gif', 'info_small_btiplus_tab.gif', 'info_small_financegap_tab.gif', 'info_small_btiplus_tab.gif', 'info_small_financegap_tab.gif');//, 'info_small_bti_tab.gif'
		var images_on = new Array('info_small_bpg_tab_on.gif', 'info_small_financegap_tab_on.gif', 'info_small_contractgap_tab_on.gif', 'info_small_commercialgap_tab_on.gif', 'info_small_fleetgap_tab_on.gif', 'info_small_motorhomegap_tab_on.gif', 'info_small_motorcyclegap_tab_on.gif', 'info_small_btiplus_tab_on.gif', 'info_small_vri_tab_on.gif', 'info_small_avg_tab_on.gif', 'info_small_caravanswarranty_tab_on.gif', 'info_small_motorhomeswaranty_tab_on.gif', 'info_small_scootergap_tab_on.gif', 'info_small_ccp_tab_on.gif', 'info_small_btiplus_tab_on.gif', 'info_small_financegap_tab_on.gif', 'info_small_btiplus_tab_on.gif', 'info_small_financegap_tab_on.gif', 'info_small_btiplus_tab_on.gif', 'info_small_financegap_tab_on.gif');//, 'info_small_bti_tab_on.gif'
		if ($("#productinfo_div").is(":visible")) {
			//MM_showHideLayers2('productinfo_div','','hide');
			$("#productinfo_div").hide();
			//$("#productinfo_div").fadeOut("fast");
		}
		for (var n = 0; n < images.length; n++) {
			if (n == prod) {
				if ($("#productinfo_div" + n).is(":hidden")) {
					//MM_showHideLayers2('productinfo_div' + n,'','show');
					$('#productinfo_div' + n).show();
					/*$("#productinfo_div" + n).fadeIn("fast", function(){
						this.style.removeAttribute("filter");
					});*/
					 //MM_swapImage('info_small_tab' + n,'','images/' + images_on[n],0);
					$('[name="info_small_tab' + n +'"]').attr('src', 'images/' + images_on[n]);
					$('[name="info_small_tab' + n +'"]').attr('oversrc', 'images/' + images_on[n]);//simpleswap
					$('[name="info_small_tab' + n +'"]').attr('origsrc', 'images/' + images_on[n]);//simpleswap
				}
			} else {
				if ($("#productinfo_div" + n).is(":visible")) {
					//MM_showHideLayers2('productinfo_div' + n,'','hide');
					$('#productinfo_div' + n).hide();
					//$("#productinfo_div" + n).fadeOut("fast");
					//MM_swapImage('info_small_tab' + n,'','images/' + images[n],0);
					$('[name="info_small_tab' + n + '"]').attr('src', 'images/' + images[n]);
					$('[name="info_small_tab' + n + '"]').attr('oversrc', 'images/' + images_on[n]);//simpleswap
					$('[name="info_small_tab' + n +'"]').attr('origsrc', 'images/' + images[n]);//simpleswap
				}
			}
		}
		/*if (prod == 0) {
			if ($("#productinfo_div0").is(":hidden")) {
				$('#productinfo_div0').show();
			}
		} else {
			if ($("#productinfo_div0").is(":visible")) {
					$('#productinfo_div0').hide();
			}
		}*/
	});
}

function product_info_open() {
	$(document).ready(function(){
		if ($("#quotehelp").is(":hidden")) {
			$("#quotehelp").slideDown("fast");
		}
	});
}
function product_info_toggle() {
	$(document).ready(function(){
		if ($("#quotehelp").is(":hidden")) {
			$("#quotehelp").slideDown("fast");
		} else {
			$("#quotehelp").slideUp("fast");
		}
	});
}

function qualification_init() {
	//qualification_
}

function qualification(q, yn, g, url, def) {
	//url is optional
	if (url == undefined) {
		url = 'quote.php';
	}
	//def is optional
	if (def == undefined) {
		def = '';
	}
	if (q == 1) {
		$("#question2").hide("fast");
		$("#unavailable").hide("fast");
		$("#question3_1").hide();
		$("#question3_2").hide();
		$("#question3_3").hide();
		$("#question3_4").hide();
		if (g == 'cars') {
			if (yn == 'yes') {
				/*$("a#question3_1").attr("href", url + "?action=goto&group=" + escape(g) + "&options=1");
				$("a#question3_2").attr("href", url + "?action=goto&group=" + escape(g) + "&options=2");
				$("a#question3_3").attr("href", url + "?action=goto&group=" + escape(g) + "&options=3");
				$("a#question3_4").attr("href", url + "?action=goto&group=" + escape(g) + "&options=4");*/
				$("#question3_1 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=1" + (def ? '&def=' + escape(def) : ''));
				$("#question3_2 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=2");
				$("#question3_3 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=3");
				$("#question3_4 a").attr("href", url + "?action=goto&group=cars_avg");
				$("#question3_1").show();
				$("#question3_2").show();
				$("#question3_3").show();
				$("#question3_4").show();
				$("#question2").show("fast");
				simpleswap_on($('[name="qualificationyes"]'));
				simpleswap_reset($('[name="qualificationno"]'));
			} else {
				$("#unavailable").show("fast");
				simpleswap_on($('[name="qualificationno"]'));
				simpleswap_reset($('[name="qualificationyes"]'));
				//document.location.href = url + '?action=goto&group=cars_avg';
			}
		}
		if (g == 'vans') {
			if (yn == 'yes') {
				/*$("a#question3_1").attr("href", url + "?action=goto&group=" + escape(g) + "&options=1");
				$("a#question3_2").attr("href", url + "?action=goto&group=" + escape(g) + "&options=2");
				$("a#question3_3").attr("href", url + "?action=goto&group=" + escape(g) + "&options=3");
				$("a#question3_4").attr("href", url + "?action=goto&group=" + escape(g) + "&options=4");*/
				$("#question3_1 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=1" + (def ? '&def=' + escape(def) : ''));
				$("#question3_2 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=2");
				$("#question3_3 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=3");
				//$("#question3_4 a").attr("href", url + "?action=goto&group=cars_avg");
				$("#question3_1").show();
				$("#question3_2").show();
				$("#question3_3").show();
				//$("#question3_4").show();
				$("#question2").show("fast");
				simpleswap_on($('[name="qualificationyes"]'));
				simpleswap_reset($('[name="qualificationno"]'));
			} else {
				$("#unavailable").show("fast");
				simpleswap_on($('[name="qualificationno"]'));
				simpleswap_reset($('[name="qualificationyes"]'));
				//document.location.href = url + '?action=goto&group=vans_avg';
			}
		}
		if (g == 'fleet') {
			if (yn == 'yes') {
				/*$("a#question3_1").attr("href", url + "?action=goto&group=" + escape(g) + "&options=1");
				$("a#question3_2").attr("href", url + "?action=goto&group=" + escape(g) + "&options=2");
				$("a#question3_3").attr("href", url + "?action=goto&group=" + escape(g) + "&options=3");
				$("a#question3_4").attr("href", url + "?action=goto&group=" + escape(g) + "&options=4");*/
				//$("#question3_1 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=1");
				//$("#question3_2 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=2");
				//$("#question3_3 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=3");
				////$("a#question3_4 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=4");
				//$("#question3_1").show();
				//$("#question3_2").show();
				//$("#question3_3").show();
				////$("#question3_4").show();
				//$("#question2").show("fast");
				document.location.href = url + "?action=goto&group=" + escape(g);
			} else {
				$("#unavailable").show("fast");
				simpleswap_on($('[name="qualificationno"]'));
				simpleswap_reset($('[name="qualificationyes"]'));
			}
		}
		/*if (g == 'trucks') {
			if (yn == 'yes') {
				/* //$("a#question3_1").attr("href", url + "?action=goto&group=" + escape(g) + "&options=1");
				$("a#question3_2").attr("href", url + "?action=goto&group=" + escape(g) + "&options=2");
				$("a#question3_3").attr("href", url + "?action=goto&group=" + escape(g) + "&options=3");* /
				//$("#question3_1 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=1");
				$("#question3_2 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=2");
				$("#question3_3 a").attr("href", url + "?action=goto&group=" + escape(g) + "&options=3");
				//$("#question3_1").show();
				$("#question3_2").show();
				$("#question3_3").show();
				$("#question2").show("fast");
				simpleswap_on($('[name="qualificationyes"]'));
				simpleswap_reset($('[name="qualificationno"]'));
			} else {
				simpleswap_on($('[name="qualificationno"]'));
				simpleswap_reset($('[name="qualificationyes"]'));
				$("#unavailable").show("fast");
			}
		}*/
		if (g == 'motorcycles' || g == 'scooters' || g == 'motorhomes' || g == 'drivingschools' || g == 'plant' || g == 'tractor' || g == 'trucks') {
			if (yn == 'yes') {
				//$("a#question3_1").attr("href", url + "?action=goto&group=" + escape(g));
				//$("a#question3_2").attr("href", url + "?action=goto&group=" + escape(g));
				////$("a#question3_3").attr("href", url + "?action=goto&group=" + escape(g));
				//$("#question3_1").show();
				//$("#question3_2").show();
				////$("#question3_3").show();
				//$("#question2").show("fast");
				document.location.href = url + "?action=goto&group=" + escape(g);
			} else {
				simpleswap_on($('[name="qualificationno"]'));
				simpleswap_reset($('[name="qualificationyes"]'));
				$("#unavailable").show("fast");
			}
		}
	}
}

function formactivity(site) {
	//$(document).ready(function(){
		/*$("input").blur(function(){
			$.ajax({
				type: "POST",
				url: "/scripts/formactivity1.php",
				data: {
					"site" : site,
					"ref" : $("form[name='contactform']").find("input[name='ref']").val(),
					"name" : $(this).attr('name'),
					"id" : $(this).attr('id'),
					"value" : $(this).val()
				}
			});
		});
		$("select").blur(function(){
			$.ajax({
				type: "POST",
				url: "/scripts/formactivity1.php",
				data: {
					"site" : site,
					"ref" : $("form[name='contactform']").find("input[name='ref']").val(),
					"name" : $(this).attr('name'),
					"id" : $(this).attr('id'),
					"value" : $(this).val()
				}
			});
		});
		$("textarea").blur(function(){
			$.ajax({
				type: "POST",
				url: "/scripts/formactivity1.php",
				data: {
					"site" : site,
					"ref" : $("form[name='contactform']").find("input[name='ref']").val(),
					"name" : $(this).attr('name'),
					"id" : $(this).attr('id'),
					"value" : $(this).val()
				}
			});
		});*/

		$("input").blur(function(){
			$.ajax({
				type: "POST",
				url: "/scripts/formactivity.php",
				data: $("#contactform").serialize() + '&site=' + site
			});
		});
		$("select").blur(function(){
			$.ajax({
				type: "POST",
				url: "/scripts/formactivity.php",
				data: $("#contactform").serialize() + '&site=' + site
			});
		});
		$("textarea").blur(function(){
			$.ajax({
				type: "POST",
				url: "/scripts/formactivity.php",
				data: $("#contactform").serialize() + '&site=' + site
			});
		});
	//});
}

function showHide(id, v) {
	$(document).ready(function(){
		if (v == 'show') {
			if ($("#" + id).is(":hidden")) {
				$("#" + id).slideDown("fast");
			}
		}
		if (v == 'hide') {
			if ($("#" + id).is(":visible")) {
				$("#" + id).slideUp("fast");
			}
		}
	});
}

function starting_benefit(f) {//test
	var vehicle_value = parseFloat($(f.vehicle_value).val());
	var benefit = $(f.benefit).val();
	var term = $(f.term).val();
	if (vehicle_value == 123) {
		alert(vehicle_value+' '+benefit+' '+term);
	}
}

function getvaluation(form_number) {
	$("#dialog").dialog('destroy');
	//$("#dialog").dialog('option', 'autoOpen', false);
	$("#dialog").dialog({width: 600, height: 530, modal: true});
	$("#dialog_src").load("getvaluation.php", {form_number: form_number}, function(){
		//
	});
}

function makepassword(f) {
	var validchars = 'abcdefghjkmnpqrstuvwxyz23456789';
	var password = '';
	for (var n = 1; n <= 8; n++) {
		password += validchars.substr(Math.floor(Math.random() * (validchars.length + 1)), 1);
	}
	f.value = password;
}

function SimpleSwap(el,which){
  el.src=el.getAttribute(which || "origsrc");
}

function SimpleSwapSetup(){
  var x = document.getElementsByTagName("img");
  for (var i=0;i<x.length;i++){
    var oversrc = x[i].getAttribute("oversrc");
    if (!oversrc) continue;
      
    // preload image
    // comment the next two lines to disable image pre-loading
    x[i].oversrc_img = new Image();
    x[i].oversrc_img.src=oversrc;
    // set event handlers
    x[i].onmouseover = new Function("SimpleSwap(this,'oversrc');");
    x[i].onmouseout = new Function("SimpleSwap(this);");
    // save original src
    x[i].setAttribute("origsrc",x[i].src);

    x[i].setAttribute("src_original",x[i].src);////
    x[i].setAttribute("oversrc_original",oversrc);////
  }

  var x = document.getElementsByTagName("input");
  for (var i=0;i<x.length;i++){
    var oversrc = x[i].getAttribute("oversrc");
    if (!oversrc) continue;
      
    // preload image
    // comment the next two lines to disable image pre-loading
    x[i].oversrc_img = new Image();
    x[i].oversrc_img.src=oversrc;
    // set event handlers
    x[i].onmouseover = new Function("SimpleSwap(this,'oversrc');");
    x[i].onmouseout = new Function("SimpleSwap(this);");
    // save original src
    x[i].setAttribute("origsrc",x[i].src);

    x[i].setAttribute("src_original",x[i].src);////
    x[i].setAttribute("oversrc_original",oversrc);////
  }
}

var PreSimpleSwapOnload =(window.onload)? window.onload : function(){};
window.onload = function(){PreSimpleSwapOnload(); SimpleSwapSetup();}

function simpleswap_on(id) {////
	if ($(id).attr('oversrc_original')) {
		$(id).attr('src', $(id).attr('oversrc_original'));
		$(id).attr('oversrc', $(id).attr('oversrc_original'));
		$(id).attr('origsrc', $(id).attr('oversrc_original'));
	}
}

function simpleswap_reset(id) {////
	if ($(id).attr('src_original') && $(id).attr('oversrc_original')) {
		$(id).attr('src', $(id).attr('src_original'));
		$(id).attr('oversrc', $(id).attr('oversrc_original'));
		$(id).attr('origsrc', $(id).attr('src_original'));
	}
}

/* at_tooltip */
(function(jQuery){
	var openTimeout=300;var closeTimeout=150;var isIE6=jQuery.browser.msie&&(parseInt(jQuery.browser.version,10)<7);function at_tooltip(target_items,name){
		jQuery(target_items).each(function(i){
			var that=jQuery(this);var namei=name+i;jQuery("body").append("<div class='"+name+"' id='"+namei+"'><p>"+that.attr('title')+"</p><p class='tooltipBottom'></p></div>");var auto_tooltip=jQuery("#"+namei);var openID,closeID,open=false;that.removeAttr("title").mouseenter(function(){
				if(closeID){
					window.clearTimeout(closeID);closeID=null;
				}
				if(!open&&!openID){
					openID=window.setTimeout(function(){
						open=true;openID=null;if(isIE6){
							auto_tooltip.show();
						}else{
							auto_tooltip.fadeIn(300);
						}
					}
					,openTimeout);
				}
			}).mouseleave(function(){
				if(openID){
					window.clearTimeout(openID);openID=null;
				}
				if(open&&!closeID){
					closeID=window.setTimeout(function(){
						open=false;if(isIE6){
							auto_tooltip.hide();
						}else{
							auto_tooltip.fadeOut(200);
						}
						closeID=null;
					}
					,closeTimeout);
				}
			}).mousemove(function(kmouse){
				var pos=that.offset();var height=jQuery("#"+name+i+"").height();auto_tooltip.css({"left":(pos.left+0)+"px","top":(pos.top-height)+"px"});
			}).click(function(e){
				e.preventDefault();auto_tooltip.fadeIn(300);
			});auto_tooltip.css({display:"none"});
		});
	}
	jQuery(document).ready(function(){
		at_tooltip("a._tooltip, .at2tooltip","tooltip");
	});
})(jQuery);
/* at_tooltip end */

/*document.write('<script type="text/javascript" src="includes/jscalendar/calendar.js"></script>' + '<script type="text/javascript" src="includes/jscalendar/lang/calendar-en.js"></script>' + '<script type="text/javascript" src="includes/jscalendar/calendar-setup.js"></script>');*/
