//**********************************************************************
//        COPYRIGHT ENDSLEIGH INSURANCE SERVICES LIMITED 2006
//**********************************************************************
//   PROJECT         :   insurance.net
//   LANGUAGE        :   Javascript
//   FILENAME        :   Quote.js
//   ENVIRONMENT     :   Microsoft Visual Studio
//**********************************************************************
//   FILE FUNCTION   :   
//   EXECUTABLE TYPE :   EXE/DLL
//   SPECIFICATION   :   None
//
//   RELATED DOCUMENTATION : None
//
//**********************************************************************
//   ABSTRACT        :   Supporting javascript for Quote.aspx.
//                       
//   AUTHOR          :   A. Weekes        CREATION DATE : 09-May-2007
//
//**********************************************************************
//   BUILD INFORMATION   :   Endsleigh Build System
//   EXECUTABLE NAME     :   
//   MAIN ENTRY POINTS   :   
//
//   EVENTS              :   
//
//**********************************************************************
//   PVCS SECTION:
//   ~~~~~~~~~~~~~
//   PVCS FILENAME: $Logfile:   $
//   PVCS REVISION: $Revision:  $
//
//   $Log$
//
//**********************************************************************

//******************************************************************************************
// Constants
//******************************************************************************************
var MAX_NUMBER_OF_DRIVERS = 5;
var OPEN_UNIVERSITY_OCCUPATION_CODE = 532;
var OPEN_UNIVERSITY_ESTABLISHMENT_CODE = 886;
var STUDENT_OCCUPATION_GROUP = 'S';


//******************************************************************************************
// Enums
//******************************************************************************************
var SearchBoxType = { Occupation:0, Education:1 };

//******************************************************************************************
// Page Load
//******************************************************************************************

// Function called when the page loads
function onLoad()
{	
	// Attach key stroke events to form controls
	setControlAttributes();
	
	//Windscreen
	coverSelected_Onload();
	
	
	//where study
	whereStudySelected_Onload();
	
	// Perform postcode search if required
	if (document.getElementById('txtHouseNumberOrName').value != '' && document.getElementById('txtPostcode').value != '')
		validatePostcode('txtHouseNumberOrName', 'txtPostcode', 'addressRow', 'showAddress', 'editAddress', 'txtAddress1', 'txtAddress2', 'lblAddress1', 'lblAddress2', 'lblAddress3', 'imgConfirmAddressProgress', 'errPostcode', 'lblErrorPostcode', true, false);

	// Make sure occ search boxes are correctly populated / displayed
    setTimeout("checkSearchBoxSlide(document.getElementById('txtFullTimeOccupation'), 'slidePanelFullTimeOccupation', 'slideContentFullTimeOccupation');", 0);
	filterList(document.getElementById('txtFullTimeOccupation'), 'cboFullTimeOccupation', 'lstFullTimeOccupation', false, 400, true, false);
	
	// If we have a part-time occ filter on it
	if (document.getElementById('optPartTimeOccupation_0').checked)
		filterList(document.getElementById('txtPartTimeOccupation'), 'cboPartTimeOccupation', 'lstPartTimeOccupation', false, 400, true, false);
	else
		filterList(document.getElementById('txtPartTimeOccupation'), 'cboPartTimeOccupation', 'lstPartTimeOccupation', true, 0, false, false);

	// Hide / display part time occupation section
    togglePartTimeOccupation('optPartTimeOccupation_0', 'slidePanelPartTimeOccupation', 'slideContentPartTimeOccupation', 'txtPartTimeOccupation', 'lstPartTimeOccupation');

	// Populate additional driver pop up 
	filterList(document.getElementById('popUpAdditionalDriver_txtAdditionalDriverFullTimeOccupation'), 'cboFullTimeOccupation', 'popUpAdditionalDriver_lstAdditionalDriverFullTimeOccupation', true, 0, false, false);
	filterList(document.getElementById('popUpAdditionalDriver_txtAdditionalDriverPartTimeOccupation'), 'cboPartTimeOccupation', 'popUpAdditionalDriver_lstAdditionalDriverPartTimeOccupation', true, 0, false, false);
	
	// See if we have a vehicle stored in session
	getVehicleDescription('rowVehicle', 'lblConfirmVehicle', 'btnEditVehicleDetails', 'txtYearOfMake');

	// Check business use
	toggleBusinessUse('optBusinessUse_0', 'lblTotalAnnualMileagePlusBusiness', 'slidePanelBusinessMileage', 'slideContentBusinessMileage', 'txtBusinessAnnualMileage');
	
	// Check for additional drivers
	getAdditionalDrivers();

	// Hide / display part time occupation section
	toggleNCDRows(document.getElementById('cboNCD'), 'slidePanelNoClaimsBonus', 'slideContentNoClaimsBonus');	
	
	// Focus the cover start date field if we have no errors & its blank
	if (document.getElementById('pageErrorMessage').style.display != 'block')
	{
		if (document.getElementById('dteCoverStartDate_Day').value == '')
			setTimeout("if (!scrolledToElement) document.getElementById('dteCoverStartDate_Day').focus();", 0);
	}
	else
		setTimeout("scrollToValidation();", 0);
	
	// Check if a scroll is required
	setTimeout("checkScrollRequired();", 0);
}

//******************************************************************************************
// Page Validation
//******************************************************************************************

//Validates the data on the main page when the page is submitted.
function validatePage()
{
	var pageIsValid = true;
	
	//moved from the btnContinue onclick as it stopped the client side validation working
	evakd('98', 'ContinueButton');
	
	try
	{
		//First we need to pop up the validate business use pop up.
		pageIsValid = validateBusinessUse('optBusinessUse_0', 'txtBusinessAnnualMileage', 'popUpMissingBusinessMileage', 'popUpMissingBusinessMileage_txtMissingBusinessMileage');
	
		if (pageIsValid)
		{
			// Clear validation summary list
			document.getElementById('validationSummaryList').innerHTML = '';
			
			//Fields
			var coverStartDateDay = document.getElementById('dteCoverStartDate_Day');
			var coverStartDateMonth = document.getElementById('dteCoverStartDate_Month');
			var coverStartDateYear = document.getElementById('dteCoverStartDate_Year');
			var windscreen = document.getElementById('rdoWindscreen');
			var windscreen_Yes = document.getElementById('rdoWindscreen_0');
			var windscreen_No = document.getElementById('rdoWindscreen_1');
			var coverRequired = document.getElementById('cboCoverRequired');
			var title = document.getElementById('cboTitle');
			var firstName = document.getElementById('txtFirstName');
			var surname = document.getElementById('txtSurname');
			var dateOfBirthDay = document.getElementById('dteDateOfBirth_Day');
			var dateOfBirthMonth = document.getElementById('dteDateOfBirth_Month');
			var dateOfBirthYear = document.getElementById('dteDateOfBirth_Year');
			var gender = document.getElementById('cboGender');
			var maritalStatus = document.getElementById('cboMaritalStatus');
			var union = document.getElementById('cboUnion');
			var fullTimeOccupation = document.getElementById('txtFullTimeOccupation');
			var partTimeOccupationOption = document.getElementById('optPartTimeOccupation');
			var partTimeOccupation_Yes = document.getElementById('optPartTimeOccupation_0');
			var partTimeOccupation_No = document.getElementById('optPartTimeOccupation_1');
			var partTimeOccupation = document.getElementById('txtPartTimeOccupation');
			var whereStudying = document.getElementById('txtWhereStudying');
			var houseNumberOrName = document.getElementById('txtHouseNumberOrName');
			var postcode = document.getElementById('txtPostcode');
			var riskPostcode = document.getElementById('txtPostcodeWhereVehicleKept');
			//var telephoneNumber = document.getElementById('txtTelephoneNumber');
			var daytimePhoneNumber = document.getElementById('txtDaytimePhoneNumber');
			var eveningPhoneNumber = document.getElementById('txtEveningPhoneNumber');
			var emailAddress = document.getElementById('txtEmailAddress');
			var ukResidencyYears = document.getElementById('txtUKResidencyYears');
			var ukResidencyMonths = document.getElementById('txtUKResidencyMonths');
			var licenceType = document.getElementById('cboLicenceType');
			var licenceHeldDurationYears = document.getElementById('txtLicenceHeldDurationYears');
			var licenceHeldDurationMonths = document.getElementById('txtLicenceHeldDurationMonths');
			var ncdEntitlement = document.getElementById('cboNCD');
			var ncdHowEarned = document.getElementById('cboNCDHowEarned');
			var ncdUsedAlready = document.getElementById('optNCDUsedAlready');
			var ncdUsedAlready_Yes = document.getElementById('optNCDUsedAlready_0');
			var ncdUsedAlready_No = document.getElementById('optNCDUsedAlready_1');
			var ncdProtected = document.getElementById('optNCDProtected');
			var ncdProtected_Yes = document.getElementById('optNCDProtected_0');
			var ncdProtected_No = document.getElementById('optNCDProtected_1');
			var carsAvailableForUse = document.getElementById('cboCarsAvailableForUse');
			var homeowner = document.getElementById('optHomeowner');
			var homeowner_Yes = document.getElementById('optHomeowner_0');
			var homeowner_No = document.getElementById('optHomeowner_1');
			var regNo = document.getElementById('txtRegNo');
			var yearOfMake = document.getElementById('txtYearOfMake');
			var numberOfSeats = document.getElementById('txtNumberOfSeats');
			var estimatedValue = document.getElementById('txtEstimatedValue');
			var rightHandDrive = document.getElementById('optRightHandDrive');
			var rightHandDrive_Yes = document.getElementById('optRightHandDrive_0');
			var rightHandDrive_No = document.getElementById('optRightHandDrive_1');
			var parkingLocation = document.getElementById('cboParkingLocation');
			var ukResidencyYears = document.getElementById('txtUKResidencyYears');
			var purchaseDateMonths = document.getElementById('txtPurchaseDateMonths');
			var purchaseDateYears = document.getElementById('txtPurchaseDateYears');
			var vehicleRegisteredTo = document.getElementById('cboVehicleRegisteredTo');
			var vehicleModifications = document.getElementById('cboVehicleModifications');
			var vehicleSecurityDevice = document.getElementById('cboVehicleSecurityDevice');
			var commute = document.getElementById('optCommute');
			var commute_Yes = document.getElementById('optCommute_0');
			var commute_No = document.getElementById('optCommute_1');
			var businessUse = document.getElementById('optBusinessUse');
			var businessUse_Yes = document.getElementById('optBusinessUse_0');
			var businessUse_No = document.getElementById('optBusinessUse_1');
			var totalAnnualMileage = document.getElementById('txtTotalAnnualMileage');
			var businessAnnualMileage = document.getElementById('txtBusinessAnnualMileage');
			var anyOtherDrivers = document.getElementById('optAnyOtherDrivers');
			var anyOtherDrivers_Yes = document.getElementById('optAnyOtherDrivers_0');
			var anyOtherDrivers_No = document.getElementById('optAnyOtherDrivers_1');
			var voluntaryExcess = document.getElementById('cboVoluntaryExcess');
			var normalPaymentMethod = document.getElementById('cboNormalPaymentMethod');
			var incidents = document.getElementById('optIncidents');
			var incidents_Yes = document.getElementById('optIncidents_0');
			var incidents_No = document.getElementById('optIncidents_1');
			var convictions = document.getElementById('optConvictions');
			var convictions_Yes = document.getElementById('optConvictions_0');
			var convictions_No = document.getElementById('optConvictions_1');
			
			//Page error message.
			var pageErrorMessage = document.getElementById('pageErrorMessage');
			
			//Array of fields in error.
			var controlsInErrorState = new Array();
			
			//Reset all the alerts first.
			var allFields = ['dteCoverStartDate_Day', 'dteCoverStartDate_Month', 'dteCoverStartDate_Year', 'cboCoverRequired', 'cboTitle', 'txtFirstName', 'txtSurname', 'dteDateOfBirth_Day', 'dteDateOfBirth_Month', 'dteDateOfBirth_Year', 'cboGender', 'cboMaritalStatus', 'cboUnion', 'txtFullTimeOccupation', 'optPartTimeOccupation', 'txtPartTimeOccupation', 'txtWhereStudying', 'txtHouseNumberOrName', 'txtPostcode', 'txtPostcodeWhereVehicleKept', 'txtDaytimePhoneNumber', 'txtEveningPhoneNumber', 'txtEmailAddress', 'txtUKResidencyYears', 'txtUKResidencyMonths', 'cboLicenceType', 'txtLicenceHeldDurationYears', 'txtLicenceHeldDurationMonths', 'cboNCD', 'cboNCDHowEarned', 'optNCDUsedAlready', 'optNCDProtected', 'cboCarsAvailableForUse', 'optHomeowner', 'txtRegNo', 'txtYearOfMake', 'txtNumberOfSeats', 'txtEstimatedValue', 'optRightHandDrive', 'cboParkingLocation', 'txtUKResidencyYears', 'txtPurchaseDateMonths', 'txtPurchaseDateYears', 'cboVehicleRegisteredTo', 'cboVehicleModifications', 'cboVehicleSecurityDevice', 'optCommute', 'optBusinessUse', 'txtTotalAnnualMileage', 'txtBusinessAnnualMileage', 'optAnyOtherDrivers_0', 'optAnyOtherDrivers_1', 'cboVoluntaryExcess', 'cboNormalPaymentMethod', 'optIncidents', 'optConvictions'];
			//var allFields = ['dteCoverStartDate_Day', 'dteCoverStartDate_Month', 'dteCoverStartDate_Year', 'cboCoverRequired', 'cboTitle', 'txtFirstName', 'txtSurname', 'dteDateOfBirth_Day', 'dteDateOfBirth_Month', 'dteDateOfBirth_Year', 'cboGender', 'cboMaritalStatus', 'cboUnion', 'txtFullTimeOccupation', 'optPartTimeOccupation', 'txtPartTimeOccupation', 'txtHouseNumberOrName', 'txtPostcode', 'txtPostcodeWhereVehicleKept', 'txtTelephoneNumber', 'txtEmailAddress', 'txtUKResidencyYears', 'txtUKResidencyMonths', 'cboLicenceType', 'txtLicenceHeldDurationYears', 'txtLicenceHeldDurationMonths', 'cboNCD', 'cboNCDHowEarned', 'optNCDUsedAlready', 'optNCDProtected', 'cboCarsAvailableForUse', 'optHomeowner', 'txtRegNo', 'txtYearOfMake', 'txtNumberOfSeats', 'txtEstimatedValue', 'optRightHandDrive', 'cboParkingLocation', 'txtUKResidencyYears', 'txtPurchaseDateMonths', 'txtPurchaseDateYears', 'cboVehicleRegisteredTo', 'cboVehicleModifications', 'cboVehicleSecurityDevice', 'optCommute', 'optBusinessUse', 'txtTotalAnnualMileage', 'txtBusinessAnnualMileage', 'optAnyOtherDrivers_0', 'optAnyOtherDrivers_1', 'cboVoluntaryExcess', 'cboNormalPaymentMethod', 'optIncidents', 'optConvictions'];
			resetAlerts(allFields);
			
			//Validate that all the fields have been filled in - business rules are validated server side.
			if (coverStartDateDay.value == '')
				controlsInErrorState[controlsInErrorState.length] = coverStartDateDay.id + "_error";
			
			if (coverStartDateMonth.value == '')
				controlsInErrorState[controlsInErrorState.length] = coverStartDateMonth.id + "_error";
			
			if (coverStartDateYear.value == '')
				controlsInErrorState[controlsInErrorState.length] = coverStartDateYear.id + "_error";
			
			if (coverStartDateDay.value == '' || coverStartDateMonth.value == '' || coverStartDateYear.value == '')
				addValidationItem('validationSummaryList', '<strong>Cover start date</strong> is required.');
			
			if (title.selectedIndex == 0)
			{
				addValidationItem('validationSummaryList', '<strong>Title</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = title.id + "_error";
			}
			
			if (firstName.value == '')
			{
				addValidationItem('validationSummaryList', '<strong>First name</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = firstName.id + "_error";
			}
			
			if (surname.value == '')
			{
				addValidationItem('validationSummaryList', '<strong>Surname</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = surname.id + "_error";
			}
				
			if (dateOfBirthDay.value == '')
				controlsInErrorState[controlsInErrorState.length] = dateOfBirthDay.id + "_error";
			
			if (dateOfBirthMonth.value == '')
				controlsInErrorState[controlsInErrorState.length] = dateOfBirthMonth.id + "_error";
				
			if (dateOfBirthYear.value == '')
				controlsInErrorState[controlsInErrorState.length] = dateOfBirthYear.id + "_error";
			
			if (dateOfBirthDay.value == '' || dateOfBirthDay.value == '' || dateOfBirthDay.value == '')
				addValidationItem('validationSummaryList', '<strong>Date of birth</strong> is required.');
			
			if (gender.selectedIndex == 0)
			{
				addValidationItem('validationSummaryList', '<strong>Gender</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = gender.id + "_error";
			}
			
			if (maritalStatus.selectedIndex == 0)
			{
				addValidationItem('validationSummaryList', '<strong>Marital Status</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = maritalStatus.id + "_error";
			}
			
			if (document.getElementById('rowUnion').style.display != 'none')
			{
				if (union.selectedIndex < 0)
				{
					addValidationItem('validationSummaryList', '<strong>Union</strong> is required.');
					controlsInErrorState[controlsInErrorState.length] = union.id + "_error";
				}
			}
			
			if (fullTimeOccupation.value == '')
			{
				addValidationItem('validationSummaryList', '<strong>Main occupation</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = fullTimeOccupation.id + "_error";
			}
			
			if (partTimeOccupation_No.checked == false && partTimeOccupation_Yes.checked == false)
			{
				addValidationItem('validationSummaryList', 'Please confirm whether you have a <strong>part-time occupation</strong>.');
				controlsInErrorState[controlsInErrorState.length] = partTimeOccupationOption.id + "_error";
			}
			
			if (partTimeOccupation_Yes.checked == true)
			{
				if (partTimeOccupation.value == '')
				{
					addValidationItem('validationSummaryList', '<strong>Part-time occupation</strong> is required.');
					controlsInErrorState[controlsInErrorState.length] = partTimeOccupation.id + "_error";
				}
			}
			
			if (document.getElementById('slidePanelWhereStudyingText').style.display == 'block') {
			    if (whereStudying.value =='') {
			        addValidationItem('validationSummaryList', '<strong>Where are you studying</strong> is required please enter your place of study and select from the list.');
			        controlsInErrorState[controlsInErrorState.length] = whereStudying.id + "_error";
			    }
			}

			if (houseNumberOrName.value == '')
			{
				addValidationItem('validationSummaryList', '<strong>House name or number</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = houseNumberOrName.id + "_error";
			}
			
			if (postcode.value == '')
			{
				addValidationItem('validationSummaryList', '<strong>Postcode</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = postcode.id + "_error";
			}
			
			if (riskPostcode.value.replace(/\s/, '') == '')
			{
				addValidationItem('validationSummaryList', '<strong>Postcode where the vehicle is kept overnight</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = riskPostcode.id + "_error";
			}
			
			//if (telephoneNumber.value == '')
			//	controlsInErrorState[controlsInErrorState.length] = telephoneNumber.id + "_error";
			
			if (daytimePhoneNumber.value == '')
			{
				addValidationItem('validationSummaryList', '<strong>Daytime/Mobile telephone number</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = daytimePhoneNumber.id + "_error";
			}
				
			if (eveningPhoneNumber.value == '')
			{
				addValidationItem('validationSummaryList', '<strong>Evening/Mobile telephone number</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = eveningPhoneNumber.id + "_error";
			}
			
			if (emailAddress.value == '')
			{
				addValidationItem('validationSummaryList', '<strong>E-mail address</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = emailAddress.id + "_error";
			}
			
			if (ukResidencyYears.value == '')
				controlsInErrorState[controlsInErrorState.length] = ukResidencyYears.id + "_error";
			else
			{
				if (isNaN(parseInt(ukResidencyYears.value)))
				{
					addValidationItem('validationSummaryList', '<strong>UK residency</strong> appears to be incorrect.');
					controlsInErrorState[controlsInErrorState.length] = ukResidencyYears.id + "_error";
				}
			}
			
			if (ukResidencyMonths.value == '')
				controlsInErrorState[controlsInErrorState.length] = ukResidencyMonths.id + "_error";
			else
			{
				if (isNaN(parseInt(ukResidencyMonths.value)))
				{
					addValidationItem('validationSummaryList', '<strong>UK residency</strong> appears to be incorrect.');
					controlsInErrorState[controlsInErrorState.length] = ukResidencyMonths.id + "_error";
				}
			}
			
			if (ukResidencyYears.value == '' || ukResidencyYears.value == '')
				addValidationItem('validationSummaryList', '<strong>UK residency</strong> is required.');
			
			if (licenceType.selectedIndex == 0)
			{
				addValidationItem('validationSummaryList', '<strong>Licence type</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = licenceType.id + "_error";	
			}
			
			if (licenceHeldDurationYears.value == '')
			{
				addValidationItem('validationSummaryList', '<strong>Length of time licence held</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = licenceHeldDurationYears.id + "_error";
			}
			else
			{
				if (isNaN(parseInt(licenceHeldDurationYears.value)))
				{
					addValidationItem('validationSummaryList', '<strong>Length of time licence held</strong> appears to be incorrect.');
					controlsInErrorState[controlsInErrorState.length] = licenceHeldDurationYears.id + "_error";
				}
			}
			
			if (licenceHeldDurationMonths.style.display != '' && licenceHeldDurationMonths.style.display != 'none')
			{
				if (licenceHeldDurationMonths.value == '')
				{
					addValidationItem('validationSummaryList', '<strong>Length of time licence held</strong> is required.');
					controlsInErrorState[controlsInErrorState.length] = licenceHeldDurationMonths.id + "_error";
				}
				else
				{
					if (isNaN(parseInt(licenceHeldDurationMonths.value)))
					{
						addValidationItem('validationSummaryList', '<strong>Length of time licence held</strong> appears to be incorrect.');
						controlsInErrorState[controlsInErrorState.length] = licenceHeldDurationMonths.id + "_error";
					}
				}
			}
			
			if (ncdEntitlement.selectedIndex > 0)
			{
				if (ncdUsedAlready_No.checked == false && ncdUsedAlready_Yes.checked == false)
				{
					addValidationItem('validationSummaryList', 'Please confirm whether your <strong>no claims bonus is being used on another policy</strong>.');
					controlsInErrorState[controlsInErrorState.length] = ncdUsedAlready.id + "_error";
				}
					
				if (ncdProtected_No.checked == false && ncdProtected_Yes.checked == false)
				{
					addValidationItem('validationSummaryList', 'Please confirm whether you wish to <strong>protect your no claims bonus</strong>.');
					controlsInErrorState[controlsInErrorState.length] = ncdProtected.id + "_error";
				}
			}
			
			if (carsAvailableForUse.selectedIndex == 0)
			{
				addValidationItem('validationSummaryList', '<strong>How many cars are there in your household</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = carsAvailableForUse.id + "_error";	
			}
			
			if (homeowner_No.checked == false && homeowner_Yes.checked == false)
			{
				addValidationItem('validationSummaryList', 'Please confirm whether <strong>you are a homeowner</strong>.');
				controlsInErrorState[controlsInErrorState.length] = homeowner.id + "_error";
			}
			
			//windscreen
			if (windscreen_No.checked == false && windscreen_Yes.checked == false)
			{
				addValidationItem('validationSummaryList', 'Please select whether or not <strong>you wish to add Windscreen Cover <strong>.');
				controlsInErrorState[controlsInErrorState.length] = windscreen.id + "_error";
			}
			
			if (yearOfMake.value == '')
			{
				addValidationItem('validationSummaryList', '<strong>Year of make</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = yearOfMake.id + "_error";	
			}
			
			if (estimatedValue.value == '')
			{
				addValidationItem('validationSummaryList', '<strong>Estimated value</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = estimatedValue.id + "_error";	
			}
			
			if (rightHandDrive_No.checked == false && rightHandDrive_Yes.checked == false)
			{
				addValidationItem('validationSummaryList', 'Please confirm whether <strong>the vehicle is right hand drive</strong>.');
				controlsInErrorState[controlsInErrorState.length] = rightHandDrive.id + "_error";
			}
			
			if (parkingLocation.selectedIndex == 0)
			{
				addValidationItem('validationSummaryList', 'Please confirm <strong>where the vehicle is kept overnight</strong>.');
				controlsInErrorState[controlsInErrorState.length] = parkingLocation.id + "_error";	
			}
			
			if (purchaseDateMonths.value == '')
				controlsInErrorState[controlsInErrorState.length] = purchaseDateMonths.id + "_error";	
				
			if (purchaseDateYears.value == '')
				controlsInErrorState[controlsInErrorState.length] = purchaseDateYears.id + "_error";	
			
			if (purchaseDateMonths.value == '' || purchaseDateYears.value == '')
				addValidationItem('validationSummaryList', '<strong>Purchase date</strong> is required.');
			
			if (commute_No.checked == false && commute_Yes.checked == false)
			{
				addValidationItem('validationSummaryList', 'Please confirm whether <strong>you use this vehicle to commute to work or a place of study</strong>.');
				controlsInErrorState[controlsInErrorState.length] = commute.id + "_error";
			}
				
			if (businessUse_No.checked == false && businessUse_Yes.checked == false)
			{
				addValidationItem('validationSummaryList', 'Please confirm whether <strong>you use this vehicle for business purposes</strong>.');
				controlsInErrorState[controlsInErrorState.length] = businessUse.id + "_error";
			}
			
			if (businessUse_Yes.checked == true)
			{
				if (businessAnnualMileage.value == '')
				{
					addValidationItem('validationSummaryList', '<strong>Annual mileage for business purposes</strong> is required.');
					controlsInErrorState[controlsInErrorState.length] = businessAnnualMileage.id + "_error";	
				}
			}
			
			if (totalAnnualMileage.value == '')
			{
				addValidationItem('validationSummaryList', '<strong>Total annual mileage in this vehicle</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = totalAnnualMileage.id + "_error";	
			}
					
			if (normalPaymentMethod.selectedIndex == 0)
			{
				addValidationItem('validationSummaryList', '<strong>Normal method of payment</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = normalPaymentMethod.id + "_error";	
			}
			
			if (incidents_No.checked == false && incidents_Yes.checked == false)
			{
				addValidationItem('validationSummaryList', 'Please confirm whether you have <strong>had any accidents, thefts or losses, regardless of blame, in the last 5 years</strong>.');
				controlsInErrorState[controlsInErrorState.length] = incidents.id + "_error";
			}
			
			if (convictions_No.checked == false && convictions_Yes.checked == false)
			{
				addValidationItem('validationSummaryList', 'Please confirm whether you have <strong>ever been unable to drive because of a court disqualification or in the last 5 years been convicted of any motoring offences or have any convictions pending</strong>.');
				controlsInErrorState[controlsInErrorState.length] = convictions.id + "_error";
			}
			

			
			if (controlsInErrorState.length > 0)
			{
				pageIsValid = false;
				
				try
				{
					showErrors(controlsInErrorState);
					pageErrorMessage.style.display = 'block';
					document.getElementById('validationSummaryList').style.display = 'block';
				}
				catch (e)
				{
				}
			}
			else
			{
				pageErrorMessage.style.display = 'none';
				document.getElementById('validationSummaryList').style.display = 'none';

				
			}
		}
	}
	catch (ex)
	{
	}

	return pageIsValid;
}

//******************************************************************************************
// Error Handling
//******************************************************************************************

// General function to handle AJAX errors
function errorHandler(error)
{
    // Simply direct user to message page
    window.location = PAGE_MESSAGE_SERVICE;
}

//******************************************************************************************
// Misc Functions
//******************************************************************************************

var scrolledToElement = false;

// Uses scrollTo to scroll to the passed in element
function scrollToElement(el, intoView)
{
	if (el.scrollIntoView && intoView)
		el.scrollIntoView(true);
	else
	{
		var destX = getAscendingLefts(el);
		var destY = getAscendingTops(el);
		
		// Scroll to element
		window.scrollTo(destX, destY);
	}
	
	scrolledToElement = true;
}

// Scrolls the page to the error summary on postback
function scrollToValidation()
{
	var btnContinue = document.getElementById('btnContinue');
	scrollToElement(btnContinue, true);
}

// Help icon constants
var ICON_HELP = "btn_Help.gif";
var ICON_HELP_ANIMATED = "icon_HelpAnimated.gif";

// Displays a help speech bubble to aid with using the mouse over icons
function showHelp()
{		
	try
	{				
		if (document.getElementById('dteCoverStartDate_Day').value == '')
		{
			// Show the speech bubble next to the first help icon
			var icon = document.getElementById('imgHelpCoverRequired');
			var speechBubble = document.getElementById('speechBubble');
			
			document.getElementById('speechBubbleText').innerHTML = "<span class='title'>Hover your mouse</span> over these icons for useful information to help you complete the quote.";
			
			speechBubble.style.zIndex = '1';
			speechBubble.style.position = 'absolute';
			speechBubble.style.display = 'block';
			
			var xPos = getAscendingLefts(icon);
			var yPos = getAscendingTops(icon);
			
			var xPosAnimation = parseInt(xPos) - parseInt(speechBubble.offsetWidth) + parseInt(icon.offsetWidth) + 7;
			var yPosAnimation = parseInt(yPos) - parseInt(speechBubble.offsetHeight) + 20;
			
			speechBubble.style.left = xPosAnimation + 'px';
			speechBubble.style.top = yPosAnimation + 'px';
			
			// Change icon images 
			animateHelpIcons(true);
		}
	}
	catch (e)
	{
	}
}

// Hides the help speech bubble
function hideHelp()
{
	// Simply hide the speech bubble & reset image url's
	document.getElementById('speechBubble').style.display = 'none';
	animateHelpIcons(false);
}

// If window is resized, check if help is open and move it
function checkHelp()
{
	if (document.getElementById('speechBubble').style.display == 'block')
		showHelp();
}

function checkWindscreen()
{
	if (document.getElementById('occSpeechWindscreen').style.display == 'block')
		showWindscreenBubble();
}

// Changes the src of all help icon images on the page 
function animateHelpIcons(animate)
{
	var icons = new Array();
	icons = document.images;
	
	for (var x = 0; x < icons.length; x++)
	{
		var icon = icons[x];
		var imageSrc = icon.src;
		
		if (animate)
		{
			if (imageSrc.indexOf(ICON_HELP) != -1)
				icon.src = imageSrc.toString().replace(ICON_HELP, ICON_HELP_ANIMATED);
		}
		else
		{
			if (imageSrc.indexOf(ICON_HELP_ANIMATED) != -1)
				icon.src = imageSrc.toString().replace(ICON_HELP_ANIMATED, ICON_HELP);
		}
	}
}

// If coming from PP to edit vehicle details, scroll page as required
function checkScrollRequired()
{
	var scrollLocation = window.location.hash;
	
	if (scrollLocation.length > 0)
	{
		var scrollElement = null;
		
		if (scrollLocation == '#VehicleDetails')
			scrollElement = document.getElementsByName('VehicleDetails')[0];
		else
		{
			scrollElement = document.getElementById('cboVoluntaryExcess');
			
			// Focus voluntary excess field
			setTimeout("scrollElement.focus();", 0);
		}
		
		// Scroll to the element
		scrollToElement(scrollElement, false);
	}
}

// Add key stroke restrictions to input fields
function setControlAttributes() 
{
	// Help speech bubble events
	addEvent(document.getElementById('dteCoverStartDate_Day'), "focus", showHelp);
	addEvent(document.getElementById('dteCoverStartDate_Day'), "blur", hideHelp);
	
	// Key restriction events
	addEvent(document.getElementById('dteCoverStartDate_Day'), "keypress", checkNum);
	addEvent(document.getElementById('dteCoverStartDate_Month'), "keypress", checkNum);
	addEvent(document.getElementById('dteCoverStartDate_Year'), "keypress", checkNum);
	addEvent(document.getElementById('dteDateOfBirth_Day'), "keypress", checkNum);
	addEvent(document.getElementById('dteDateOfBirth_Month'), "keypress", checkNum);
	addEvent(document.getElementById('dteDateOfBirth_Year'), "keypress", checkNum);
	addEvent(document.getElementById('txtHouseNumberOrName'), "keypress", checkAlphaNum);
	addEvent(document.getElementById('txtPostcode'), "keypress", checkAlphaNumPostcode);
	//addEvent(document.getElementById('txtTelephoneNumber'), "keypress", checkNum);
	addEvent(document.getElementById('txtDaytimePhoneNumber'), "keypress", checkNum);
	addEvent(document.getElementById('txtEveningPhoneNumber'), "keypress", checkNum);
	addEvent(document.getElementById('txtUKResidencyYears'), "keypress", checkNum);
	addEvent(document.getElementById('txtUKResidencyMonths'), "keypress", checkNum);
	addEvent(document.getElementById('txtLicenceHeldDurationYears'), "keypress", checkNum);
	addEvent(document.getElementById('txtRegNo'), "keypress", checkAlphaNumPostcode);
	addEvent(document.getElementById('txtYearOfMake'), "keypress", checkNum);
	addEvent(document.getElementById('txtEstimatedValue'), "keypress", checkNum);
	addEvent(document.getElementById('txtPurchaseDateMonths'), "keypress", checkNum);
	addEvent(document.getElementById('txtPurchaseDateYears'), "keypress", checkNum);
	addEvent(document.getElementById('txtTotalAnnualMileage'), "keypress", checkNum);
	addEvent(document.getElementById('popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Day'), "keypress", checkNum);
	addEvent(document.getElementById('popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Month'), "keypress", checkNum);
	addEvent(document.getElementById('popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Year'), "keypress", checkNum);
	addEvent(document.getElementById('popUpAdditionalDriver_txtAdditionalDriverUKResidencyYears'), "keypress", checkNum);
	addEvent(document.getElementById('popUpAdditionalDriver_txtAdditionalDriverUKResidencyMonths'), "keypress", checkNum);
	addEvent(document.getElementById('popUpAdditionalDriver_txtAdditionalDriverLicenceHeldDurationYears'), "keypress", checkNum);
	addEvent(document.getElementById('popUpVehicleDetails_txtYearOfMake'), "keypress", checkNum);
	
	// Occupation search events
	addEvent(document.getElementById('lstFullTimeOccupation'), "focus", function() { SearchBoxList_OnFocus(document.getElementById('lstFullTimeOccupation'), 'txtFullTimeOccupation', 'errFullTimeOccupation', true); });
	addEvent(document.getElementById('lstPartTimeOccupation'), "focus", function() { SearchBoxList_OnFocus(document.getElementById('lstPartTimeOccupation'), 'txtPartTimeOccupation', 'errPartTimeOccupation', true); });
	addEvent(document.getElementById('popUpAdditionalDriver_lstAdditionalDriverFullTimeOccupation'), "focus", function() { SearchBoxList_OnFocus(document.getElementById('popUpAdditionalDriver_lstAdditionalDriverFullTimeOccupation'), 'popUpAdditionalDriver_txtAdditionalDriverFullTimeOccupation', '', false); });
	addEvent(document.getElementById('popUpAdditionalDriver_lstAdditionalDriverPartTimeOccupation'), "focus", function() { SearchBoxList_OnFocus(document.getElementById('popUpAdditionalDriver_lstAdditionalDriverPartTimeOccupation'), 'popUpAdditionalDriver_txtAdditionalDriverPartTimeOccupation', '', false); });

	// Education search events
	addEvent(document.getElementById('hlUniNotListed'), "click", function() { hlUniNotListed_Click(); return false; });
	addEvent(document.getElementById('lstWhereStudying'), "focus", function() { SearchBoxList_OnFocus(document.getElementById('lstWhereStudying'), 'txtWhereStudying', 'errWhereStudying', true); });
	
	// Windscreen upsell events
	addEvent(document.getElementById('rdoWindscreen_0'), "click", function() { showWindscreenBubble(false); });
	addEvent(document.getElementById('rdoWindscreen_1'), "click", function() { showWindscreenBubble(false); });
}

// Prompts user whether they would like to close the pop up window
function confirmCancel(popUpID) 
{
	answer = confirm('Are you sure you wish to close without saving?');
	
	if ( answer != 0 ) 
	{	
		hidePopUp(popUpID);
		return true;
	}
	else 
	{
		return false;
	}
}

function setSelectedIndex(selectObject, selectedValue)
{
	selectObject = document.getElementById(selectObject);
	if (selectObject)
	{
		for ( var i=0; i < selectObject.options.length; i++ )
		{
			if (selectObject.options[i].text.toUpperCase() == selectedValue.toUpperCase() || selectObject.options[i].value == selectedValue)
				selectObject.options[i].selected = true;
			else
				selectObject.options[i].selected = false;
		}
	}
}

// Adds a list item to a list
function addListItem(list, listItem)
{
	try
	{
		list.add(listItem, null);
	}
	catch (e)
	{
		list.add(listItem);
	}
}

//******************************************************************************************
// Field Specific Functions
//******************************************************************************************

//Fired when we need to check whether or not there are any additional drivers.
function evaluateDriverCount(driverIndex, driverCount, additionalDrivers_Yes, additionalDrivers_No, additionalDriversPanel, additionalDriversOptionRow, addAnotherDriverRow)
{
	document.getElementById(driverIndex).value = '';
	driverCount = document.getElementById(driverCount).value;
	additionalDrivers_Yes = document.getElementById(additionalDrivers_Yes);
	additionalDrivers_No = document.getElementById(additionalDrivers_No);
	additionalDriversPanel = document.getElementById(additionalDriversPanel);
	additionalDriversOptionRow = document.getElementById(additionalDriversOptionRow);
	addAnotherDriverRow = document.getElementById(addAnotherDriverRow);
	
	if (parseInt(driverCount) == 0)
	{
		additionalDrivers_Yes.checked = false;
		additionalDrivers_No.checked = true;
		additionalDriversPanel.style.display = 'none';
		additionalDriversOptionRow.style.display = 'block';
	}
	else
	{
		additionalDriversPanel.style.display = 'block';
		additionalDriversOptionRow.style.display = 'none';
		
		if (parseInt(driverCount) >= MAX_NUMBER_OF_DRIVERS)
			addAnotherDriverRow.style.display = 'none';
	}
}

//Fired by every event when is loses focus.
function clearAlert(control)
{
	try
	{
		var controlID;
		if (typeof control != 'object')
			controlID = control;
		else
			controlID = control.id;
	
		arrInput = [controlID];
		resetAlerts(arrInput);
	}
	catch (e)
	{
		
	}
}

//Fired when the vehicle modifications is changed.
function toggleVehicleModifications(modifications, slidePanel, slideContent, modificationsList)
{
	modifications = document.getElementById(modifications);
	modificationsList = document.getElementById(modificationsList);
	
	if (modifications.checked)
	{
		slideElement(slidePanel, slideContent, 100);
		if (modificationsList[modificationsList.selectedIndex].value == "")
		{
			for ( var i=0; i < modificationsList.options.length; i++ )
			{
				modificationsList.options[i].selected = false;
			}
			modificationsList.options[0].selected = true;
		}
		else
			modificationsList.options[0].selected = false;
	}
	else
	{
		cancelSlide(slidePanel, slideContent);
		for ( var i=0; i < modificationsList.options.length; i++ )
		{
			modificationsList.options[i].selected = false;
		}
		modificationsList.options[0].selected = true;
	}
}

//Fired when the business use radio buttons are clicked.
function toggleBusinessUse(businessUse, businessUseMessage, slidePanel, slideContent, businessUseMileage)
{
	businessUse = document.getElementById(businessUse);
	businessUseMessage = document.getElementById(businessUseMessage);
	businessUseMileage = document.getElementById(businessUseMileage);
	
	if (businessUse.checked)
	{
		slideElement(slidePanel, slideContent, 50);
		businessUseMessage.innerHTML = ' (including for business)';
	}
	else
	{
		cancelSlide(slidePanel, slideContent);
		businessUseMessage.innerHTML = '';
		businessUseMileage.value = '';
	}
}

//Fired when they've changed the any other drivers option.
function toggleAnyOtherDrivers(anyOtherDriversOption, changeChecked)
{	
	anyOtherDriversOption = document.getElementById(anyOtherDriversOption);
	coverStartDateDay = document.getElementById('dteCoverStartDate_Day');
	coverStartDateMonth = document.getElementById('dteCoverStartDate_Month');
	coverStartDateYear = document.getElementById('dteCoverStartDate_Year');
	
	//Error fields.
	rowError = document.getElementById('errAnyOtherDrivers');
	errorMessage = document.getElementById('lblErrorAnyOtherDrivers');
	
	//Validate the cover start date first.
	if (coverStartDateDay.value == '' || coverStartDateMonth.value == '' || coverStartDateYear.value == '')
	{
		rowError.style.display = 'block';
		errorMessage.innerHTML = "<strong>Cover start date</strong> must be completed before adding additional drivers."; 
		
		if (changeChecked)
		{
			document.getElementById('optAnyOtherDrivers_0').checked = false;
			document.getElementById('optAnyOtherDrivers_1').checked = true;
		}
	}
	else
	{
		rowError.style.display = 'none';
		
		if (anyOtherDriversOption.checked == true)
		{
			resetDriverPopup();
			showPopUp('popUpAdditionalDriver', 'middleCenter', 660, 520); //Height, width.
		}
	}
}

//Fired when they've entered their full name.
function fullNameEntered(clientForename, clientSurname, vehicleOwnerList, vehicleRegisteredToList)
{
	clientForename = document.getElementById(clientForename).value;
	clientSurname = document.getElementById(clientSurname).value;	
	vehicleOwnerList = document.getElementById(vehicleOwnerList);	
	vehicleRegisteredToList = document.getElementById(vehicleRegisteredToList);	
	
	if (clientForename != '' && clientSurname != '')
	{
		//Update the combo boxes to replace 'Proposer' with the client's name.
		for ( var i=0; i < vehicleOwnerList.options.length; i++ )
        {
            if (vehicleOwnerList.options[i].value == 'X') //X = Proposer
            {       
				var y = document.createElement('option');
                y.value = vehicleOwnerList.options[i].value;
                y.text = clientForename + ' ' + clientSurname;
                if (vehicleOwnerList.options[i].selected)
					y.selected = true;
                vehicleOwnerList.options[i] = y;
            }
        }
        
        for ( var i=0; i < vehicleOwnerList.options.length; i++ )
        {
            if (vehicleRegisteredToList.options[i].value == 'X') //X = Proposer
            {       
				var y = document.createElement('option');
                y.value = vehicleRegisteredToList.options[i].value;
                y.text = clientForename + ' ' + clientSurname;
                if (vehicleRegisteredToList.options[i].selected)
					y.selected = true;
                vehicleRegisteredToList.options[i] = y;
            }
        }
	}
}

//Fired when the date of birth is updated.
function updateUKResidency(checkbox, dateOfBirthDays, dateOfBirthMonths, dateOfBirthYears, ukResidencyMonths, ukResidencyYears, populate, rowError, errorMessage)
{
	checkbox = document.getElementById(checkbox);
	if (checkbox.checked && (document.getElementById(dateOfBirthDays).value != '' && document.getElementById(dateOfBirthMonths).value != '' && document.getElementById(dateOfBirthYears).value != ''))
	{
		document.getElementById(ukResidencyMonths).value = '';
		document.getElementById(ukResidencyYears).value = '';
		validateUKResidency(checkbox, dateOfBirthDays, dateOfBirthMonths, dateOfBirthYears, ukResidencyMonths, ukResidencyYears, populate, rowError, errorMessage);
	}
	else
	{
		if (checkbox.checked == false && (document.getElementById(ukResidencyYears).value != '' || document.getElementById(ukResidencyMonths).value != ''))
		{
			validateUKResidency(checkbox, dateOfBirthDays, dateOfBirthMonths, dateOfBirthYears, ukResidencyMonths, ukResidencyYears, false, rowError, errorMessage);
		}		
		else
		{
			if (document.getElementById(dateOfBirthDays).value != '' && document.getElementById(dateOfBirthMonths).value != '' && document.getElementById(dateOfBirthYears).value != '')
			{
				//They've just entered their date of birth so we need to default the check box to true and work out the UK residency.
				checkbox.checked = true;
				document.getElementById(ukResidencyMonths).value = '';
				document.getElementById(ukResidencyYears).value = '';
				validateUKResidency(checkbox, dateOfBirthDays, dateOfBirthMonths, dateOfBirthYears, ukResidencyMonths, ukResidencyYears, populate, rowError, errorMessage);
			}
			else
			{
				checkbox.checked = false;
				document.getElementById(ukResidencyMonths).value = '';
				document.getElementById(ukResidencyYears).value = '';
			}
		}
	}
}

//Fired when the UK residency checkbox is clicked.
function toggleUKResidency(checkbox, dateOfBirthDays, dateOfBirthMonths, dateOfBirthYears, ukResidencyMonths, ukResidencyYears, populate, rowError, errorMessage)
{
	if (!checkbox.checked)
	{
		document.getElementById(ukResidencyMonths).value = '';
		document.getElementById(ukResidencyYears).value = '';
	}
	else
	{
		document.getElementById(ukResidencyMonths).value = '';
		document.getElementById(ukResidencyYears).value = '';
		validateUKResidency(checkbox, dateOfBirthDays, dateOfBirthMonths, dateOfBirthYears, ukResidencyMonths, ukResidencyYears, populate, rowError, errorMessage);
	}
}

//Fired when the number of years NCD changes.
function toggleNCDRows(cboNCD, slidePanel, slideContent)
{
	if (cboNCD.selectedIndex >= 1)
		slideElement(slidePanel, slideContent, 110);
	else
		cancelSlide(slidePanel, slideContent);
}

function togglePartTimeOccupation(partTimeOccupation, slidePanel, slideContent, txtPartTimeOccupation, lstPartTimeOccupation)
{
	partTimeOccupation = document.getElementById(partTimeOccupation);
	txtPartTimeOccupation = document.getElementById(txtPartTimeOccupation);
	lstPartTimeOccupation = document.getElementById(lstPartTimeOccupation);
	
	if (partTimeOccupation.checked)
		slideElement(slidePanel, slideContent, 100);
	else
	{
		cancelSlide(slidePanel, slideContent);
		txtPartTimeOccupation.value = '';
		
		//Sneaky way of performing an asynchronous call.
		setTimeout("filterList(document.getElementById('txtPartTimeOccupation'), 'cboPartTimeOccupation', 'lstPartTimeOccupation', true, 400, false, false, false)", 1);
		lstPartTimeOccupation.selectedIndex = -1;
		var errorField = [txtPartTimeOccupation.id];
		resetAlerts(errorField);
	}
}

//Fired when any button on the page is clicked.
function buttonClickEvent(buttonToClick)
{
    if (window.event)
    {
        if (window.event.keyCode == 13)
        {
            event.returnValue = false;
            event.cancel = true;

            if (buttonToClick != '')
            {
                buttonToClick = document.getElementById(buttonToClick);
                buttonToClick.click();
            }
        }
    }
}

// Handles the txtPostcode onblur event - Performs an address lookup
function txtPostcode_OnBlur(txt)
{
	clearAlert(txt); 
	styleSwap(txt, 'off'); 

	if (checkValidPostcode(txt, 'errPostcode', 'rowAddress'))
	{
		document.getElementById('txtAddress1').value = '';
		document.getElementById('txtAddress2').value = '';
		checkAddressPostcode(txt, 'txtPostcodeWhereVehicleKept', 'chkPostcodeWhereVehicleKept');
		validatePostcode('txtHouseNumberOrName', 'txtPostcode', 'addressRow', 'showAddress', 'editAddress', 'txtAddress1', 'txtAddress2', 'lblAddress1', 'lblAddress2', 'lblAddress3',  'imgConfirmAddressProgress', 'errPostcode', 'lblErrorPostcode', false, true);
		
		// Progress image doesn't always hide correctly, so hide once complete
		setTimeout("document.getElementById('imgConfirmAddressProgress').style.display = 'none';", 0);
	}
}

// Handles the btnConfirmAddress onclick event - Performs an address lookup
function btnConfirmAddress_OnClick(txt)
{	
	clearAlert(txt); 
	
	if (checkValidPostcode(txt, 'errPostcode', 'rowAddress') || txt.value == '')
	{
		document.getElementById('txtAddress1').value = '';
		document.getElementById('txtAddress2').value = '';
		document.getElementById('lblAddress2').style.display = 'block';
		checkAddressPostcode(txt, 'txtPostcodeWhereVehicleKept', 'chkPostcodeWhereVehicleKept');
		validatePostcode('txtHouseNumberOrName', 'txtPostcode', 'addressRow', 'showAddress', 'editAddress', 'txtAddress1', 'txtAddress2', 'lblAddress1', 'lblAddress2', 'lblAddress3',  'imgConfirmAddressProgress', 'errPostcode', 'lblErrorPostcode', true, true);
		
		// Progress image doesn't always hide correctly, so hide once complete
		setTimeout("document.getElementById('imgConfirmAddressProgress').style.display = 'none';", 0);
	}
}

//Fired when we need to validate a postcode.
function checkValidPostcode(postcode, errorRow, addressMessage)
{
	var regEx = /\b[a-zA-Z]([a-zA-Z]|[0-9])([a-zA-Z]|[0-9])?([a-zA-Z]|[0-9])?[ ]*[0-9][a-zA-Z][a-zA-Z]|[a-zA-Z][0-9]\b/;
	var isValid = regEx.test(postcode.value);
	
	errorRow = document.getElementById(errorRow);
	
	if (postcode.value == '')
		return false;
		
	if (!isValid)
	{
		errorRow.style.display = 'block';
		errorRow.innerHTML = '<strong>Postcode</strong> does not appear to be valid, please check what you have entered.';
		
		if (addressMessage != '')
		{
			addressMessage = document.getElementById(addressMessage);
			addressMessage.style.display = 'none';
		}
	}
	else
	{
		errorRow.style.display = 'none';
		arrInput = [postcode.id, 'txtHouseNumberOrName'];
		resetAlerts(arrInput);
	}
	
	return isValid;
}

//Fired when we need to validate where the vehicle is kept.
function checkPostcodeWhereVehicleKept(vehicleKeptPostcode, checkbox, addressPostcode, errorRow)
{
	addressPostcode = document.getElementById(addressPostcode);
	checkbox = document.getElementById(checkbox);

	if (checkValidPostcode(vehicleKeptPostcode, errorRow, ''))
	{
		if (addressPostcode.value == vehicleKeptPostcode.value)
			checkbox.checked = true;
		else
			checkbox.checked = false;
	}
	else
		checkbox.checked = false;
}

function OpenAddressEdit()
{
	document.getElementById('showAddress').style.display = 'none';
	document.getElementById('editAddress').style.display = 'block';
	
	document.getElementById('lblAddress2').style.display = 'block';
	document.getElementById('txtAddress1').value = document.getElementById('lblAddress1').innerHTML.substring(0, 20);
	document.getElementById('txtAddress2').value = document.getElementById('lblAddress2').innerHTML.substring(0, 20);
	document.getElementById('txtAddress1').focus();
}

function SaveAddressEdit()
{
	document.getElementById('lblAddress1').innerHTML = document.getElementById('txtAddress1').value;
	document.getElementById('lblAddress2').innerHTML = document.getElementById('txtAddress2').value;
	
	if (document.getElementById('txtAddress2').value == '')
		document.getElementById('lblAddress2').style.display = 'none';
	else
		document.getElementById('lblAddress2').style.display = 'block';

	document.getElementById('showAddress').style.display = 'block';
	document.getElementById('editAddress').style.display = 'none';
}

function CancelAddressEdit()
{
	document.getElementById('txtAddress1').value = document.getElementById('lblAddress1').innerHTML;
	document.getElementById('txtAddress2').value = document.getElementById('lblAddress2').innerHTML;

	document.getElementById('showAddress').style.display = 'block';
	document.getElementById('editAddress').style.display = 'none';
}

//Fired when we need to validate where the main postcode in conjunction with the postcode where the vehicle kept.
function checkAddressPostcode(addressPostcode, vehicleKeptPostcode, checkbox)
{
	vehicleKeptPostcode = document.getElementById(vehicleKeptPostcode);
	checkbox = document.getElementById(checkbox);

	if (vehicleKeptPostcode.value == addressPostcode.value)
		checkbox.checked = true;
	else
		checkbox.checked = false;
}

//Fired when the vehicle is kept at the same address as the residency.
function togglePostcodeWhereVehicleKept(checkbox, addressPostcode, vehicleKeptPostcode, errorRow)
{
	addressPostcode = document.getElementById(addressPostcode);
	vehicleKeptPostcode = document.getElementById(vehicleKeptPostcode);
	
	if (addressPostcode.value == '' || !checkValidPostcode(addressPostcode, errorRow, ''))
	{
		checkbox.checked = false;
	}
	else
	{
		if (checkbox.checked)
		{
			vehicleKeptPostcode.value = addressPostcode.value;
			clearAlert(vehicleKeptPostcode);
		}
		else
		{
			vehicleKeptPostcode.value = '';
		}
	}
}

//Fired when we need to check whether or not someone wishes to remove any specified accidents from their quote.
function checkAccidents(accidentsRadio, hasAccidents)
{
	accidentsRadio = document.getElementById(accidentsRadio);	
	hasAccidents = document.getElementById(hasAccidents);
	
	if (accidentsRadio.checked == true && parseInt(hasAccidents.value) > 0)
		showPopUp('popUpConfirmRemoveAccidents', 'middleCenter', 250, 400);
}

//Fired when we need to check whether or not someone wishes to remove any specified convictions/bans from their quote.
function checkBansAndConvictions(bansAndConvictionsRadio, hasBans, hasConvictions)
{
	bansAndConvictionsRadio = document.getElementById(bansAndConvictionsRadio);	
	hasBans = document.getElementById(hasBans);
	hasConvictions = document.getElementById(hasConvictions);
	
	if (bansAndConvictionsRadio.checked == true && (parseInt(hasBans.value) > 0 || parseInt(hasConvictions.value) > 0))
		showPopUp('popUpConfirmRemoveBansAndConvictions', 'middleCenter', 250, 400);
}

//Resets the option boxes to yes.
function resetAnswers(yesAnswer, noAnswer)
{
	yesAnswer = document.getElementById(yesAnswer);
	noAnswer = document.getElementById(noAnswer);
	
	yesAnswer.checked = true;
	noAnswer.checked = false;
}

//Clears the fields of the driver popup box.
function clearDriverPopup()
{
	document.getElementById('popUpAdditionalDriver_cboAdditionalDriverTitle').selectedIndex = 0;
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverFirstName').value = '';
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverSurname').value = '';
	document.getElementById('popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Day').value = '';
	document.getElementById('popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Month').value = '';
	document.getElementById('popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Year').value = '';
	document.getElementById('popUpAdditionalDriver_cboAdditionalDriverGender').selectedIndex = 0;
	document.getElementById('popUpAdditionalDriver_cboAdditionalDriverMaritalStatus').selectedIndex = 0;
	if (document.getElementById('popUpAdditionalDriver_cboAdditionalDriverUnion'))
		document.getElementById('popUpAdditionalDriver_cboAdditionalDriverUnion').selectedIndex = 0;
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverFullTimeOccupation').value = '';
	document.getElementById('popUpAdditionalDriver_lstAdditionalDriverFullTimeOccupation').selectedIndex = 0;
	document.getElementById('slidePanelAdditionalFullTimeOccupation').style.display = 'none';
	document.getElementById('slideContentAdditionalFullTimeOccupation').style.display = 'none';
	document.getElementById('popUpAdditionalDriver_optAdditionalDriverPartTimeOccupation_0').checked = false;
	document.getElementById('popUpAdditionalDriver_optAdditionalDriverPartTimeOccupation_1').checked = true;
	togglePartTimeOccupation('popUpAdditionalDriver_optAdditionalDriverPartTimeOccupation_0', 'slidePanelAdditionalDriverPartTimeOccupation', 'slideContentAdditionalDriverPartTimeOccupation', 'popUpAdditionalDriver_txtAdditionalDriverPartTimeOccupation', 'popUpAdditionalDriver_lstAdditionalDriverPartTimeOccupation');
	filterList(document.getElementById('popUpAdditionalDriver_txtAdditionalDriverFullTimeOccupation'), 'cboFullTimeOccupation', 'popUpAdditionalDriver_lstAdditionalDriverFullTimeOccupation', true, 0, false, false);
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverPartTimeOccupation').value = '';
	document.getElementById('popUpAdditionalDriver_lstAdditionalDriverPartTimeOccupation').selectedIndex = 0;
	filterList(document.getElementById('popUpAdditionalDriver_txtAdditionalDriverPartTimeOccupation'), 'cboPartTimeOccupation', 'popUpAdditionalDriver_lstAdditionalDriverPartTimeOccupation', true, 0, false, false);
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverUKResidencyYears').value = '';
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverUKResidencyMonths').value = '';
	document.getElementById('popUpAdditionalDriver_chkAdditionalDriverUKResidency').checked = false;
	document.getElementById('popUpAdditionalDriver_cboAdditionalDriverLicenceType').selectedIndex = 0;
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverLicenceHeldDurationYears').value = '';
	var txtLicenceHeldDurationMonths = document.getElementById('popUpAdditionalDriver_txtAdditionalDriverLicenceHeldDurationMonths');
	txtLicenceHeldDurationMonths.value = '';
	txtLicenceHeldDurationMonths.style.display = 'none';
	document.getElementById('popUpAdditionalDriver_lblAdditionalDriverLicenceHeldDurationMonths').style.display = 'none';
	document.getElementById('popUpAdditionalDriver_optAdditionalDriverCommute_0').checked = false;
	document.getElementById('popUpAdditionalDriver_optAdditionalDriverCommute_1').checked = false;
	document.getElementById('popUpAdditionalDriver_optAdditionalDriverBusinessUse_0').checked = false;
	document.getElementById('popUpAdditionalDriver_optAdditionalDriverBusinessUse_1').checked = false;
	document.getElementById('popUpAdditionalDriver_cboRelationshipToMainDriver').selectedIndex = 0;
}

//Clears all the errors in the driver popup.
function resetDriverPopup()
{
	var driverFields = ['cboAdditionalDriverTitle', 'popUpAdditionalDriver_txtAdditionalDriverFirstName', 'popUpAdditionalDriver_txtAdditionalDriverSurname', 'popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Day', 'popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Month', 'popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Year', 'cboAdditionalDriverGender', 'cboAdditionalDriverMaritalStatus', 'cboAdditionalDriverUnion', 'popUpAdditionalDriver_txtAdditionalDriverFullTimeOccupation', 'popUpAdditionalDriver_txtAdditionalDriverPartTimeOccupation', 'popUpAdditionalDriver_txtAdditionalDriverUKResidencyYears', 'popUpAdditionalDriver_txtAdditionalDriverUKResidencyMonths', 'cboAdditionalDriverLicenceType', 'popUpAdditionalDriver_txtAdditionalDriverLicenceHeldDurationYears', 'popUpAdditionalDriver_txtAdditionalDriverLicenceHeldDurationMonths', 'popUpAdditionalDriver_optAdditionalDriverCommute', 'popUpAdditionalDriver_optAdditionalDriverBusinessUse', 'cboRelationshipToMainDriver'];
	document.getElementById('errAdditionalDriverPopUp').style.display = 'none';
	document.getElementById('errAdditionalDriverUKResidency').style.display = 'none';
	document.getElementById('errAdditionalDriverLicenceHeldDuration').style.display = 'none';
	document.getElementById('errAdditionalDriverDateOfBirth').style.display = 'none';
	resetAlerts(driverFields);
}

//Displays the pop up and populates the fields.
function editAdditionalDriver(driverIndex, title, firstName, surname, dateOfBirthDay, dateOfBirthMonth, dateOfBirthYear, gender, maritalStatus, union, fullTimeOccupation, partTimeOccupation, ukResidencyYears, ukResidencyMonths, licenceType, licenceHeldDurationYears, licenceHeldDurationMonths, commutes, businessUse, relationshipToMainDriver)
{
	//Set the driver index so we know we're editing.
	document.getElementById('hdnDriverIndex').value = driverIndex;
	//Show the popup.
	toggleAnyOtherDrivers('optAnyOtherDrivers_0', false);
	//Populate the fields.
	setSelectedIndex('popUpAdditionalDriver_cboAdditionalDriverTitle', title);
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverFirstName').value = firstName;
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverSurname').value = surname;
	document.getElementById('popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Day').value = dateOfBirthDay;
	document.getElementById('popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Month').value = dateOfBirthMonth;
	document.getElementById('popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Year').value = dateOfBirthYear;
	setSelectedIndex('popUpAdditionalDriver_cboAdditionalDriverGender', gender);
	setSelectedIndex('popUpAdditionalDriver_cboAdditionalDriverMaritalStatus', maritalStatus);
	setSelectedIndex('popUpAdditionalDriver_cboAdditionalDriverUnion', union);
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverFullTimeOccupation').value = fullTimeOccupation;
	setSelectedIndex('popUpAdditionalDriver_lstAdditionalDriverFullTimeOccupation', fullTimeOccupation);
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverPartTimeOccupation').value = partTimeOccupation;
	setSelectedIndex('popUpAdditionalDriver_lstAdditionalDriverPartTimeOccupation', partTimeOccupation);
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverUKResidencyYears').value = ukResidencyYears;
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverUKResidencyMonths').value = ukResidencyMonths;
	setSelectedIndex('popUpAdditionalDriver_cboAdditionalDriverLicenceType', licenceType);
	document.getElementById('popUpAdditionalDriver_txtAdditionalDriverLicenceHeldDurationYears').value = licenceHeldDurationYears;
	var txtLicenceHeldDurationMonths = document.getElementById('popUpAdditionalDriver_txtAdditionalDriverLicenceHeldDurationMonths');
	txtLicenceHeldDurationMonths.value = '';
	
	if (licenceHeldDurationYears < 2 && licenceHeldDurationMonths > 0)
	{
		txtLicenceHeldDurationMonths.value = licenceHeldDurationMonths;
		txtLicenceHeldDurationMonths.style.display = 'inline';
		document.getElementById('popUpAdditionalDriver_lblAdditionalDriverLicenceHeldDurationMonths').style.display = 'inline';
	}
	else
	{
		txtLicenceHeldDurationMonths.style.display = 'none';
		document.getElementById('popUpAdditionalDriver_lblAdditionalDriverLicenceHeldDurationMonths').style.display = 'none';
	}

	//I'm sure there's nice way of doing this but I can't remember what it is!!	
	if (commutes == "true")
	{
		document.getElementById('popUpAdditionalDriver_optAdditionalDriverCommute_0').checked = true;
		document.getElementById('popUpAdditionalDriver_optAdditionalDriverCommute_1').checked = false;
	}
	else
	{
		document.getElementById('popUpAdditionalDriver_optAdditionalDriverCommute_0').checked = false;
		document.getElementById('popUpAdditionalDriver_optAdditionalDriverCommute_1').checked = true;
	}
	
	if (businessUse == "true")
	{
		document.getElementById('popUpAdditionalDriver_optAdditionalDriverBusinessUse_0').checked = true;
		document.getElementById('popUpAdditionalDriver_optAdditionalDriverBusinessUse_1').checked = false;
	}
	else
	{
		document.getElementById('popUpAdditionalDriver_optAdditionalDriverBusinessUse_0').checked = false;
		document.getElementById('popUpAdditionalDriver_optAdditionalDriverBusinessUse_1').checked = true;
	}
	
	setSelectedIndex('popUpAdditionalDriver_cboRelationshipToMainDriver', relationshipToMainDriver);	

	if (partTimeOccupation != '' && partTimeOccupation != 'No occupation selected')
	{
		document.getElementById('popUpAdditionalDriver_optAdditionalDriverPartTimeOccupation_0').checked = true;
		document.getElementById('popUpAdditionalDriver_optAdditionalDriverPartTimeOccupation_1').checked = false;
		togglePartTimeOccupation('popUpAdditionalDriver_optAdditionalDriverPartTimeOccupation_0', 'slidePanelAdditionalDriverPartTimeOccupation', 'slideContentAdditionalDriverPartTimeOccupation', 'popUpAdditionalDriver_txtAdditionalDriverPartTimeOccupation', 'popUpAdditionalDriver_lstAdditionalDriverPartTimeOccupation');
	}
	else
	{
		document.getElementById('popUpAdditionalDriver_optAdditionalDriverPartTimeOccupation_0').checked = false;
		document.getElementById('popUpAdditionalDriver_optAdditionalDriverPartTimeOccupation_1').checked = true;
	}
}

function missingBusinessMileageIsValid(missingBusinessUseMileage, businessUseMileage, businessUseOption)
{
	//Reset the alert.
	arrInput = [missingBusinessUseMileage];
	resetAlerts(arrInput);
	
	missingBusinessUseMileage = document.getElementById(missingBusinessUseMileage);
	businessUseMileage = document.getElementById(businessUseMileage);
	businessUseOption = document.getElementById(businessUseOption);
	
	if (isNaN(parseInt(missingBusinessUseMileage.value)) || missingBusinessUseMileage.value == '')
	{	
		showError(missingBusinessUseMileage.id);
		return false;
	}
	else
	{
		businessUseMileage.value = missingBusinessUseMileage.value;
		missingBusinessUseMileage.value = '';
		arrInput = [businessUseMileage.id];
		resetAlerts(arrInput);
		businessUseOption.checked = true;
		return true;
	}
}

//******************************************************************************************
// Web Service Calls
//******************************************************************************************

//Animate the appropriate animated gif.
function beginAnimation(imageToAnimate)
{	
	var timeoutID = setTimeout("document.images['" + imageToAnimate.id + "'].style.display = 'inline'", 500);
	var imgSrc = document.images[imageToAnimate.id].src;
	setTimeout("document.images['" + imageToAnimate.id + "'].src = '" + imgSrc + "'", 100);
	return timeoutID;
}

//Validate the business mileage before they continue.
function validateBusinessUse(businessUse, businessMileage, popup, missingBusinessUseMileage)
{	
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	var retVal = false;
	
	businessUse = document.getElementById(businessUse);
	businessMileage = document.getElementById(businessMileage);
	missingBusinessUseMileage = document.getElementById(missingBusinessUseMileage);

	// Create the SOAP Envelope
	var requestMessage = 

			"    <ValidateBusinessUse xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
			
			"		<businessMileageOption>" + businessUse.checked + "</businessMileageOption>" +
			
			"		<businessMileageValue>" + businessMileage.value + "</businessMileageValue>" +
			
			"    </ValidateBusinessUse>";
	
	// Send the message
	proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/ValidateBusinessUse", requestMessage, false);

	// Process the return message.
	var responseMessage = proxy.XmlHttp.responseXML;	

	var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;

	if (isValid == 'true')
		retVal = true;
	else
	{				
		if (responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0) != null)
			errorHandler(responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data);
		
		if (responseMessage.getElementsByTagName("CaptureBusinessMileage")[0].childNodes.item(0) != null)
			if (responseMessage.getElementsByTagName("CaptureBusinessMileage")[0].childNodes.item(0).data == 'true')
				showPopUp(popup, 'middleCenter', 160, 410);
	}
	
	return retVal;
}

// Get all additional drivers on page load
function getAdditionalDrivers()
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	// Create the SOAP Envelope
	var requestMessage =

			"<GetAllDriverHtml xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
			
			"</GetAllDriverHtml>"
	
	// Set up the post
	proxy.XmlHttp.onreadystatechange = function()
	{
		// Where readyState = 4 and status = 200
		if (proxy.ResponseReceived())
		{
			//Process the return message.
			var responseMessage = proxy.ResponseXml;	
			var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
			
			if (isValid == 'true')
			{
				// Clear previous drivers
				document.getElementById('pnlAdditionalDriver').innerHTML = '';
					
				var drivers = new Array();
				drivers = responseMessage.getElementsByTagName("GetDriverHtmlDetails");
				
				for (var x = 0; x < drivers.length; x++)
				{
					var driver = drivers[x];
					
					//Add the details.
					var newDriver = document.createElement('div');
					newDriver.setAttribute('id', driver.getElementsByTagName("AdditionalDriverID")[0].childNodes.item(0).data);
					newDriver.innerHTML = driver.getElementsByTagName("Html")[0].childNodes.item(0).data;
					
					// If new driver, add to the end
					document.getElementById('pnlAdditionalDriver').appendChild(newDriver);
				}
				
				document.getElementById('hdnDriverCount').value = responseMessage.getElementsByTagName("AdditionalDriverCount")[0].childNodes.item(0).data;
				evaluateDriverCount('hdnDriverIndex', 'hdnDriverCount', 'optAnyOtherDrivers_0', 'optAnyOtherDrivers_1', 'pnlAdditionalDrivers', 'rowAdditionalDriversOption', 'rowAddAnotherDriver');
				document.getElementById('errAnyOtherDrivers').style.display = 'none';
			}
		}
	}
	
	proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/GetAllDriverHtml", requestMessage, true);
}

//Add a new driver.
function addAdditionalDriver()
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	//Fields
	var coverStartDateDay = document.getElementById('dteCoverStartDate_Day');
	var coverStartDateMonth = document.getElementById('dteCoverStartDate_Month');
	var coverStartDateYear = document.getElementById('dteCoverStartDate_Year');
	var title = document.getElementById('popUpAdditionalDriver_cboAdditionalDriverTitle');
	var firstName = document.getElementById('popUpAdditionalDriver_txtAdditionalDriverFirstName');
	var surname = document.getElementById('popUpAdditionalDriver_txtAdditionalDriverSurname');
	var dateOfBirthDay = document.getElementById('popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Day');
	var dateOfBirthMonth = document.getElementById('popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Month');
	var dateOfBirthYear = document.getElementById('popUpAdditionalDriver_dteAdditionalDriverDateOfBirth_Year');
	var gender = document.getElementById('popUpAdditionalDriver_cboAdditionalDriverGender');
	var maritalStatus = document.getElementById('popUpAdditionalDriver_cboAdditionalDriverMaritalStatus');
	var union = document.getElementById('popUpAdditionalDriver_cboAdditionalDriverUnion');
	var fullTimeOccupation = document.getElementById('popUpAdditionalDriver_txtAdditionalDriverFullTimeOccupation');
	var partTimeOccupation_Yes = document.getElementById('popUpAdditionalDriver_optAdditionalDriverPartTimeOccupation_0');
	var partTimeOccupation = document.getElementById('popUpAdditionalDriver_txtAdditionalDriverPartTimeOccupation');
	var ukResidencyYears = document.getElementById('popUpAdditionalDriver_txtAdditionalDriverUKResidencyYears');
	var ukResidencyMonths = document.getElementById('popUpAdditionalDriver_txtAdditionalDriverUKResidencyMonths');
	var licenceType = document.getElementById('popUpAdditionalDriver_cboAdditionalDriverLicenceType');
	var licenceHeldDurationYears = document.getElementById('popUpAdditionalDriver_txtAdditionalDriverLicenceHeldDurationYears');
	var licenceHeldDurationMonths = document.getElementById('popUpAdditionalDriver_txtAdditionalDriverLicenceHeldDurationMonths');
	var commutes = document.getElementById('popUpAdditionalDriver_optAdditionalDriverCommute');
	var commutes_Yes = document.getElementById('popUpAdditionalDriver_optAdditionalDriverCommute_0');
	var commutes_No = document.getElementById('popUpAdditionalDriver_optAdditionalDriverCommute_1');
	var businessUse = document.getElementById('popUpAdditionalDriver_optAdditionalDriverBusinessUse');
	var businessUse_Yes = document.getElementById('popUpAdditionalDriver_optAdditionalDriverBusinessUse_0');
	var businessUse_No = document.getElementById('popUpAdditionalDriver_optAdditionalDriverBusinessUse_1');
	var relationshipToMainDriver = document.getElementById('popUpAdditionalDriver_cboRelationshipToMainDriver');
	
	//Driver index if present.
	var driverIndex = document.getElementById('hdnDriverIndex');
	var driverCount = document.getElementById('hdnDriverCount');
	
	//Place to add response to.
	var placeholder = document.getElementById('pnlAdditionalDriver');
	
	//Error controls.
	var rowError = document.getElementById('errAdditionalDriverPopUp');
	var errorMessage = document.getElementById('popUpAdditionalDriver_lblErrorAdditionalDriverPopUp');
	var validationSummaryList = document.getElementById('validationSummaryListAdditional');
	
	rowError.style.display = 'none';
	validationSummaryList.innerHTML = '';
	validationSummaryList.style.display = 'none';
	
	//Validate that the fields have been filled in correctly.
	var controlsInErrorState = new Array();
	
	if (title.selectedIndex == 0)
	{
		addValidationItem('validationSummaryListAdditional', '<strong>Title</strong> is required.');
		controlsInErrorState[controlsInErrorState.length] = "cboAdditionalDriverTitle_error";
	}
	
	if (firstName.value == '')
	{
		addValidationItem('validationSummaryListAdditional', '<strong>First name</strong> is required.');
		controlsInErrorState[controlsInErrorState.length] = firstName.id + "_error";
	}
	
	if (surname.value == '')
	{
		addValidationItem('validationSummaryListAdditional', '<strong>Surname</strong> is required.');
		controlsInErrorState[controlsInErrorState.length] = surname.id + "_error";
	}
		
	if (dateOfBirthDay.value == '')
		controlsInErrorState[controlsInErrorState.length] = dateOfBirthDay.id + "_error";
	
	if (dateOfBirthMonth.value == '')
		controlsInErrorState[controlsInErrorState.length] = dateOfBirthMonth.id + "_error";
		
	if (dateOfBirthYear.value == '')
		controlsInErrorState[controlsInErrorState.length] = dateOfBirthYear.id + "_error";
	
	if (dateOfBirthDay.value == '' || dateOfBirthMonth.value == '' || dateOfBirthYear.value == '')
		addValidationItem('validationSummaryListAdditional', '<strong>Date of birth</strong> is required.');
	
	if (gender.selectedIndex == 0)
	{
		addValidationItem('validationSummaryListAdditional', '<strong>Gender</strong> is required.');
		controlsInErrorState[controlsInErrorState.length] = "cboAdditionalDriverGender_error";
	}
	
	if (maritalStatus.selectedIndex == 0)
	{
		addValidationItem('validationSummaryListAdditional', '<strong>Marital status</strong> is required.');
		controlsInErrorState[controlsInErrorState.length] = "cboAdditionalDriverMaritalStatus_error";
	}
	
	if (document.getElementById('rowUnion').style.display != 'none')
	{
		if (union)
		{
			if (union.selectedIndex < 0)
			{
				addValidationItem('validationSummaryListAdditional', '<strong>Union</strong> is required.');
				controlsInErrorState[controlsInErrorState.length] = "cboAdditionalDriverUnion_error";
			}
		}
	}
	
	if (fullTimeOccupation.value == '')
	{
		addValidationItem('validationSummaryListAdditional', '<strong>Main occupation</strong> is required.');
		controlsInErrorState[controlsInErrorState.length] = fullTimeOccupation.id + "_error";
	}
	
	if (partTimeOccupation_Yes.checked && partTimeOccupation.value == '')
	{
		addValidationItem('validationSummaryListAdditional', '<strong>Part-time occupation</strong> is required.');
		controlsInErrorState[controlsInErrorState.length] = partTimeOccupation.id + "_error";
	}
	
	if (ukResidencyYears.value == '')
	{
		addValidationItem('validationSummaryListAdditional', '<strong>UK residency</strong> is required.');
		controlsInErrorState[controlsInErrorState.length] = ukResidencyYears.id + "_error";
	}
	else
	{
		if (isNaN(parseInt(ukResidencyYears.value)))
		{
			addValidationItem('validationSummaryListAdditional', '<strong>UK residency</strong> appears to be incorrect.');
			controlsInErrorState[controlsInErrorState.length] = ukResidencyYears.id + "_error";
		}
	}
	
	if (ukResidencyMonths.value == '')
	{
		addValidationItem('validationSummaryListAdditional', '<strong>UK residency</strong> is required.');
		controlsInErrorState[controlsInErrorState.length] = ukResidencyMonths.id + "_error";
	}
	else
	{
		if (isNaN(parseInt(ukResidencyMonths.value)))
		{
			addValidationItem('validationSummaryListAdditional', '<strong>UK residency</strong> appears to be incorrect.');
			controlsInErrorState[controlsInErrorState.length] = ukResidencyMonths.id + "_error";
		}
	}
	
	
	if (licenceType.selectedIndex == 0)
	{
		addValidationItem('validationSummaryListAdditional', '<strong>Licence type</strong> is required.');
		controlsInErrorState[controlsInErrorState.length] = "cboAdditionalDriverLicenceType_error";	
	}
	
	if (licenceHeldDurationYears.value == '')
	{
		addValidationItem('validationSummaryListAdditional', '<strong>Length of time licence held</strong> is required.');
		controlsInErrorState[controlsInErrorState.length] = licenceHeldDurationYears.id + "_error";
	}
	else
	{
		if (isNaN(parseInt(licenceHeldDurationYears.value)))
		{
			addValidationItem('validationSummaryListAdditional', '<strong>Length of time licence held</strong> appears to be incorrect.');
			controlsInErrorState[controlsInErrorState.length] = licenceHeldDurationYears.id + "_error";
		}
	}
	
	if (licenceHeldDurationMonths.style.display != '' && licenceHeldDurationMonths.style.display != 'none')
	{
		if (licenceHeldDurationMonths.value == '')
		{
			addValidationItem('validationSummaryListAdditional', '<strong>Length of time licence held</strong> is required.');
			controlsInErrorState[controlsInErrorState.length] = licenceHeldDurationMonths.id + "_error";
		}
		else
		{
			if (isNaN(parseInt(licenceHeldDurationMonths.value)))
			{
				addValidationItem('validationSummaryListAdditional', '<strong>Length of time licence held</strong> appears to be incorrect.');
				controlsInErrorState[controlsInErrorState.length] = licenceHeldDurationMonths.id + "_error";
			}
		}
	}
	
	if (commutes_No.checked == false && commutes_Yes.checked == false)
	{
		addValidationItem('validationSummaryListAdditional', 'Please confirm whether <strong>this driver uses this vehicle to commute to work or a place of study.</strong>.');
		controlsInErrorState[controlsInErrorState.length] = commutes.id + "_error";
	}
		
	if (businessUse_No.checked == false && businessUse_Yes.checked == false)
	{
		addValidationItem('validationSummaryListAdditional', 'Please confirm whether <strong>this driver use this vehicle for business purposes.</strong>.');
		controlsInErrorState[controlsInErrorState.length] = businessUse.id + "_error";
	}

	if (relationshipToMainDriver.selectedIndex == 0)
	{
		addValidationItem('validationSummaryListAdditional', '<strong>Relationship to main driver</strong> is required.');
		controlsInErrorState[controlsInErrorState.length] = "cboRelationshipToMainDriver_error";
	}
	
	if (controlsInErrorState.length > 0)
	{
		try
		{
			showErrors(controlsInErrorState);
			rowError.style.display = 'block';
			validationSummaryList.style.display = 'block';
			
			// Call this to move pop up back into central view
			updatePopUp();
		}
		catch (e)
		{
		}
	}
	else
	{
		var driverCommutes;
		var driverHasBusinessUse;
		var driverLicenceHeldDurationMonths;

		if (isNaN(parseInt(licenceHeldDurationMonths.value)))
			driverLicenceHeldDurationMonths = 0;
		else
			driverLicenceHeldDurationMonths = licenceHeldDurationMonths.value;
		
		if (commutes_Yes.checked == true)
			driverCommutes = true;
		else
			driverCommutes = false;
		
		if (businessUse_Yes.checked == true)
			driverHasBusinessUse = true;
		else
			driverHasBusinessUse = false;
		
		var unionValue = union ? union.options[union.selectedIndex].value : '00';
		
		// Create the SOAP Envelope
		var requestMessage =
	
				"<GetDriverHtml xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
				
				"	<coverStartDateDay>" + coverStartDateDay.value + "</coverStartDateDay>" +
				
				"	<coverStartDateMonth>" + coverStartDateMonth.value + "</coverStartDateMonth>" +
				
				"	<coverStartDateYear>" + coverStartDateYear.value + "</coverStartDateYear>" +
				
				"	<title>" + title.value + "</title>" +
				
				"	<firstName>" + firstName.value + "</firstName>" +
				
				"	<surname>" + surname.value + "</surname>" +
				
				"	<dateOfBirthDay>" + dateOfBirthDay.value + "</dateOfBirthDay>" +
				
				"	<dateOfBirthMonth>" + dateOfBirthMonth.value + "</dateOfBirthMonth>" +
				
				"	<dateOfBirthYear>" + dateOfBirthYear.value + "</dateOfBirthYear>" +
				
				"	<gender>" + gender.options[gender.selectedIndex].value + "</gender>" +
				
				"	<maritalStatus>" + maritalStatus.options[maritalStatus.selectedIndex].value + "</maritalStatus>" +
										
				"	<union>" + unionValue + "</union>" +
				
				"	<fullTimeOccupation>" + fullTimeOccupation.value + "</fullTimeOccupation>" +
				
				"	<partTimeOccupation>" + partTimeOccupation.value + "</partTimeOccupation>" +
				
				"	<ukResidencyYears>" + ukResidencyYears.value + "</ukResidencyYears>" +
				
				"	<ukResidencyMonths>" + ukResidencyMonths.value + "</ukResidencyMonths>" +
				
				"	<licenceType>" + licenceType.value + "</licenceType>" +
				
				"	<licenceHeldDurationYears>" + licenceHeldDurationYears.value + "</licenceHeldDurationYears>" +
				
				"	<licenceHeldDurationMonths>" + driverLicenceHeldDurationMonths + "</licenceHeldDurationMonths>" +
		
				"	<commutes>" + driverCommutes + "</commutes>" +	
				
				"	<businessUse>" + driverHasBusinessUse + "</businessUse>" +		
					
				"	<relationshipToMainDriver>" + relationshipToMainDriver.options[relationshipToMainDriver.selectedIndex].value + "</relationshipToMainDriver>" +
				
				"	<isNewDriver>true</isNewDriver>" +
				
				"	<driverIndex>" + driverIndex.value + "</driverIndex>" +
				
				"</GetDriverHtml>";
		
		// Set up the post
		proxy.XmlHttp.onreadystatechange = function()
		{
			// Where readyState = 4 and status = 200
			if (proxy.ResponseReceived())
			{
				//Process the return message.
				var responseMessage = proxy.ResponseXml;	
				var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
				
				if (isValid == 'true')
				{
					// Clear previous drivers
					document.getElementById('pnlAdditionalDriver').innerHTML = '';
					
					var drivers = new Array();
					drivers = responseMessage.getElementsByTagName("GetDriverHtmlDetails");
					
					for (var x = 0; x < drivers.length; x++)
					{
						var driver = drivers[x];
						
						//Add the details.
						var newDriver = document.createElement('div');
						newDriver.setAttribute('id', driver.getElementsByTagName("AdditionalDriverID")[0].childNodes.item(0).data);
						newDriver.innerHTML = driver.getElementsByTagName("Html")[0].childNodes.item(0).data;
						
						// If new driver, add to the end
						document.getElementById('pnlAdditionalDriver').appendChild(newDriver);
					}
								
					driverCount.value = responseMessage.getElementsByTagName("AdditionalDriverCount")[0].childNodes.item(0).data;
					evaluateDriverCount('hdnDriverIndex', 'hdnDriverCount', 'optAnyOtherDrivers_0', 'optAnyOtherDrivers_1', 'pnlAdditionalDrivers', 'rowAdditionalDriversOption', 'rowAddAnotherDriver');
					hidePopUp('popUpAdditionalDriver');
					
					// Clear pop up
					clearDriverPopup();
				}
				else
				{
					if (responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0) != null)
					{
						try
						{
							document.getElementById(responseMessage.getElementsByTagName("ErrorMessageField")[0].childNodes.item(0).data).innerHTML = responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data;
							document.getElementById(responseMessage.getElementsByTagName("ErrorMessageRow")[0].childNodes.item(0).data).style.display = 'block';
						}
						catch (e)
						{
							errorHandler(e.message);
						}
					}
					
					if (responseMessage.getElementsByTagName("ErrorFields")[0].childNodes.item(0) != null)
					{
						var fieldsInError = new Array();
						fieldsInError = responseMessage.getElementsByTagName("ErrorFields")[0].childNodes.item(0).data.split(",");
						showErrors(fieldsInError);
						rowError.style.display = 'block';
					}
					else
					{
						// Reset any error message that could be shown by this call.
						document.getElementById('errAdditionalDriverDateOfBirth').style.display = 'none';
					}
				}
			}
		}
		
		proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/GetDriverHtml", requestMessage, true);
	}
}

//Remove an existing driver.
function removeAdditionalDriver(additionalDrivers, driverIndex, driverRowID, displayConfirmation)
{	
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	if (displayConfirmation)
	{
		//We're coming here from the code defined in the web service i.e. they've clicked remove driver.
		showPopUp('popUpConfirmRemoveDriver', 'middleCenter', 80, 400);
		document.getElementById('hdnDriverRowID').value = driverRowID;
		document.getElementById('hdnDriverIndex').value = driverIndex;
	}
	else
	{
		//We're coming here from the code defined in the 
		driverRowID = document.getElementById('hdnDriverRowID').value;
		driverIndex = document.getElementById('hdnDriverIndex').value;

		// Create the SOAP Envelope
		var requestMessage =
	
				"<RemoveDriver xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
				
				"	<driverIndex>" + driverIndex + "</driverIndex>" +
				
				"</RemoveDriver>";
		
		// Set up the post
		proxy.XmlHttp.onreadystatechange = function()
		{
			// Where readyState = 4 and status = 200
			if (proxy.ResponseReceived())
			{
				//Process the return message.
				var responseMessage = proxy.ResponseXml;	
				var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
				
				if (isValid == 'true')
				{
					// Clear previous drivers
					document.getElementById('pnlAdditionalDriver').innerHTML = '';
					
					var drivers = new Array();
					drivers = responseMessage.getElementsByTagName("GetDriverHtmlDetails");
					
					for (var x = 0; x < drivers.length; x++)
					{
						var driver = drivers[x];
						
						//Add the details.
						var newDriver = document.createElement('div');
						newDriver.setAttribute('id', driver.getElementsByTagName("AdditionalDriverID")[0].childNodes.item(0).data);
						newDriver.innerHTML = driver.getElementsByTagName("Html")[0].childNodes.item(0).data;
						
						// If new driver, add to the end
						document.getElementById('pnlAdditionalDriver').appendChild(newDriver);
					}
					
					document.getElementById('hdnDriverCount').value = responseMessage.getElementsByTagName("AdditionalDriverCount")[0].childNodes.item(0).data;
					evaluateDriverCount('hdnDriverIndex', 'hdnDriverCount', 'optAnyOtherDrivers_0', 'optAnyOtherDrivers_1', 'pnlAdditionalDrivers', 'rowAdditionalDriversOption', 'rowAddAnotherDriver');
					rowError.style.display = 'none';
				}
				else
				{
					errorHandler(responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data);
				}
			}
		}
		
		proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/RemoveDriver", requestMessage, true);
	}
}

//Remove bans and convictions from the quote.
function removeBansAndConvictionsFromQuote(hasBans, hasConvictions)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	hasBans = document.getElementById(hasBans);
	hasConvictions = document.getElementById(hasConvictions);
	
	// Create the SOAP Envelope
	var requestMessage =

			"<RemoveBansAndConvictions xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
	
			"</RemoveBansAndConvictions>";
			
	// Set up the post
	proxy.XmlHttp.onreadystatechange = function()
	{
		// Where readyState = 4 and status = 200
		if (proxy.ResponseReceived())
		{
			//Process the return message.
			var responseMessage = proxy.ResponseXml;	
			var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
			
			if (isValid == 'true')
			{
				hasBans.value = 0;
				hasConvictions.value = 0;
			}
			else
			{
				errorHandler(responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data);
			}
		}
	}
	
	proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/RemoveBansAndConvictions", requestMessage, true);
}

//Remove accidents from the quote.
function removeAccidentsFromQuote(hasAccidents)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	hasAccidents = document.getElementById(hasAccidents);

	// Create the SOAP Envelope
	var requestMessage =

			"<RemoveAccidents xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
	
			"</RemoveAccidents>";
			
	// Set up the post
	proxy.XmlHttp.onreadystatechange = function()
	{
		// Where readyState = 4 and status = 200
		if (proxy.ResponseReceived())
		{
			//Process the return message.
			var responseMessage = proxy.ResponseXml;	
			var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
			
			if (isValid == 'true')
			{
				hasAccidents.value = 0;
			}
			else
			{
				errorHandler(responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data);
			}
		}
	}
	
	proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/RemoveAccidents", requestMessage, true);
}

//Validate the purchase date.
function validatePurchaseDate(coverStartDateDays, coverStartDateMonths, coverStartDateYears, purchaseDateMonths, purchaseDateYears, rowError, errorMessage)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	coverStartDateDays = document.getElementById(coverStartDateDays).value;
	coverStartDateMonths = document.getElementById(coverStartDateMonths).value;
	coverStartDateYears = document.getElementById(coverStartDateYears).value;
	purchaseDateMonths = document.getElementById(purchaseDateMonths);
	purchaseDateYears = document.getElementById(purchaseDateYears);
	//Error fields.
	rowError = document.getElementById(rowError);
	errorMessage = document.getElementById(errorMessage);
	
	if (coverStartDateDays == '' || coverStartDateMonths == '' || coverStartDateYears == '')
	{
		errorMessage.innerHTML = "<strong>Cover start date</strong> must be completed before entering the 'Purchase date'."; 
		rowError.style.display = 'block';
	}
	else
	{
		if (purchaseDateMonths.value != '' && purchaseDateYears.value != '')
		{	
			// Create the SOAP Envelope
			var requestMessage =
		
					"<ValidatePurchaseDate xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
					
					"	<coverStartDateDays>" + coverStartDateDays + "</coverStartDateDays>" +
					
					"	<coverStartDateMonths>" + coverStartDateMonths + "</coverStartDateMonths>" +
					
					"	<coverStartDateYears>" + coverStartDateYears + "</coverStartDateYears>" +
					
					"	<purchaseDateMonths>" + purchaseDateMonths.value + "</purchaseDateMonths>" +
					
					"	<purchaseDateYears>" + purchaseDateYears.value + "</purchaseDateYears>" +
			
					"</ValidatePurchaseDate>";
					
			// Set up the post
			proxy.XmlHttp.onreadystatechange = function()
			{
				// Where readyState = 4 and status = 200
				if (proxy.ResponseReceived())
				{
					//Process the return message.
					var responseMessage = proxy.ResponseXml;	
					var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
					
					if (isValid == 'true')
					{
						rowError.style.display = 'none';
						//Do nothing.
					}
					else
					{
						errorMessage.innerHTML = responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data;
						rowError.style.display = 'block';
						purchaseDateMonths.value = '';
						purchaseDateYears.value = '';
						purchaseDateMonths.focus();
					}
				}
			}
			
			proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/ValidatePurchaseDate", requestMessage, true);
		}
	}
}

// Retrieve the vehicle decription from session
function getVehicleDescription(rowVehicle, vehicleDetails, editButton, yearOfMake)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	// Get elements
	rowVehicle = document.getElementById(rowVehicle);
	vehicleDetails = document.getElementById(vehicleDetails);
	editButton = document.getElementById(editButton);
	yearOfMake = document.getElementById(yearOfMake);
	
	// Create the SOAP Envelope
	var requestMessage =

			"<GetVehicleDescription xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
	
			"</GetVehicleDescription>";
			
	// Set up the post
	proxy.XmlHttp.onreadystatechange = function()
	{
		// Where readyState = 4 and status = 200
		if (proxy.ResponseReceived())
		{
			//Process the return message.
			var responseMessage = proxy.ResponseXml;	
			var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
			
			if (isValid == 'true')
			{
				vehicleDetails.innerHTML = responseMessage.getElementsByTagName("VehicleDetails")[0].childNodes.item(0).data + '<br/><br/>';
				vehicleDetails.className = 'common';
				clearAlert(yearOfMake);
				
				var abiCode = responseMessage.getElementsByTagName("ABICode")[0].childNodes.item(0).data;
				editButton.onclick = function(){displayEditVehicle(abiCode);return false;};
				editButton.style.display = 'inline';
				rowVehicle.style.display = 'block';
				
				// Reset validation
				resetVehicleValidation();
				
				// Hide reg no link
				document.getElementById('rowDontKnowRegNo').style.display = 'none';
				
				// Align fields
				document.getElementById('lblRegNo').style.paddingTop = '7px';
				document.getElementById('imgHelpRegNo').style.paddingTop = '7px';
			}
		}
	}
	
	proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/GetVehicleDescription", requestMessage, true);
}

//Get the vehicle details from the registration number.
function validateRegistrationNumber(regNo, rowVehicle, vehicleDetails, yearOfMake, editButton, progressAnimation, rowError, errorMessage, performLookup)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	rowVehicle = document.getElementById(rowVehicle);
	editButton = document.getElementById(editButton);
	regNo = document.getElementById(regNo);
	
	//Error fields.
	rowError = document.getElementById(rowError);
	errorMessage = document.getElementById(errorMessage);

	if (regNo.value.length > 0)
	{
		if (validateUKRegNumber(regNo.id, true)) 
		{
			if (performLookup)
			{
				vehicleDetails = document.getElementById(vehicleDetails);
				yearOfMake = document.getElementById(yearOfMake);
				progressAnimation = document.getElementById(progressAnimation);
				
				var timeoutID = beginAnimation(progressAnimation);
				
				// Create the SOAP Envelope
				var requestMessage =
			
						"<ValidateRegistrationNumber xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
						
						"	<regNo>" + regNo.value + "</regNo>" +
				
						"</ValidateRegistrationNumber>";
				
				// Set up the post
				proxy.XmlHttp.onreadystatechange = function()
				{
					// Where readyState = 4 and status = 200
					if (proxy.ResponseReceived())
					{
						//Process the return message.
						var responseMessage = proxy.ResponseXml;	
						var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
						
						if (isValid == 'true')
						{
							vehicleDetails.innerHTML = responseMessage.getElementsByTagName("VehicleDetails")[0].childNodes.item(0).data + '<br/><br/>';
							vehicleDetails.className = 'common';
							yearOfMake.value = responseMessage.getElementsByTagName("YearOfMake")[0].childNodes.item(0).data;
							clearAlert(yearOfMake);
							
							var abiCode = responseMessage.getElementsByTagName("ABICode")[0].childNodes.item(0).data;
							editButton.onclick = function(){displayEditVehicle(abiCode);return false;};
							editButton.style.display = 'inline';
							rowVehicle.style.display = 'block';
							
							// Reset validation
							resetVehicleValidation();
							
							// Hide reg no link
							document.getElementById('rowDontKnowRegNo').style.display = 'none';
							
							// Align fields
							document.getElementById('lblRegNo').style.paddingTop = '7px';
							document.getElementById('imgHelpRegNo').style.paddingTop = '7px';
						}
						else
						{
							errorMessage.innerHTML = responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data;
							rowError.style.display = 'block';
							rowVehicle.style.display = 'none';
							editButton.style.display = 'none';
							
							// Show reg no link
							document.getElementById('rowDontKnowRegNo').style.display = 'block';
							
							// Align fields
							document.getElementById('lblRegNo').style.paddingTop = '0';
							document.getElementById('imgHelpRegNo').style.paddingTop = '0';
						}
						progressAnimation.style.display = 'none';
						clearTimeout(timeoutID);
					}
				}
				
				proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/ValidateRegistrationNumber", requestMessage, true);
			}
			else
				rowError.style.display = 'none';
		}
		else
		{
			rowVehicle.style.display = 'none';
			editButton.style.display = 'none';
			errorMessage.innerHTML = '<strong>Registration number</strong> does not appear to be a valid format.';
			rowError.style.display = 'block';
			
			// Show reg no link
			document.getElementById('rowDontKnowRegNo').style.display = 'block';
			
			// Align fields
			document.getElementById('lblRegNo').style.paddingTop = '0';
			document.getElementById('imgHelpRegNo').style.paddingTop = '0';
		}
	}
	else
	{
		rowVehicle.style.display = 'none';
		editButton.style.display = 'none';
		rowError.style.display = 'none';
		
		// Show reg no link
		document.getElementById('rowDontKnowRegNo').style.display = 'block';
		
		// Align fields
		document.getElementById('lblRegNo').style.paddingTop = '0';
		document.getElementById('imgHelpRegNo').style.paddingTop = '0';
	}
}

//Get the gender from the title.
function getGenderFromTitle(title, genderList)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	// Create the SOAP Envelope
	var requestMessage =

			"<GetGenderFromTitle xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
			
			"	<title>" + title + "</title>" +
	
			"</GetGenderFromTitle>";
			
	// Set up the post
	proxy.XmlHttp.onreadystatechange = function()
	{
		// Where readyState = 4 and status = 200
		if (proxy.ResponseReceived())
		{
			//Process the return message.
			var responseMessage = proxy.ResponseXml;	
			genderList = document.getElementById(genderList);
			var gender;
			//Browser compatible.
			gender = responseMessage.getElementsByTagName("GetGenderFromTitleResult")[0].childNodes.item(0).data;
			
			if (gender == "NOMATCH")
			{	
				genderList.selectedIndex = 0;
			}
			else
			{
				for(index = 0; index < genderList.length; index++)
				{
					if (genderList[index].value == gender)
						genderList.selectedIndex = index;
				}
				clearAlert(genderList);
				clearAlert('cboAdditionalDriverGender'); //Frig because the error doesn't inherit the name from it's parent.
			}
		}
	}
	
	proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/GetGenderFromTitle", requestMessage, true);
}

//Get the occupation group from occupation code.
function getOccupationGroup(occupationCode) 
{
    var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);

    // Create the SOAP Envelope
    var requestMessage =

			"<GetOccupationGroup xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +

			"	<occupationCode>" + occupationCode + "</occupationCode>" +

			"</GetOccupationGroup>";

    // Set up the post
    proxy.XmlHttp.onreadystatechange = function() {
        // Where readyState = 4 and status = 200
        if (proxy.ResponseReceived()) {
            //Process the return message.
            var responseMessage = proxy.ResponseXml;
            var occGroup;
            //Browser compatible.
            occGroup = responseMessage.getElementsByTagName("GetOccupationGroupResult")[0].childNodes.item(0).data;
            if (occGroup == "NOMATCH") {
                // keep where do you study hidden
                toggleWhereStudying('off', 'slidePanelWhereStudyingText', 'slideContentWhereStudyingText');
            }
            else if (occGroup == STUDENT_OCCUPATION_GROUP) {
                //awful hard coded bodgery
                //student occupation group selected therefore open "where studying" question
                toggleWhereStudying('on', 'slidePanelWhereStudyingText', 'slideContentWhereStudyingText');
                //check for open university student
                if (occupationCode == OPEN_UNIVERSITY_OCCUPATION_CODE) {
                    //set the whereStudying controls to the open university
                    document.getElementById('cboWhereStudying').value = OPEN_UNIVERSITY_ESTABLISHMENT_CODE;
                    document.getElementById('lstWhereStudying').value = OPEN_UNIVERSITY_ESTABLISHMENT_CODE;
                    document.getElementById('txtWhereStudying').value = document.getElementById('cboWhereStudying')[document.getElementById('cboWhereStudying').selectedIndex].text;
                    checkSearchBoxSlide(document.getElementById('txtWhereStudying'), 'slidePanelWhereStudying', 'slideContentWhereStudying');
                    filterList(document.getElementById('txtWhereStudying'), 'cboWhereStudying', 'lstWhereStudying', false, 400, false, false);
                }
            }
        }
    }
    proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/GetOccupationGroup", requestMessage, true);
}


// Check YOM is valid and populate vechicle description dropdown if it's good
function validateVechicleDetailYearOfMake()
{
	yearOfMake = document.getElementById('popUpVehicleDetails_txtYearOfMake');
	
	// if it's got 4 chars it's valid
	if ( yearOfMake.value.length == 4 || yearOfMake.value.length == 0 )		
		// Do populate
		populateVehicleDescriptionDropdown('');
}

function showLoadingListItem(dropDown)
{
	dropDown.length = 0;
	dropDown.options[0] = new Option('Loading list...', 'Loading list...', false, false);	
}

//******************************************************************************************
// Vehicle Search Functions
//******************************************************************************************
function txtRegNo_OnBlur(txt)
{
	clearAlert(txt); 
	styleSwap(txt, 'off'); 
	processFindVehicleClick();
}

function hlDontKnowRegNo_OnClick()
{
	// Reset validation
	resetVehicleValidation();
	
	// Set the reg number to nothing
	document.getElementById('txtRegNo').value = '';
	
	// Will need to display the VGRG list, populate first dropdown and display popup
	populateVehicleMakeDropDown(true);
}

function processFindVehicleClick()
{		
	if (document.getElementById('txtRegNo').value == '' && document.getElementById('rowVehicle').style.display == 'block')
		// If we have a vehicle just exit the function
		return;
		
	// If we have no reg no and no vehicle selected
	if (document.getElementById('txtRegNo').value == '' && (document.getElementById('rowVehicle').style.display == 'none' || document.getElementById('rowVehicle').style.display == ''))
	{
		// Reset validation
		resetVehicleValidation();
	
		// Will need to display the VGRG list, populate first dropdown and display popup
		populateVehicleMakeDropDown(true);
		return
	}

	// Validate the registration number if we've got this far
	validateRegistrationNumber('txtRegNo', 'rowVehicle', 'lblConfirmVehicle', 'txtYearOfMake', 'btnEditVehicleDetails', 'imgVehicleProgress', 'errVehicle', 'lblErrorVehicle', true); 
}

// Persists the ABI Code in session via the web service
function persistABICode(ABICode)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	var requestMessage =
	
			"<PersistABICode xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
			
			"	<ABICode>" + ABICode + "</ABICode>" +
			
			"</PersistABICode>";
	
	proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/PersistABICode", requestMessage, true);
}

function resetVehicleValidation()
{
	// Hide field error
	clearAlert(document.getElementById('txtRegNo'));
	
	// Hide error row
	document.getElementById('errVehicle').style.display = 'none';
}

// Populate the cboVehicleMake dropdown on the popUpVehicleDetails popup
function populateVehicleMakeDropDown(showVehicleDetail)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	// Only pop if it hasn't already been populated.
	if ( document.getElementById('popUpVehicleDetails_cboVehicleMake').length == 0 )
	{
		var requestMessage =
		
				"<GetVehicleMakeList xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
				
				"</GetVehicleMakeList>";		
		
		// Set up the post
		proxy.XmlHttp.onreadystatechange = function()
		{
			// Where readyState = 4 and status = 200, status 200 means OK
			if (proxy.ResponseReceived())
			{
				//Process the return message.
				var responseMessage = proxy.ResponseXml;
				var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;

				// Check we have a valid response
				if (isValid == 'true')
				{						
					// call generic vehicle ddl populate method
					populateVehicleDropdownFromList(responseMessage.getElementsByTagName('VehicleMakeList')[0], 
													'popUpVehicleDetails_cboVehicleMake');
					
					// Show pop up if required
					if (showVehicleDetail)
						showPopUp('popUpVehicleDetails', 'middleCenter', 205, 650);
				}
				else
				{
					// Display error msg from web service
					errorHandler(responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data);
				}
			}
		}
		
		proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/GetVehicleMakeList", requestMessage, true);
	}
	else
	{
		document.getElementById('popUpVehicleDetails_cboVehicleMake').selectedIndex = 0;
		
		// Show pop up if required
		if (showVehicleDetail)
			showPopUp('popUpVehicleDetails', 'middleCenter', 205, 650);
	}
	
	// Clear down / disable the other boxes
	document.getElementById('popUpVehicleDetails_cboVehicleModel').length = 0;
	document.getElementById('popUpVehicleDetails_cboVehicleModel').setAttribute("disabled", "disabled");
	document.getElementById('popUpVehicleDetails_cboVehicleDescription').length = 0;	
	document.getElementById('popUpVehicleDetails_cboVehicleDescription').setAttribute("disabled", "disabled");
}

// Populate the cboVehicleModel dropdown on the popUpVehicleDetails popup
function populateVehicleModelDropdown()
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	if (document.getElementById('popUpVehicleDetails_cboVehicleMake').value != '')
	{
		var requestMessage =

				"<GetVehicleModelList xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
				
				"	<Make>" + document.getElementById('popUpVehicleDetails_cboVehicleMake').value + "</Make>" +
				
				"</GetVehicleModelList>";
		
		// Set up the post
		proxy.XmlHttp.onreadystatechange = function()
		{
			// Where readyState = 4 and status = 200, status 200 means OK
			if (proxy.ResponseReceived())
			{
				//Process the return message.
				var responseMessage = proxy.ResponseXml;
				var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
				
				// Check we have a valid response
				if (isValid == 'true')
				{	
					// Reset drop downs
					document.getElementById('popUpVehicleDetails_cboVehicleModel').removeAttribute("disabled");
					document.getElementById('popUpVehicleDetails_cboVehicleDescription').length = 0;
					document.getElementById('popUpVehicleDetails_cboVehicleDescription').setAttribute("disabled", "disabled");
					
					// call generic vehicle ddl populate method
					populateVehicleDropdownFromList(responseMessage.getElementsByTagName('VehicleModelList')[0], 
													'popUpVehicleDetails_cboVehicleModel');			
				}
				else
				{
					// Display error msg from web service
					errorHandler(responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data);
				}
			}
		}
		
		proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/GetVehicleModelList", requestMessage, true);
	}
	else
	{
		// Disable model & description if Please select... selected
		document.getElementById('popUpVehicleDetails_cboVehicleModel').length = 0;
		document.getElementById('popUpVehicleDetails_cboVehicleModel').setAttribute("disabled", "disabled");
		document.getElementById('popUpVehicleDetails_cboVehicleDescription').length = 0;
		document.getElementById('popUpVehicleDetails_cboVehicleDescription').setAttribute("disabled", "disabled");
	}
}

// Populate the cboVehicleDescription dropdown on the popUpVehicleDetails popup
function populateVehicleDescriptionDropdown(selectedVehValue)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	if (document.getElementById('popUpVehicleDetails_cboVehicleModel').value != '')
	{
		var requestMessage =

				"<GetVehicleDescriptionList xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
				
				"	<Make>" + document.getElementById('popUpVehicleDetails_cboVehicleMake').value + "</Make>" +
				
				"	<Model>" + document.getElementById('popUpVehicleDetails_cboVehicleModel').value + "</Model>" +
				
				"	<YearOfMake>" + document.getElementById('popUpVehicleDetails_txtYearOfMake').value + "</YearOfMake>" +
				
				"</GetVehicleDescriptionList>";
		
		// display a 'loading list...' caption if the load takes longer than 150 milisecs
		vehDetails = document.getElementById('popUpVehicleDetails_cboVehicleDescription');
		loadListTimeout = setTimeout("showLoadingListItem(vehDetails)",150);
		
		// Set up the post
		proxy.XmlHttp.onreadystatechange = function()
		{
			// Where readyState = 4 and status = 200, status 200 means OK
			if (proxy.ResponseReceived())
			{
				// clear the time out
				clearTimeout(loadListTimeout);
				
				//Process the return message.
				var responseMessage = proxy.ResponseXml;
				var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
				
				// Check we have a valid response
				if (isValid == 'true')
				{	

					if (responseMessage.getElementsByTagName('VehicleDescriptionList')[0].childNodes.length > 1)
					{
						document.getElementById('popUpVehicleDetails_cboVehicleDescription').removeAttribute("disabled");
						
						// call generic vehicle ddl populate method
						populateVehicleDropdownFromList(responseMessage.getElementsByTagName('VehicleDescriptionList')[0], 
													'popUpVehicleDetails_cboVehicleDescription');
					
						if (selectedVehValue != '')
							document.getElementById('popUpVehicleDetails_cboVehicleDescription').value = selectedVehValue;
						
						// Hide error message
						document.getElementById('lblErrorVehicleDetails').style.display = 'none';
					}
					else
					{
						// We have no vehicles so display message + clear drop down
						document.getElementById('popUpVehicleDetails_cboVehicleDescription').length = 0;
						document.getElementById('popUpVehicleDetails_cboVehicleDescription').setAttribute("disabled", "disabled");
						document.getElementById('errVehicleDetailsPopUp').style.display = 'none';
						document.getElementById('lblErrorVehicleDetails').style.display = 'block';
					}
				}
				else
				{
					// Display error msg from web service
					errorHandler(responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data);
				}
			}
		}
		
		proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/GetVehicleDescriptionList", requestMessage, true);
	}
	else
	{
		// Disable description if Please select... selected
		document.getElementById('popUpVehicleDetails_cboVehicleDescription').length = 0;
		document.getElementById('popUpVehicleDetails_cboVehicleDescription').setAttribute("disabled", "disabled");
	}
}

function populateAllVehicleDropdowns(abiCode)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	var requestMessage =
	
			"<GetAllVehicleListsFromABI xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
			
			"	<ABICode>" + abiCode + "</ABICode>" +
			
			"</GetAllVehicleListsFromABI>";
	
	// call generic veh populate method	
	var progressAnimation = document.getElementById('imgVehicleProgress');
	var timeoutID = beginAnimation(progressAnimation);
	
	// Set up the post
	proxy.XmlHttp.onreadystatechange = function()
	{
		// Where readyState = 4 and status = 200, status 200 means OK
		if (proxy.ResponseReceived())
		{
			//Process the return message.
			var responseMessage = proxy.ResponseXml;
			var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
			
			// Check we have a valid response
			if (isValid == 'true')
			{	
				// call generic vehicle ddl populate method
				populateVehicleDropdownFromList(responseMessage.getElementsByTagName('VehicleMakeList')[0], 
												'popUpVehicleDetails_cboVehicleMake');
												
				populateVehicleDropdownFromList(responseMessage.getElementsByTagName('VehicleModelList')[0], 
												'popUpVehicleDetails_cboVehicleModel');																
				
				populateVehicleDropdownFromList(responseMessage.getElementsByTagName('VehicleDescriptionList')[0], 
												'popUpVehicleDetails_cboVehicleDescription');
				
				showPopUp('popUpVehicleDetails', 'middleCenter', 205, 650);
				progressAnimation.style.display = 'none';
				clearTimeout(timeoutID);
				
				// Hide error message
				document.getElementById('lblErrorVehicleDetails').style.display = 'none';
			}
			else
			{
				// Display error msg from web service
				errorHandler(responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data);
			}
		}
	}
	
	proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/GetAllVehicleListsFromABI", requestMessage, true);
	
	// Re-enable all drop down lists
	document.getElementById('popUpVehicleDetails_cboVehicleMake').removeAttribute("disabled");
	document.getElementById('popUpVehicleDetails_cboVehicleModel').removeAttribute("disabled");
	document.getElementById('popUpVehicleDetails_cboVehicleDescription').removeAttribute("disabled");
}

function populateVehicleDropdownFromList(vehList, cboTargetDropDown)
{
	// Defualt the selected index to 0 (nothing selcted)
	var selectedIndex = 0;
	
	// Get the dropdown we are going to populate from the document
	cboTargetDropDown = document.getElementById(cboTargetDropDown);
	
	// Ensure the drop down is empty
	cboTargetDropDown.length = 0;
	
	// add dummy empty entry so as not to get a flicker from the real text as it loads
	cboTargetDropDown.options[0] = new Option('Please select...', '', false, false);	

	// Loop through each item in the list
	for(var index = 0; index < vehList.childNodes.length; index++)
	{
		try
		{
			// Get the vechicle list item and write each value to variable
			var vehListItem = vehList.childNodes.item(index);
			var listItemCode = vehListItem.getElementsByTagName("Code")[0].childNodes.item(0).data;
			var listItemText = vehListItem.getElementsByTagName("Text")[0].childNodes.item(0).data;
			var listItemSelected = vehListItem.getElementsByTagName("Selected")[0].childNodes.item(0).data;
			
			// Add entry to dropdown
			cboTargetDropDown.options[cboTargetDropDown.length] = new Option(listItemText, listItemCode, false, false);
			
			// if item is marked as selected, set list index
			if (listItemSelected == 'true')
				selectedIndex = parseInt(index + 1);

		}
		catch(e)
		{}
	}
		
	// Set selected list index (either -1 or >=0 if "selected" value has been set)
	cboTargetDropDown.selectedIndex = selectedIndex;
}

function displayEditVehicle(abiCode)
{
	// if no ABI code is passed into this function we can't edit, so just display from scratch (should never happen)
	if ( abiCode == '' )
	{
		populateVehicleMakeDropDown(false);
	}
	else
	{
		// Make sure the YOM on this pages matches the YOM on the edit screen
		yearOfMake = document.getElementById('txtYearOfMake');
		popupYearOfMake = document.getElementById('popUpVehicleDetails_txtYearOfMake');
		
		// get the ABI code from the selected vehicle desctiption
		var cboVehDesc = document.getElementById('popUpVehicleDetails_cboVehicleDescription');
		var selectedVehValue = '';
		var selectedABICode = '';
		
		if ( cboVehDesc.selectedIndex > 0 )
		{
			selectedABICode = cboVehDesc.options[cboVehDesc.selectedIndex].text;
			selectedVehValue = cboVehDesc.options[cboVehDesc.selectedIndex].value;
		}
		
		if ( yearOfMake.value.length == 4 )
		{
			popupYearOfMake.value = yearOfMake.value;
			populateVehicleDescriptionDropdown(selectedVehValue);
		}
		else
			popupYearOfMake.value = '';
		
		if (abiCode != selectedVehValue)
		{
			// ABI code is different to whats on page, so reload from ABI code.
			populateAllVehicleDropdowns(abiCode);
		}
		else
			showPopUp('popUpVehicleDetails', 'middleCenter', 205, 650);
	}
}

function validateVehicleDetailsPopUp(cboVehicleDescription, lblVehicleDetails, txtVehicleDetailYearOfMake, txtYearOfMake, editButton, rowVehicle)
{
	// Get controls
	var cboVehicleMake = document.getElementById('popUpVehicleDetails_cboVehicleMake');
	var cboVehicleModel = document.getElementById('popUpVehicleDetails_cboVehicleModel');
	cboVehicleDescription = document.getElementById(cboVehicleDescription);
	
	// Error controls.
	var rowError = document.getElementById('errVehicleDetailsPopUp');
	var validationSummaryList = document.getElementById('validationSummaryListVehicle');
	var noVehicleErrorRow = document.getElementById('lblErrorVehicleDetails');
	
	rowError.style.display = 'none';
	validationSummaryList.innerHTML = '';
	validationSummaryList.style.display = 'none';
	noVehicleErrorRow.style.display = 'none';
	
	// Reset all the alerts first.
	var allFields = ['cboVehicleMake', 'cboVehicleModel', 'cboVehicleDescription'];
	resetAlerts(allFields);
	
	// if we have something in the vechicle description, then we are valid.
	if ( cboVehicleDescription.selectedIndex > 0 )
	{	
		var selectedOption = cboVehicleDescription.options[cboVehicleDescription.selectedIndex];
		lblVehicleDetails = document.getElementById(lblVehicleDetails);
		
		// Split vehicle description on to two lines
		var carDescription = new String();
		var modelDescription = new String(); 
		var arrModelDesc = new Array();
		
		modelDescription = selectedOption.text;
		arrModelDesc = modelDescription.split(',');
		
		carDescription = cboVehicleMake.options[cboVehicleMake.selectedIndex].text + ' ';
		
		for (var x = 0; x < arrModelDesc.length; x++)
		{
			carDescription = carDescription + arrModelDesc[x] + ', ';
			
			if (x == 2)
				carDescription = carDescription + '<br />';
		}
	
		// Remove trailing comma + add breaks
		carDescription = carDescription.substring(0, (carDescription.length - 2))  + '<br /><br />';
		
		// write vehicle description to main page
		lblVehicleDetails.innerHTML = carDescription;
		lblVehicleDetails.className = 'common';
		
		// also update the YOM field on the main page with ours, but only if a valid yom wan entred
		txtVehicleDetailYearOfMake = document.getElementById(txtVehicleDetailYearOfMake);
		txtYearOfMake = document.getElementById(txtYearOfMake);
		
		if (txtVehicleDetailYearOfMake.value.length == 4)
		{
			txtYearOfMake.value = txtVehicleDetailYearOfMake.value;
			clearAlert(yearOfMake);
		}
		else
		{
			// Extract earliest year of make from description
			var yearDesc = arrModelDesc[arrModelDesc.length - 1].toString().replace(/\s/, '');
			yearDesc = yearDesc.substring(0, 4);
			
			// Check we have a valid year value
			if (isNaN(yearDesc) != true)
				txtYearOfMake.value = yearDesc;
		}
		
		editButton = document.getElementById(editButton);
		rowVehicle = document.getElementById(rowVehicle);
		
		// set function to call and value to pass to function (ABI code) for the edit button onclick event
		editButton.onclick = function(){displayEditVehicle(selectedOption.value); return false;}
		
		//display edit button
		editButton.style.display = 'inline';
		rowVehicle.style.display = 'block';
		
		// Hide reg no link
		document.getElementById('rowDontKnowRegNo').style.display = 'none';
		
		// Align fields
		document.getElementById('lblRegNo').style.paddingTop = '7px';
		document.getElementById('imgHelpRegNo').style.paddingTop = '7px';
		
		// what do you think this does?
		hidePopUp('popUpVehicleDetails');
		
		// Store the AbiCode in session state
		persistABICode(selectedOption.value);
	}
	else
	{
		var controlsInErrorState = new Array();
		
		if (cboVehicleMake.selectedIndex <= 0)
		{
			addValidationItem('validationSummaryListVehicle', '<strong>Make</strong> is required.');
			controlsInErrorState[controlsInErrorState.length] = "cboVehicleMake_error";
		}
		
		if (cboVehicleModel.selectedIndex <= 0)
		{
			addValidationItem('validationSummaryListVehicle', '<strong>Model</strong> is required.');
			controlsInErrorState[controlsInErrorState.length] = "cboVehicleModel_error";
		}
		
		if (cboVehicleDescription.selectedIndex <= 0)
		{
			addValidationItem('validationSummaryListVehicle', '<strong>Vehicle description</strong> is required.');
			controlsInErrorState[controlsInErrorState.length] = "cboVehicleDescription_error";
		}
		
		if (controlsInErrorState.length > 0)
		{
			try
			{
				showErrors(controlsInErrorState);
				rowError.style.display = 'block';
				validationSummaryList.style.display = 'block';
				
				// Call this to move pop up back into central view
				updatePopUp();
			}
			catch (e)
			{
			}
		}
		
		return false;
	}
}

//Validate the licence held duration entries.
function validateLicenceHeldDuration(dateOfBirthDays, dateOfBirthMonths, dateOfBirthYears, licenceHeldDurationMonths, licenceHeldDurationYears, labelLicenceHeldDurationMonths, nextField, rowError, errorMessage)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	dateOfBirthDays = document.getElementById(dateOfBirthDays).value;
	dateOfBirthMonths = document.getElementById(dateOfBirthMonths).value;
	dateOfBirthYears = document.getElementById(dateOfBirthYears).value;
	licenceHeldDurationMonths = document.getElementById(licenceHeldDurationMonths);
	licenceHeldDurationYears = document.getElementById(licenceHeldDurationYears);
	labelLicenceHeldDurationMonths = document.getElementById(labelLicenceHeldDurationMonths);
	nextField = document.getElementById(nextField);
	//Error fields.
	rowError = document.getElementById(rowError);
	errorMessage = document.getElementById(errorMessage);
	
	// Only validate if we have a value
	if (licenceHeldDurationYears.value != '')
	{
		if (dateOfBirthDays == '' || dateOfBirthMonths == '' || dateOfBirthYears == '')
		{
			errorMessage.innerHTML = "<strong>Date of birth</strong> must be completed before specifying how long you've held your current licence."; 
			rowError.style.display = 'block';
			licenceHeldDurationMonths.value = '';
			licenceHeldDurationYears.value = '';
			
			// If called from additional driver pop up, need to update pop up location
			if (popUpShowing)
				updatePopUp();
		}
		else
		{
			var continueCall = true;
			if((window.event.srcElement.id == licenceHeldDurationMonths.id) && (licenceHeldDurationMonths.style.display == '' || licenceHeldDurationMonths.style.display == 'none'))
				continueCall = false;
		
			if (continueCall)
			{	
				// Create the SOAP Envelope
				var requestMessage =
			
						"<ValidateLicenceHeldDuration xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
						
						"	<dateOfBirthDays>" + dateOfBirthDays + "</dateOfBirthDays>" +
						
						"	<dateOfBirthMonths>" + dateOfBirthMonths + "</dateOfBirthMonths>" +
						
						"	<dateOfBirthYears>" + dateOfBirthYears + "</dateOfBirthYears>" +
						
						"	<licenceHeldDurationMonths>" + licenceHeldDurationMonths.value + "</licenceHeldDurationMonths>" +
						
						"	<licenceHeldDurationYears>" + licenceHeldDurationYears.value + "</licenceHeldDurationYears>" +
				
						"</ValidateLicenceHeldDuration>";
						
				

				// Set up the post
				proxy.XmlHttp.onreadystatechange = function()
				{
					// Where readyState = 4 and status = 200
					if (proxy.ResponseReceived())
					{
						//Process the return message.
						var responseMessage = proxy.ResponseXml;	
						var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
						
						if (isValid == 'true')
						{
							rowError.style.display = 'none';
							if (parseInt(licenceHeldDurationYears.value) <= 2)
							{
								licenceHeldDurationMonths.style.display = 'inline';
								if (labelLicenceHeldDurationMonths.style.display == '' || labelLicenceHeldDurationMonths.style.display == 'none')
								{
									licenceHeldDurationMonths.value = '';
									licenceHeldDurationMonths.focus();
								}
								labelLicenceHeldDurationMonths.style.display = 'inline';
							}
							else
							{
								if (labelLicenceHeldDurationMonths.style.display == 'inline')
									nextField.focus();
								licenceHeldDurationMonths.style.display = 'none';
								labelLicenceHeldDurationMonths.style.display = 'none';
							}
						}
						else
						{
							errorMessage.innerHTML = responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data;
							rowError.style.display = 'block';
							licenceHeldDurationYears.value = '';
							licenceHeldDurationMonths.value = '';
							licenceHeldDurationMonths.style.display = 'none';
							labelLicenceHeldDurationMonths.style.display = 'none';
							licenceHeldDurationYears.focus();
							
							// If called from additional driver pop up, need to update pop up location
							if (popUpShowing)
								updatePopUp();
						}
					}
				}
				
				proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/ValidateLicenceHeldDuration", requestMessage, true);
			}
		}
	}
}

//Validate the UK residency entries.
function validateUKResidency(checkbox, dateOfBirthDays, dateOfBirthMonths, dateOfBirthYears, ukResidencyMonths, ukResidencyYears, populate, rowError, errorMessage)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);
	
	dateOfBirthDays = document.getElementById(dateOfBirthDays).value;
	dateOfBirthMonths = document.getElementById(dateOfBirthMonths).value;
	dateOfBirthYears = document.getElementById(dateOfBirthYears).value;
	ukResidencyMonths = document.getElementById(ukResidencyMonths);
	ukResidencyYears = document.getElementById(ukResidencyYears);
	//Error fields.
	rowError = document.getElementById(rowError);
	errorMessage = document.getElementById(errorMessage);
	
	if ((dateOfBirthDays == '' || dateOfBirthMonths == '' || dateOfBirthYears == '') && populate)
	{
		errorMessage.innerHTML = "<strong>Date of birth</strong> must be completed before clicking this check box."; 
		rowError.style.display = 'block';
		checkbox.checked = false;
	}
	else
	{
		// Create the SOAP Envelope
		var requestMessage =
	
				"<ValidateUKResidency xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
				
				"	<dateOfBirthDays>" + dateOfBirthDays + "</dateOfBirthDays>" +
				
				"	<dateOfBirthMonths>" + dateOfBirthMonths + "</dateOfBirthMonths>" +
				
				"	<dateOfBirthYears>" + dateOfBirthYears + "</dateOfBirthYears>" +
				
				"	<ukResidencyMonths>" + ukResidencyMonths.value + "</ukResidencyMonths>" +
				
				"	<ukResidencyYears>" + ukResidencyYears.value + "</ukResidencyYears>" +
		
				"</ValidateUKResidency>";
				
		

		// Set up the post
		proxy.XmlHttp.onreadystatechange = function()
		{
			// Where readyState = 4 and status = 200
			if (proxy.ResponseReceived())
			{
				//Process the return message.
				var responseMessage = proxy.ResponseXml;	
				var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;
				
				if (isValid == 'true')
				{
					rowError.style.display = 'none';
					if (!populate)
					{
						checkbox.checked = false;
					}
					else
					{
						ukResidencyMonths.value = responseMessage.getElementsByTagName("UKResidencyMonths")[0].childNodes.item(0).data;
						ukResidencyYears.value = responseMessage.getElementsByTagName("UKResidencyYears")[0].childNodes.item(0).data;
						clearAlert(ukResidencyMonths);
						clearAlert(ukResidencyYears);
					}
				}
				else
				{
					errorMessage.innerHTML = responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data;
					rowError.style.display = 'block';
					checkbox.checked = false;
					ukResidencyMonths.value = '';
					ukResidencyYears.value = '';
					ukResidencyYears.focus();
				}
			}
		}
		
		proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/ValidateUKResidency", requestMessage, true);
	}
}

//Validate the postcode.
function validatePostcode(houseNumberOrName, postcode, rowAddress, showRowAddress, editRowAddress, editMessage1, editMessage2, addressMessage1, addressMessage2, addressMessage3, progressAnimation, rowError, errorMessage, buttonRaisedEvent, showAnimation)
{
	var proxy = new WebServiceProxy(PAGE_MESSAGE_SERVICE);

	houseNumberOrName = document.getElementById(houseNumberOrName).value;
	postcode = document.getElementById(postcode).value;
	rowAddress = document.getElementById(rowAddress);
	showRowAddress = document.getElementById(showRowAddress);
	editRowAddress = document.getElementById(editRowAddress);
	editMessage1 = document.getElementById(editMessage1);
	editMessage2 = document.getElementById(editMessage2);
	progressAnimation = document.getElementById(progressAnimation);
	
	//Error fields.
	rowError = document.getElementById(rowError);
	errorMessage = document.getElementById(errorMessage);
	
	var isValid = true;
	
	showRowAddress.style.display = 'block';
	editRowAddress.style.display = 'none';
	
	if (houseNumberOrName == '' && postcode == '')
	{
		isValid = false;
		
		if (buttonRaisedEvent)
		{
			rowAddress.style.display = 'none';
			errorMessage.innerHTML = "Please ensure you have completed the 'House name or number' and 'Postcode' fields before clicking 'Find Address'."; 
			rowError.style.display = 'block';
		}
	}
	else if (houseNumberOrName == '')
	{
		isValid = false;
		
		if (buttonRaisedEvent)
		{
			rowAddress.style.display = 'none';
			rowError.style.display = 'block';	
			
			try
			{
				// Don't know why this would ever be null but under certain circumstances it is
				errorMessage.innerHTML = "Please ensure you have completed the 'House name or number' field before clicking 'Find Address'."; 
			}
			catch (e)
			{
				// Recreate the error message holder
				rowError.innerHTML = "<span id='lblErrorPostcode'>Please ensure you have completed the 'House name or number' field before clicking 'Find Address'.</span>"; 
			}
		}
	}
	else if (postcode == '')
	{
		isValid = false;
		
		if (buttonRaisedEvent)
		{
			rowAddress.style.display = 'none';
			errorMessage.innerHTML = "Please ensure you have completed the 'Postcode' field before clicking 'Find Address'."; 
			rowError.style.display = 'block';	
		}
	}
	
	if (isValid)
	{
		if (showAnimation)
			var timeoutID = beginAnimation(progressAnimation);
			
		//Create query string array;
		var queryString = new QueryString();
		queryString.Read();

		// Create the SOAP Envelope
		var requestMessage =
	
				"<ValidateAddress xmlns=\"http://www.quotes-endsleigh.co.uk/MotorQuote/\">" +
				
				"	<houseNumberOrName>" + houseNumberOrName + "</houseNumberOrName>" +
				
				"	<postcode>" + postcode + "</postcode>" +
				
				"	<companyID>" + queryString.GetValue("CompanyID") + "</companyID>" +
		
				"</ValidateAddress>";
				
		// Set up the post
		proxy.XmlHttp.onreadystatechange = function() {
			// Where readyState = 4 and status = 200
			if (proxy.ResponseReceived())
			{
				//Process the return message.
				var responseMessage = proxy.ResponseXml;	
				var isValid = responseMessage.getElementsByTagName("IsValid")[0].childNodes.item(0).data;

				if (isValid == 'true')
				{
					rowError.style.display = 'none';
					addressMessage1 = document.getElementById(addressMessage1);
					addressMessage2 = document.getElementById(addressMessage2);
					addressMessage3 = document.getElementById(addressMessage3);
					addressMessage3.innerHTML = '';
					
					var address = responseMessage.getElementsByTagName("Address")[0];
					
					if (address.getElementsByTagName("AddressLine1")[0].childNodes.item(0).data != '') {
						if (editMessage1.value != '' & (editMessage1.value != address.getElementsByTagName("AddressLine1")[0].childNodes.item(0).data)) {
							addressMessage1.innerHTML = editMessage1.value;
						} else {
							addressMessage1.innerHTML = address.getElementsByTagName("AddressLine1")[0].childNodes.item(0).data;
						}
					}
					
					if (address.getElementsByTagName("AddressLine2")[0].childNodes.item(0) != null) {
						if (editMessage2.value != '' & (editMessage2.value != address.getElementsByTagName("AddressLine2")[0].childNodes.item(0).data)) {
							addressMessage2.innerHTML = editMessage2.value;
						} else {
							addressMessage2.innerHTML = address.getElementsByTagName("AddressLine2")[0].childNodes.item(0).data;
						}
					} else {
						addressMessage2.innerHTML = editMessage2.value;
					}
					
						
					if (address.getElementsByTagName("AddressLine3")[0].childNodes.item(0) != null) {
						addressMessage3.innerHTML += address.getElementsByTagName("AddressLine3")[0].childNodes.item(0).data + "<br/>";;
					}
					
					if (address.getElementsByTagName("AddressLine4")[0].childNodes.item(0) != null) {
						addressMessage3.innerHTML += address.getElementsByTagName("AddressLine4")[0].childNodes.item(0).data + "<br/>";;
					}
					
					if (address.getElementsByTagName("TownOrCity")[0].childNodes.item(0) != null)
					{
						if (addressMessage3.innerHTML.indexOf(address.getElementsByTagName("TownOrCity")[0].childNodes.item(0).data) == -1) {
							addressMessage3.innerHTML += address.getElementsByTagName("TownOrCity")[0].childNodes.item(0).data + "<br/>";;
						}
					}
					
					if (address.getElementsByTagName("County")[0].childNodes.item(0) != null) {
						addressMessage3.innerHTML += address.getElementsByTagName("County")[0].childNodes.item(0).data + "<br/>";;
					}
					
					if (address.getElementsByTagName("PostCode")[0].childNodes.item(0) != null) {
						addressMessage3.innerHTML += address.getElementsByTagName("PostCode")[0].childNodes.item(0).data + "<br/><br/>";;
					}
									
					rowAddress.style.display = 'block';
					rowAddress.className = 'common';
				}
				else
				{
					errorMessage.innerHTML = responseMessage.getElementsByTagName("ErrorMessage")[0].childNodes.item(0).data;
					rowAddress.style.display = 'none';
					rowError.style.display = 'block';
				}

				progressAnimation.style.display = 'none';
				
				if (showAnimation)
					clearTimeout(timeoutID);
			}
		}
		
		proxy.SendMessage("Quote.asmx", "http://www.quotes-endsleigh.co.uk/MotorQuote/ValidateAddress", requestMessage, true);
	}
}

//******************************************************************************************
// Occupation Search Functions
//******************************************************************************************

// Constant for occupation search
var SEARCH_BOX_SPEECH_BUBBLE = "occSpeechBubble";
var SEARCH_BOX_SPEECH_BUBBLE_TEXT = "occSpeechBubbleText";

// Variables used to hold previously started searches.
var previousSearch = '';
var previousText = '';

// Variables to keep track of where the speech bubbles are
var _textBox = null;
var _bubbleElement = null;
var _arrowElement = null;
var _inPopUp = null;

// Variables to hold messages
var _messageItemSelected = '';
var _messageStartTyping = '';
var _messageNoMatches = '';
var _messageOneMatch = '';
var _messageMoreThanOneMatch = '';

// Variable to hold no matches item entry
var _itemNoMatchesFoundText = '';

function Education_OnFocus(textBox, filteredList)
{
    var inPopUp = false;
    if (filteredList.toString().indexOf('popUp') != -1)
        inPopUp = true;

    var speechBubble = document.getElementById(SEARCH_BOX_SPEECH_BUBBLE_TEXT);
    filteredList = document.getElementById(filteredList);

    _messageItemSelected = 'A university/college has been successfully selected from the list, overwrite or delete the university/college to see the list again.';
    _messageStartTyping = 'Start typing the name of your university/college to search our list for the nearest match.';
    _messageNoMatches = "Try shortening your search phrase or click 'Uni not listed?'.";
    _messageOneMatch = "Please select your uni/college from the list, or click 'Uni not listed?' if yours is not there.";
    _messageMoreThanOneMatch = "Please select your uni/college from the list, or click 'Uni not listed?' if yours is not there.";
    _itemNoMatchesFoundText = 'No matching universities/colleges found';    

    if (filteredList.selectedIndex != -1)
    {
        speechBubble.innerHTML = _messageItemSelected;
        displaySearchBoxHelp(textBox, SEARCH_BOX_SPEECH_BUBBLE, null, inPopUp);
    }
    else if (textBox.value.length < 3)
    {
        speechBubble.innerHTML = _messageStartTyping;
        displaySearchBoxHelp(textBox, SEARCH_BOX_SPEECH_BUBBLE, null, inPopUp);
    }
    else if (filteredList.options[0].text == _itemNoMatchesFoundText)
    {
        speechBubble.innerHTML = "<div style='margin-bottom: 5px;' class='title'>0 matches found <br /></div>  " + _messageNoMatches;
        displaySearchBoxHelp(textBox, SEARCH_BOX_SPEECH_BUBBLE, "occNoMatchesFoundArrow", inPopUp);
    }
    else if (filteredList.options.length == 1)
    {
        speechBubble.innerHTML = "<div style='margin-bottom: 5px;' class='title'>1 match found <br /></div>  " + _messageOneMatch;
        displaySearchBoxHelp(textBox, SEARCH_BOX_SPEECH_BUBBLE, "occMatchesFoundArrow", inPopUp);
    }
    else
    {
        speechBubble.innerHTML = "<div style='margin-bottom: 5px;' class='title'>" + filteredList.options.length + " matches found <br /></div>  " + _messageMoreThanOneMatch;
        displaySearchBoxHelp(textBox, SEARCH_BOX_SPEECH_BUBBLE, "occMatchesFoundArrow", inPopUp);
    }

    var uniNotListed = document.getElementById('hlUniNotListed');
    if (uniNotListed != null)
        uniNotListed.style.display = 'block';
}


function Occupation_OnFocus(textBox, filteredList)
{
	var inPopUp = false;
	if (filteredList.toString().indexOf('popUp') != -1)
		inPopUp = true;

    var speechBubble = document.getElementById(SEARCH_BOX_SPEECH_BUBBLE_TEXT);
    filteredList = document.getElementById(filteredList);

    _messageItemSelected = 'An occupation has been successfully selected from the list.';
    _messageStartTyping = 'Start typing your job title to search our list of occupations.';
    _messageNoMatches = "Try a less specific description and choose the job title which best describes what you do.";
    _messageOneMatch = "Please select the occupation which best describes what you do from the list.";
    _messageMoreThanOneMatch = "Please select the occupation which best describes what you do from the list.";
    _itemNoMatchesFoundText = 'No matching occupations found';

    if (filteredList.selectedIndex != -1)
    {
        speechBubble.innerHTML = _messageItemSelected;
        displaySearchBoxHelp(textBox, SEARCH_BOX_SPEECH_BUBBLE, null, inPopUp);
    }
    else if (textBox.value.length < 3)
    {
        speechBubble.innerHTML = _messageStartTyping;
        displaySearchBoxHelp(textBox, SEARCH_BOX_SPEECH_BUBBLE, null, inPopUp);
    }
    else if (filteredList.options[0].text == _itemNoMatchesFoundText)
    {
        speechBubble.innerHTML = "<div style='margin-bottom: 5px;' class='title'>0 matches found <br /></div>  " + _messageNoMatches;
        displaySearchBoxHelp(textBox, SEARCH_BOX_SPEECH_BUBBLE, "occNoMatchesFoundArrow", inPopUp);
    }
    else if (filteredList.options.length == 1)
    {
        speechBubble.innerHTML = "<div style='margin-bottom: 5px;' class='title'>1 match found <br /></div>  " + _messageOneMatch;
        displaySearchBoxHelp(textBox, SEARCH_BOX_SPEECH_BUBBLE, "occMatchesFoundArrow", inPopUp);
    }
    else
    {
        speechBubble.innerHTML = "<div style='margin-bottom: 5px;' class='title'>" + filteredList.options.length + " matches found <br /></div>  " + _messageMoreThanOneMatch;
        displaySearchBoxHelp(textBox, SEARCH_BOX_SPEECH_BUBBLE, "occMatchesFoundArrow", inPopUp);
    }
}

function Education_OnBlur()
{
    // Simply hide everything
    hideSearchBoxHelp();
}

function Occupation_OnBlur()
{
	// Simply hide everything
    hideSearchBoxHelp();
}

function SearchBoxList_OnFocus(filteredList, textBox, errorRow, mainDriver)
{
	if (filteredList.selectedIndex == -1 && filteredList.length == 1)
	{
		// Select 1st row on focus if nothing selected and only one item
		filteredList.selectedIndex = 0;
		
		// Populate the search box
		populateSearchBox(filteredList, textBox, errorRow, mainDriver);
	}
}

function hlUniNotListed_Click()
{
    // Need to perform an unlisted search
    var textBox = document.getElementById('txtWhereStudying');
    textBox.value = 'Unlisted';

    // Filter to get unlisted list
    filterList(textBox, 'cboWhereStudying', 'lstWhereStudying', false, 400, false, true);

    // Focus the textbox to display help messages
    textBox.focus();
}

function checkSearchBoxHelp()
{
	if (_textBox != null)
	    displaySearchBoxHelp(_textBox, _bubbleElement, _arrowElement, _inPopUp);
}

function hideSearchBoxHelp()
{
	// Hide all occupation help related images
	document.getElementById('occSpeechBubble').style.display = 'none';
	document.getElementById('occMatchesFoundArrow').style.display = 'none';
	document.getElementById('occNoMatchesFoundArrow').style.display = 'none';
	
	// Reset global variables
	_textBox = null;
	_bubbleElement = null;
	_arrowElement = null;
	_inPopUp = null;
}

function checkSearchBoxSlide(textBox, occSlidePanel, occSlideContent)
{
	occSlideContent = document.getElementById(occSlideContent);

	if (textBox.value.length >= 3 && occSlideContent.style.display != 'block')
		slideElement(occSlidePanel, occSlideContent.id, 75);
}

// Populates the occupation text box when an entry in the list is selected.
function populateSearchBox(filteredListBox, textBox, errorRow, mainDriver)
{
	var selectedOccupation = filteredListBox[filteredListBox.selectedIndex].text;
	
	if (selectedOccupation != null)
	{
	    if (selectedOccupation != _itemNoMatchesFoundText)
		{
			document.getElementById(textBox).value = selectedOccupation;
			
			if (mainDriver)
			{
				document.getElementById(errorRow).style.display = 'none';

				if (filteredListBox.id == 'lstFullTimeOccupation')		
				{
					if (selectedOccupation.indexOf('Student') != -1)
						document.getElementById('lblPostcodeWhereVehicleKept').innerHTML = 'Postcode of your term time address';
					else
					{
						document.getElementById('lblPostcodeWhereVehicleKept').innerHTML = 'Postcode where the vehicle is kept overnight';
						
						if (document.getElementById('txtPostcode').value != '' && document.getElementById('txtPostcodeWhereVehicleKept').value == '')
						    document.getElementById('chkPostcodeWhereVehicleKept').click();
					}

                    getOccupationGroup(filteredListBox[filteredListBox.selectedIndex].value);
				}
			}
		}
		else
			filteredListBox.selectedIndex = -1;
	}
}

// Sets the timeout for when the list filtering will begin,
function filterList(textEntered, originalList, filteredList, addAll, timeout, alwaysSelect, displayHelp)
{
	if (previousSearch != '')
		clearTimeout(previousSearch);

	if (alwaysSelect)
		setTimeout("performFilter(document.getElementById('" + textEntered.id + "'), '" + originalList + "', '" + filteredList + "', " + addAll + ", " + alwaysSelect + ", " + displayHelp + ")", timeout); 
	else if (timeout == 0 || textEntered.value.length < 3)
		performFilter(textEntered, originalList, filteredList, addAll, alwaysSelect, displayHelp);
	else
	{
		if (textEntered.value.length >= 3)
			if (textEntered.value != previousText)
				loadingList(filteredList);
		
		previousSearch = setTimeout("performFilter(document.getElementById('" + textEntered.id + "'), '" + originalList + "', '" + filteredList + "', " + addAll + ", " + alwaysSelect + ", " + displayHelp + ")", timeout); 
	}
	
	previousText = textEntered.value;
}

// Filters the list box.
function performFilter(textEntered, originalList, filteredList, addAll, alwaysSelect, displayHelp)
{	
	var inPopUp = false;
	if (filteredList.toString().indexOf('popUp') != -1)
		inPopUp = true;
	
	originalList = document.getElementById(originalList);
	filteredList = document.getElementById(filteredList);
	
	if (filteredList.options.length != originalList.options.length || textEntered.value.length > 2)
	{
		var filterList = true;
		if (filteredList.selectedIndex != -1)
		{
			if (textEntered.value == filteredList[filteredList.selectedIndex].text)
				filterList = false;
		}
		
		if (filterList)
		{
			for ( var i = (filteredList.options.length - 1); i > -1; i--)
			{
				filteredList.options[i] = null;
			}
		    
			if (textEntered.value.length > 2)
			{
				for ( var i=0; i < originalList.options.length; i++ )
				{
					if ((originalList.options[i].text.toUpperCase().indexOf(textEntered.value.toUpperCase()) != -1) || addAll)
					{       
						var y = document.createElement('option');
						y.value = originalList.options[i].value;
						y.text=originalList.options[i].text;
						
						addListItem(filteredList, y);
					}
				}
				
				//Now select the right item if there's only one in the list or the onload event has called the function.
				if (filteredList.options.length == 1 || alwaysSelect)
				{
					for (var x = (filteredList.options.length - 1); x > -1; x--)
					{
						if (filteredList.options[x].text.toUpperCase() == textEntered.value.toUpperCase())
						{
							filteredList.options[x].selected = true;
							textEntered.value = filteredList.options[x].text;
							previousText = textEntered.value;

							if (filteredList.id == 'lstFullTimeOccupation')
							{
							    getOccupationGroup(filteredList.options[x].value);
							}								
			            }					
		            }
				}
				
				// Set up speech bubble and images
				var speechBubble = document.getElementById(SEARCH_BOX_SPEECH_BUBBLE_TEXT);		

				if (filteredList.options.length == 0)
					speechBubble.innerHTML = "<div style='margin-bottom: 5px;' class='title'>0 matches found <br /></div>" + _messageNoMatches; 
				else if (filteredList.options.length == 1)
					speechBubble.innerHTML = "<div style='margin-bottom: 5px;' class='title'>1 match found <br /></div>  " + _messageOneMatch; 
				else
					speechBubble.innerHTML = "<div style='margin-bottom: 5px;' class='title'>" +filteredList.options.length + " matches found <br /></div>  " + _messageMoreThanOneMatch;
				
				if (filteredList.options.length != 0)
				{
					if (displayHelp)
					    displaySearchBoxHelp(textEntered, SEARCH_BOX_SPEECH_BUBBLE, "occMatchesFoundArrow", inPopUp);
				}
				else
				{
					// No occupations match the criteria so add a dummy record
					var noMatch = document.createElement('option');
					noMatch.value = '';
					noMatch.text = _itemNoMatchesFoundText;
					
					addListItem(filteredList, noMatch);
					
					if (displayHelp)
					    displaySearchBoxHelp(textEntered, SEARCH_BOX_SPEECH_BUBBLE, "occNoMatchesFoundArrow", inPopUp);
					
				}
			}
			else
			{
				for ( var i=0; i < originalList.options.length; i++ )
				{
					var y = document.createElement('option');
					y.text = originalList.options[i].text;
					y.value = originalList.options[i].value;
					
					addListItem(filteredList, y);
				}

				document.getElementById('occSpeechBubbleText').innerHTML = _messageStartTyping; 
				document.getElementById('occMatchesFoundArrow').style.display = 'none';
				document.getElementById('occNoMatchesFoundArrow').style.display = 'none';
			}
		}
	}
}

// Clears the items and indicates that the list is reloading.
function loadingList(filteredList)
{
	filteredList = document.getElementById(filteredList);
	filteredList.length = 0;
	
	var y = document.createElement('option');
	y.value = '';
	y.text = "Loading list...";
	
	addListItem(filteredList, y);
}

function showWindscreenBubble(value)
{	
	//Get Objects
	var occSpeechWindscreen = document.getElementById('occSpeechWindscreen');
	var rdoWindscreen = document.getElementById('cboCoverRequired');
	
	//Set Position for Bubble
	occSpeechWindscreen.style.zIndex = '1';
	occSpeechWindscreen.style.position = 'absolute';
	occSpeechWindscreen.style.display = 'block';
				
	var xPos = getAscendingLefts(rdoWindscreen);
	var yPos = getAscendingTops(rdoWindscreen);	
		
	var xPosAnimation = parseInt(xPos) - parseInt(occSpeechWindscreen.offsetWidth) + parseInt(rdoWindscreen.offsetWidth) + 170;
	var yPosAnimation = parseInt(yPos) - parseInt(occSpeechWindscreen.offsetHeight) + 60;
			
	occSpeechWindscreen.style.left = xPosAnimation + 'px';
	occSpeechWindscreen.style.top = yPosAnimation + 'px';
		
	if (value == false)
		//Hide Bubble
		occSpeechWindscreen.style.display = 'none';
}

function resetWindscreenRadioList(value)
{
	var rdoWindscreen = document.forms[0].elements['rdoWindscreen'];
	
	if (value == 'None')
	{
		rdoWindscreen[0].checked = false;
		rdoWindscreen[1].checked = false;
	}
	else if (value == 'Yes')
	{
		rdoWindscreen[0].checked = true;
		rdoWindscreen[1].checked = false;
	}
	else if (value == 'No')
	{
	}	
}


function toggleWhereStudying(status, slidePanel, slideContent) {

    if (status == "on"){
        //open the slide panel
        slideElement(slidePanel, slideContent, 50);
    }
    else {
        //close the panel and reset the controls
        cancelSlide(slidePanel, slideContent);

        document.getElementById('txtWhereStudying').value = '';

        //Sneaky way of performing an asynchronous call.
        setTimeout("filterList(document.getElementById('txtWhereStudying'), 'cboWhereStudying', 'lstWhereStudying', true, 400, false, false, true)", 1);
        document.getElementById('lstWhereStudying').selectedIndex = -1;
        var errorField = [document.getElementById('txtWhereStudying').id];
        resetAlerts(errorField);
    }
}

function whereStudySelected_Onload() {

    filterList(document.getElementById('txtWhereStudying'), 'cboWhereStudying', 'lstWhereStudying', false, 400, true, false);

    var lstWhereStudying = document.getElementById('lstWhereStudying')
    var txtWhereStudying = document.getElementById('txtWhereStudying')
    var slidePanelWhereStudyingText = document.getElementById('slidePanelWhereStudyingText')
    var slideContentWhereStudyingText = document.getElementById('slideContentWhereStudyingText')
    var slidePanelWhereStudying = document.getElementById('slidePanelWhereStudying')
    var slideContentWhereStudying = document.getElementById('slideContentWhereStudying')

    if (lstWhereStudying.selectedIndex != -1 || txtWhereStudying.value != '') {
        slidePanelWhereStudyingText.style.display = 'block';
        slideContentWhereStudyingText.style.display = 'block';
        slidePanelWhereStudying.style.display = 'block';
        slideContentWhereStudying.style.display = 'block';
    }

}


function coverSelected_Onload()
{
	var cboCoverRequired = document.getElementById('cboCoverRequired')
	var slidePanelCoverSelected = document.getElementById('slidePanelCoverSelected')
	var slideContentCoverSelected= document.getElementById('slideContentCoverSelected')

	if (cboCoverRequired.value == 'TPFT' || cboCoverRequired.value == 'TPO')
	{
		slidePanelCoverSelected.style.display = 'block';
		slideContentCoverSelected.style.display = 'block';
	}
}
function coverSelected(cboCoverRequired, slidePanel, slideContent)
{
	var	windscreenBubbleText = document.getElementById('windscreenBubbleText');
	
	if (cboCoverRequired.value == 'TPFT')
	{
		//Add here
		slideElement(slidePanel, slideContent, 50);
		showWindscreenBubble(true);
		resetWindscreenRadioList('None');
			
		//Set Text
		windscreenBubbleText.innerHTML = "<span class='title'>Protect your windscreen</span> and glass against damage which is not included under third party policies.";
	}
	else if (cboCoverRequired.value == 'TPO')
	{
		//Add here
		slideElement(slidePanel, slideContent, 50);
		showWindscreenBubble(true);
		resetWindscreenRadioList('None');
			
		//Set Text
		windscreenBubbleText.innerHTML = "<span class='title'>Protect your windscreen</span> and glass against damage which is not included under third party policies.";
	}
	else
	{	
		cancelSlide(slidePanel, slideContent);
		showWindscreenBubble(false);
		resetWindscreenRadioList('Yes');
	}
}

function displaySearchBoxHelp(textBox, bubbleElement, arrowElement, inPopUp)
{
	// Hide everything first
    hideSearchBoxHelp();
	
	// Position speech bubble element and display
	var xPos = getAscendingLefts(textBox);
	var yPos = getAscendingTops(textBox);
	
	bubbleElement = document.getElementById(bubbleElement);
	bubbleElement.style.zIndex = '9999';
	bubbleElement.style.position = 'absolute';
	bubbleElement.style.display = 'block';
	
	var xPosBubble = parseInt(xPos) + parseInt(textBox.offsetWidth);
	var yPosBubble = parseInt(yPos) - parseInt(bubbleElement.offsetHeight) + 20;
	
	// Need to slightly change if in a pop up?
	if (inPopUp)
	{
		xPosBubble = parseInt(xPosBubble) + 3;
		yPosBubble = parseInt(yPosBubble) + 2;
	}
	
	bubbleElement.style.left = xPosBubble + 'px';
	bubbleElement.style.top = yPosBubble + 'px';
	
	// If we have an arrow element display it
	if (arrowElement != null)
	{
		var xPosArrow = parseInt(xPos) + parseInt(textBox.offsetWidth);
		var yPosArrow = parseInt(yPos) - 4;
		
		// Need to slightly change if in a pop up?
		if (inPopUp)
		{
			xPosArrow = parseInt(xPosArrow) + 3;
			yPosArrow = parseInt(yPosArrow) + 2;
		}
	
		arrowElement = document.getElementById(arrowElement);
	
		arrowElement.style.left = xPosArrow + 'px';
		arrowElement.style.top = yPosArrow + 'px';
		arrowElement.style.zIndex = '9998';
		arrowElement.style.position = 'absolute';
		arrowElement.style.display = 'block';
	}
	
	// Set global variables for use in onscroll and onresize window events
	_textBox = textBox;
	_bubbleElement = bubbleElement.id;
	if (arrowElement != null)
		_arrowElement = arrowElement.id;
	_inPopUp = inPopUp;
}

//******************************************************************************************
// Query String Manipulation
//******************************************************************************************

//Query string "object".
function QueryString() {
	var data = [];
	this.Read = function()
	{
		var aPairs, aTmp;
		var queryString = new String(window.location.search);
		queryString = queryString.substr(1, queryString.length); //remove "?"
		aPairs = queryString.split("&");	

		try
		{		
			for (var i=0 ; i<aPairs.length; i++)
			{
				aTmp = aPairs[i].split("=");
				var item = aTmp[0];
				data[aTmp[0].toString().toUpperCase()] = aTmp[1].toString().toUpperCase();
			}
		}
		catch (e)
		{
		}
	}
	
	this.GetValue = function( key )
	{
		var retVal = data[key.toUpperCase()];
		if (retVal == undefined)
			retVal = '';
		return retVal;
	}
	this.SetValue = function( key, value )
	{
		if (value == null)
			delete data[key];
		else 
			data[key] = value;
	}
	this.ToString = function()
	{
		var queryString = new String(""); 
		
		for (var key in data)
		{	
			if (queryString != "")
				queryString += "&"
			if (data[key])
				queryString += key + "=" + data[key];		
		}
		if (queryString.length > 0)
			return "?" + queryString;
		else
			return queryString;
	}
	this.Clear = function()
	{
		delete data;
		data = [];
	}
}

//******************************************************************************************
// Attach function to the onload event to make sure all data is loaded when the page loads
//******************************************************************************************
addEvent(window, "load", onLoad);
addEvent(window, "resize", checkHelp);
addEvent(window, "resize", checkWindscreen);
addEvent(window, "resize", checkSearchBoxHelp);
addEvent(window, "scroll", checkSearchBoxHelp);
