
if(typeof(formName) == "undefined") {
	var formName = "frm";
}

if(typeof(QASAddressList) == "undefined") {
	var QASAddressList = "dAddressList";
}

var carDataXML;
var resetInputArray = new Array();

/***************** UTILITIES ******************/

/*
* Name:		lovService
* Description:	A JavaScript (AJAX) function to use the Java LOV service.
* 
* Parameters:	batch - a boolean to indicate whether this is a single call or a batch call ( false = single,true = batch)
* 				strParam_or_itemArray  - if used for a single call then this will be the lov ID e.g. TITLE (or equivalent numeric ID)
*									   - can also be used to supply the filter to the lov service e.g. TITLE&startFilter=1
*				      				   - if used for a batch call then this is the JavaScript Array reference
*			               				(example format of Array : lovArray = [['TITLE&startFilter=1',frm.title],['FUEL_TYPE',frm.fuel]]
*										 > Each element in the inner arrays refers to a parameter that would normally be passed in e.g. 1st item = strParam_or_itemArray                  
*				element_or_currentItem - 1. If used for a single call (Dropdown) then this will be the HTML Form Element reference
*									   - 2. If used for a single call (Radio/Checkbox Elements) then this will be the name required for the elements
*		    		       			   - NOT USED FOR A BATCH CALL
*				holdingDiv			   - Used for Radio / Checkbox usage. To identify where to write the HTML source
*				elementType			   - Used for Radio / Checkbox usage. To idenitfy whether "Radio" or "Checkbox" elements are required
*				firstSelected		   - (boolean) Used for Radio / Checkbox usage. To signify whether the first item should be default selected
*				onClickJS			   - Used for Radio / Checkbox usage. To add any JavaScript to the onClick method of the Radio/Checkbox elements
*									   
* Usage:	1. Single one-off
* 		   lovService(false,'<LOV ID>',<FORM ELEMENT REFERENCE>)
*			2. Startup / batch
*		   lovService(true,<JAVASCRIPT ARRAY NAME>)				   
*/
function lovService(batch,strParam_or_itemArray,element_or_currentItem,holdingDiv,elementType,firstSelected,onClickJS) {

	var LOVServiceUrl = "/SSDiffService/lovService.do";
	var urlParam;
	var formElement;
	var divName;
	var typeOfElement;
	var selectFirst;
	var onClickCode;
		
	if(batch && typeof(element_or_currentItem)=="undefined") {
		urlParam = strParam_or_itemArray[0][0];
		formElement = strParam_or_itemArray[0][1];
		divName = strParam_or_itemArray[0][2];
		typeOfElement = strParam_or_itemArray[0][3];
		selectFirst = strParam_or_itemArray[0][4];
		onClickCode = strParam_or_itemArray[0][5];
		element_or_currentItem = 0;	
	} else if(batch) {
		urlParam = strParam_or_itemArray[element_or_currentItem][0];
		formElement = strParam_or_itemArray[element_or_currentItem][1];
		divName = strParam_or_itemArray[element_or_currentItem][2];
		typeOfElement = strParam_or_itemArray[element_or_currentItem][3];
		selectFirst = strParam_or_itemArray[element_or_currentItem][4];
		onClickCode = strParam_or_itemArray[element_or_currentItem][5];
	} else {
		urlParam = strParam_or_itemArray;
		formElement = element_or_currentItem;
		divName = holdingDiv;
		typeOfElement = elementType;
		selectFirst = firstSelected;
		onClickCode = onClickJS;
	}
	
    $.get(LOVServiceUrl+'?codeType='+urlParam, function(xmldoc){
				if(typeof(formElement)!="string") {
					formElement.options.length = 0;
					formElement.options[0] = new Option("Please select ...","",false,false);
				}
				var itemCount = 0;
				var lovXML = $(xmldoc).find('LookupValue').each(function() {
					
					var description = $(this).find('Description').text();
					
					// Special exception - Exclude the UNKNOWN item from the list
					if(description.toUpperCase() == 'UNKNOWN') {
						return true;
					}
					if(description == 'INVALID') {
					 	return false;
					}
			
					var value = $(this).find('Value').text();
					var displayOrder = $(this).find('DisplayOrder').text();	

					if(typeof(formElement)=="string") {
						
						if(selectFirst && $itemCount == 0) {
							divName.innerHTML = divName.innerHTML + '<li><input type="' + typeOfElement + '" name="' + formElement + '" id="' + formElement + '" value="'+ value +'" onClick="' + onClickCode + '" checked>&nbsp;&nbsp;' + description + "</li>";
						} else {
							divName.innerHTML = divName.innerHTML + '<li><input type="' + typeOfElement + '" name="' + formElement + '" id="' + formElement + '" value="'+ value +'" onClick="' + onClickCode + '">&nbsp;&nbsp;' + description + "</li>";
						}

					} else {
						if(itemCount == 0) {
							if(formElement.options.length > 0 && formElement.options[0].value != '') {
								formElement.options.length = 0;
							}
						}
						formElement.options[formElement.length] = new Option(description,value,false,false);
					}
					itemCount++;
				});				
				
				
				if(typeof(formElement)=="string") {
					divName.innerHTML = "<ul>" +  divName.innerHTML + "</ul>";
				}
				
				if(batch) {
					element_or_currentItem++;
					if(element_or_currentItem < strParam_or_itemArray.length) {
						lovService(true,strParam_or_itemArray,element_or_currentItem, holdingDiv, elementType, firstSelected);
					}
				}
	});	
        	

			
		
	
 
 	
}

function makeModel(makeElement,modelElement,detailsDiv) {
	if(makeElement.value != '') {
		$(modelElement).empty();
		$(modelElement).append('<option value="">Loading models ...</option>');
		lovService(false,'213&startFilter='+makeElement.value,modelElement)
		$(modelElement).attr('disabled','disabled');

		if(typeof(detailsDiv)!="undefined") {
			$(detailsDiv).show();
		}
		
	} else {
		$(modelElement).removeAttr('disabled');
		$(modelElement).empty();
		if(typeof(detailsDiv)!="undefined") {
			$(detailsDiv).hide();
		}
	}
}

function updateMakeModel(makeElement,modelElement) {
	if($(makeElement).val() != '') {
		$(modelElement).empty();
		$(modelElement).append('<option value="">Loading models ...</option>');
		lovService(false,'213&startFilter='+$(makeElement).val(),$(modelElement).get(0))
		$(modelElement).removeAttr('disabled');
		
	} else {
		$(modelElement).attr('disabled','disabled');
		$(modelElement).empty();
	}
}

function datePast(theDay,theMonth,theYear) {
	var currentDate = new Date();
	
	if(theDay == '') {
		theDay = currentDate.getDate();
	}
	
	if(theMonth == '') {
		theMonth = currentDate.getMonth();
	} else {
		theMonth = (theMonth-1)
	}
	
	if(theYear == '') {
		theYear = currentDate.getFullYear();
	}
	
	var compareDate = new Date(theYear,theMonth,theDay,currentDate.getHours(),currentDate.getMinutes(),currentDate.getSeconds(),currentDate.getMilliseconds());
	
	return(compareDate.getTime() <= currentDate.getTime());
}

function dateFuture(theDay,theMonth,theYear) {
	var currentDate = new Date();
	
	
	if(theDay == '') {
		theDay = currentDate.getDate();
	}
	
	if(theMonth == '') {
		theMonth = currentDate.getMonth();
	} else {
		theMonth = (theMonth-1)
	}
	
	if(theYear == '') {
		theYear = currentDate.getFullYear();
	}
	
	
	var compareDate = new Date(theYear,theMonth,theDay,currentDate.getHours(),currentDate.getMinutes(),currentDate.getSeconds(),currentDate.getMilliseconds());

	return(compareDate.getTime() >= currentDate.getTime());
}

function getCurrentDate(returnYear,returnMonth,returnDay) {
	var currentDate = new Date();
	var currentMonth;
	var currentDay;
	
	if((currentDate.getMonth()+1) < 10) {
		currentMonth = "0" + (currentDate.getMonth()+1);
	} else {
		currentMonth = (currentDate.getMonth()+1);
	}
	
	if(currentDate.getDate() < 10) {
		currentDay= "0" + currentDate.getDate();
	} else {
		currentDay = currentDate.getDate();
	}
	
	if(returnYear && returnMonth  && returnDay ) {
		return currentDate.getFullYear() + "-" + currentMonth + "-" + currentDay;
	} else if(returnYear && returnMonth ) {
		return currentDate.getFullYear() + "-" + currentMonth;
	} else {
		return currentDate.getFullYear();
	}
}

function formatSSDIFDate(currentDate,isUTC) {
	var currentMonth;
	var currentDay;
	
	if(isUTC) {	
		if((currentDate.getUTCMonth()+1) < 10) {
			currentMonth = "0" + (currentDate.getUTCMonth()+1);
		} else {
			currentMonth = (currentDate.getUTCMonth()+1);
		}
		
		if(currentDate.getUTCDate() < 10) {
			currentDay= "0" + currentDate.getUTCDate();
		} else {
			currentDay = currentDate.getUTCDate();
		}
	
		return currentDate.getUTCFullYear() + "-" + currentMonth + "-" + currentDay;
	} else {
		if((currentDate.getMonth()+1) < 10) {
			currentMonth = "0" + (currentDate.getMonth()+1);
		} else {
			currentMonth = (currentDate.getMonth()+1);
		}
		
		if(currentDate.getDate() < 10) {
			currentDay= "0" + currentDate.getDate();
		} else {
			currentDay = currentDate.getDate();
		}
	
		return currentDate.getFullYear() + "-" + currentMonth + "-" + currentDay;
	}
	
}


function initDay(dayElement) {
	//$(dayElement).empty();
	for(x=1; x < 32; x++) {
		if(x < 10) {
			$(dayElement).append("<option value='0"+x+"'>"+x+"</option>");
		} else {
			$(dayElement).append("<option value='"+x+"'>"+x+"</option>");
		}		
	}
}

function initMonth(monthElement) {
	//$(monthElement).empty();
	for(x=1; x < 13; x++) {
		if(x < 10) {
			$(monthElement).append("<option value='0"+x+"'>"+x+"</option>");
		} else {
			$(monthElement).append("<option value='"+x+"'>"+x+"</option>");
		}		
	}
}

function initYear(yearElement,averageYear,minYear,maxYear) {
	var currentDate = new Date();
	var third = Math.round((maxYear-1)/3);
	$(yearElement).empty();
	if(maxYear >= 0) {		
		for(x=0+minYear; x < maxYear; x++) {
				if(averageYear && (x == third)) {
					$(yearElement).append("<option value='"+(currentDate.getFullYear()+x)+"'>"+(currentDate.getFullYear()+x)+"</option>");	
				} else {
					$(yearElement).append("<option value='"+(currentDate.getFullYear()+x)+"'>"+(currentDate.getFullYear()+x)+"</option>");	
				}
		}	
	} else {		
		for(x=0-minYear; x > maxYear; x--) {
				if(averageYear && (x == third)) {
					$(yearElement).append("<option value='"+(currentDate.getFullYear()+x)+"'>"+(currentDate.getFullYear()-x)+"</option>");	
				} else {
					$(yearElement).append("<option value='"+(currentDate.getFullYear()+x)+"'>"+(currentDate.getFullYear()-x)+"</option>");	
				}
		}
	}
	
	if(minYear < 0) {
		for(x = minYear; x > maxYear; x--) {
			$(yearElement).append("<option value='"+(currentDate.getFullYear()+x)+"'>"+(currentDate.getFullYear()+x)+"</option>");	
		}
	}
	
}
/*
	yearElement - e.g. #CurrentProduct\\/RegYear
	start - e.g. 30 to start 30 years in the future, -30 to start 30 years in the past
	length - how many years from the START (THIS SHOULD BE >= 0)
	isOrderAsc - true if you want it ascending (starts from START), false if you want it descending (starts from START + LENGTH)
*/
function initYearList(yearElement,start,length,isOrderAsc) {
	var currentDate = new Date();
	
	currentDate.setFullYear(currentDate.getFullYear()+start);	
	
	if(isOrderAsc) {
		for(x=0; x <= length; x++) {
			$(yearElement).append("<option value='"+(currentDate.getFullYear()+x)+"'>"+(currentDate.getFullYear()+x)+"</option>");	
		}	
	} else {
		for(x=length; 0 <= x; x--) {
			$(yearElement).append("<option value='"+(currentDate.getFullYear()+x)+"'>"+(currentDate.getFullYear()+x)+"</option>");	
		}	
	}
	
}


function initDateOfBirth(dayElement,monthElement,yearElement,minAge) {
	initDay(dayElement);
	initMonth(monthElement);
	var MIN_AGE = 18;
	var currentDate = new Date();
	initYearList(yearElement,-100,(100-MIN_AGE),false);
	
	
}

function dateValid(dayElement,monthElement,yearElement) {
	if(dayElement == '' || monthElement == '' || yearElement == '') {
		return false;
	}
	monthElement = parseInt(monthElement,10) -1;

	var testDate = new Date(yearElement,monthElement,dayElement)
	if( (parseInt(dayElement,10) != testDate.getDate()) || (parseInt(monthElement,10) != testDate.getMonth()) || (parseInt(yearElement,10) != testDate.getFullYear())) {
		return false
	}
	
	return true;
}


function forenameValidate(textStr) {

	var regExPattern=/^([a-zA-Z\s'-]+)$/
	
	if(textStr.match(regExPattern) == null) {
		return false;
	} 	
	return true;	
}

function surnameValidate(textStr) {

	var regExPattern=/^([a-zA-Z\s'-]+?){2}$/; // The +? is needed for Opera support. Beware or cross browser reg exp differences.
	
	if(textStr.match(regExPattern) == null) {
		return false;
	} 	
	return true;	
}

function telephoneValidate(telStr) {

	var regExPattern=/^([0-9]){10,13}$/
	
	telStr = removeAllSpaces(telStr);

	if(telStr == '') {
		return false;
	}
	
	if(telStr.substring(0,1) != '0') {
		return false;
	}

	if(telStr.match(regExPattern) == null) {
		return false;
	} 	
	
	return true;
}

function vehicleRegValidate(regStr) {
	var regExPattern=/^([a-zA-Z0-9]){2,7}$/
	
	regStr = removeAllSpaces(regStr);
	
	if(regStr == '') {
		return false;
	}
	
	if(regStr.match(regExPattern) == null) {
		return false;
	} 	
	
	return true;
}

function engineCCValidate(ccStr) {
	var regExPattern=/^([0-9]){1,4}$/
	
	ccStr = removeAllSpaces(ccStr);
	
	if(ccStr == '') {
		return false;
	}
	
	if(ccStr.substring(0,1) == '0') {
		return false;
	}
	
	if(ccStr.match(regExPattern) == null) {
		return false;
	} 	
	
	return true;
}

function cleanName(textStr) {
	 return textStr.substring(0,1).toUpperCase() + textStr.substring(1);
}


function titleOtherCheck(titleElement,otherTitleID) {

	if($(titleElement + ' option:selected').val() == 14) {
	 	$(otherTitleID).show();
	} else {
		$(otherTitleID).hide();
	}	
}

function businessRecreationVisibility()
{
	if(radioSelectedValue('ContactWithHonda/Questions_15/Responses/Response') == '1') {
		$('#' + formName + ' #useBusinessDiv').show();
		$('#' + formName + ' #businessLabel').show();
		$('#' + formName + ' #ContactWithHonda\\/Questions_16\\/Responses\\/Response').show();
		$('#' + formName + ' #ContactWithHonda\\/Questions_16\\/QuestionCode').removeAttr('disabled');
		$('#' + formName + ' #ContactWithHonda\\/Questions_16\\/Responses\\/Response').removeAttr('disabled');
		$('#' + formName + ' #useRecreationDiv').hide();
		$('#' + formName + ' #recreationLabel').hide();
		$('#' + formName + ' #Person\\/Occupation').hide();
		$('#' + formName + ' #Person\\/Occupation').attr('disabled','disabled');
	} else {
		$('#' + formName + ' #useBusinessDiv').hide();
		$('#' + formName + ' #businessLabel').hide();
		$('#' + formName + ' #ContactWithHonda\\/Questions_16\\/Responses/Response').hide();
		$('#' + formName + ' #ContactWithHonda\\/Questions_16\\/QuestionCode').attr('disabled','disabled');
		$('#' + formName + ' #ContactWithHonda\\/Questions_16\\/Responses/Response').attr('disabled','disabled');
		$('#' + formName + ' #useRecreationDiv').show();
		$('#' + formName + ' #recreationLabel').show();
		$('#' + formName + ' #Person\\/Occupation').show();
		$('#' + formName + ' #Person\\/Occupation').removeAttr('disabled');
	}
}

function currentlyOwn() {
	if(radioSelectedValue('ContactWithHonda/Questions_14/Responses/Response') == 'Y') {
		$('#' + formName + ' #ownATVDiv').show();
		$('#' + formName + ' #CurrentProduct\\/PowerEquipment\\/Brand').show();
		$('#' + formName + ' #CurrentProduct\\/PowerEquipment\\/Brand').removeAttr('disabled');
		$('#' + formName + ' #CurrentProduct\\/PowerEquipment\\/ATVData\\/Range').removeAttr('disabled');
		$('#' + formName + ' #CurrentProduct\\/PowerEquipment\\/ATVData\\/Model').removeAttr('disabled');
		$('#' + formName + ' #CurrentProduct\\/PowerEquipment\\/ATVData\\/EngineSizeCC').show();
		$('#' + formName + ' #CurrentProduct\\/PowerEquipment\\/ATVData\\/EngineSizeCC').removeAttr('disabled');
		$('#' + formName + ' #CurrentProduct\\/Division').removeAttr('disabled');
		$('#' + formName + ' #CurrentProduct\\/ProductSegment').removeAttr('disabled');
		$('#' + formName + ' #X_ownershipMonth').show();
		$('#' + formName + ' #X_ownershipMonth').removeAttr('disabled');
		$('#' + formName + ' #X_ownershipYear').show();
		$('#' + formName + ' #X_ownershipYear').removeAttr('disabled');
		$('#' + formName + ' #CurrentProduct\\/RelationshipStartDate').removeAttr('disabled');
		$('#' + formName + ' #ContactWithHonda\\/Questions_17\\/QuestionCode').removeAttr('disabled');
		
		$('#' + formName + ' #atvUseDiv').show();
				
		$('#' + formName + ' #ContactWithHonda\\/Questions_17\\/Responses\\/Response').each(function() {
			$(this).show();
			$(this).removeAttr('disabled');
		});
		
	} else {
		$('#' + formName + ' #ownATVDiv').hide();
		$('#' + formName + ' #CurrentProduct\\/PowerEquipment\\/Brand').hide();
		$('#' + formName + ' #CurrentProduct\\/PowerEquipment\\/Brand').attr('disabled','disabled');
		$('#' + formName + ' #CurrentProduct\\/PowerEquipment\\/ATVData\\/Range').attr('disabled','disabled');
		$('#' + formName + ' #CurrentProduct\\/PowerEquipment\\/ATVData\\/Model').attr('disabled','disabled');
		$('#' + formName + ' #CurrentProduct\\/PowerEquipment\\/ATVData\\/EngineSizeCC').hide();
		$('#' + formName + ' #CurrentProduct\\/Division').attr('disabled','disabled');
		$('#' + formName + ' #CurrentProduct\\/ProductSegment').attr('disabled','disabled');
		$('#' + formName + ' #X_ownershipMonth').hide();
		$('#' + formName + ' #X_ownershipMonth').attr('disabled','disabled');
		$('#' + formName + ' #X_ownershipYear').hide();
		$('#' + formName + ' #X_ownershipYear').attr('disabled','disabled');
		$('#' + formName + ' #CurrentProduct\\/RelationshipStartDate').attr('disabled','disabled');
		$('#' + formName + ' #ContactWithHonda\\/Questions_17\\/QuestionCode').attr('disabled','disabled');		
		$('#' + formName + ' #atvUseDiv').hide();		
		
		$('#' + formName + ' #ContactWithHonda\\/Questions_17\\/Responses\\/Response').each(function() {
			$(this).hide();
			$(this).attr('disabled','disabled');
		});
	}
}

function radioSelectedValue(elementName) {
	return $('#' + formName + ' input[name="' + elementName + '"]:checked').val();
}

function radioSelected(elementName) {
	return Boolean($('#' + formName + ' input[name="' + elementName + '"]:checked').val());
}

function selectSelected(elementName) {
	return Boolean($('#'+ elementName +' option:selected').val());
}

function disableRadio(buttonGroup) {
	if (buttonGroup) {
		for (var i = 0; i < buttonGroup.length; i++) {
        	buttonGroup[i].disabled = true;
    	}
	}
	return false;
}

function removeAllSpaces(original) {
	while(original.indexOf(' ') > -1) {	
		original = original.replace(' ','');
	}
	return original;
}

function removeAllWhitespace(original) {
	var regExPattern=/\s+/;
	
	while(original.match(regExPattern)) {	
		original = original.replace(regExPattern,'');
	}
	
	return original;
}





// QAS Scripts - End

function emailCheck (emailStr)
{
var emailPat=/^(.+)@(.+)$/
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]&{}~#"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null) {
    return false
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
		return false
	    }
    }
    return true
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
    return false
}

var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 ||
    domArr[domArr.length-1].length>4) {
   return false
}

if (len<2) {
   return false
}

return true;
}

/**
 * Appends the days of the week into a nominated select element identified by argument 'id'
 */
function appendDaysOfWeek(id) {
	var DOW = new Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
	for (i=0; i<DOW.length; i++) {
		$('#'+id).append('<option value="'+DOW[i]+'">'+DOW[i]+'</option>');
	}
}

/**
 * Appends the timeslots of a day into a nominated select selement identified by argument 'id'
 */
function appendTimeslots(id) {
	var TIME_SLOTS = new Array("9am - 11am", "11am - 1pm", "1pm - 3pm", "3pm - 5pm");
	for (i=0; i<TIME_SLOTS.length; i++) {
		$('#'+id).append('<option value="'+TIME_SLOTS[i]+'">'+TIME_SLOTS[i]+'</option>');	
	}
}

/*******************************************************************************************/
/************************** SSDIF - VALIDATION FUNCTIONS ***********************************/
/*******************************************************************************************/

		function SSDIF_Validate_Title() {
			if((($('#X_title' + ' option:selected').val() == 14) && (($('#X_titleOther').val() == '') || ($('#X_titleOther').val() == ' '))) || $('#X_title' + ' option:selected').val() == '') {
				alert("Please enter a valid title");
				return false;		
			} else {
				// Set the Person/Title field
				if($('#X_title' + ' option:selected').val() == 14) { $('#Person\\/Title').val($('#X_titleOther').val());
				} else { $('#Person\\/Title').val($('#X_title' + ' option:selected').val()); }
			}
			return true;
		}			
		
		function SSDIF_Validate_Forename_Surname() {
			if(!forenameValidate($('#Person\\/Name1').val())) {
				alert("Please enter a valid Firstname");
				return false;
			} else if(!surnameValidate($('#Person\\/Name3').val())) {
				alert("Please enter a valid Surname");
				return false;
			} else {
				// Clean up the Firstname & Surname
				if($('#Person\\/Name1').val().length == 1) {
					$('#Person\\/Name1').attr("name","Person/Initials");
					$('#Person\\/Name1').val($('#Person\\/Name1').val().toUpperCase());
				} else {
					$('#Person\\/Name1').attr("name","Person/Name1");
					$('#Person\\/Name1').val(cleanName($('#Person\\/Name1').val()));
				}
				
				$('#Person\\/Name3').val(cleanName($('#Person\\/Name3').val()));
			}
			return true;
		}
		
		function SSDIF_Validate_Address() {
			if($("#Address\\/Address1").val() == '' || $("#Address\\/Town").val() == '' || !isValidPostcode($("#X_postcode").val())) {
				alert("Please enter a complete address");
				return false;
			} else {				
				// Address - Postcode
				if($('#Address\\/Postcode1').val() == '') {
					$('#Address\\/Postcode1').val($('#X_postcode').val().toUpperCase().replace(' ','').substring(0,$('#X_postcode').val().replace(' ','').length-3));
				}
				
				if($('#Address\\/Postcode2').val() == '') {
					$('#Address\\/Postcode2').val($('#X_postcode').val().toUpperCase().replace(' ','').substring($('#X_postcode').val().replace(' ','').length-3));
				}
			}
			return true;
		}
		
		function SSDIF_Validate_Date_Of_Birth() {
			
			if($("#X_birthDay").val() != '' || $("#X_birthMonth").val() != '' || $("#X_birthYear").val() != '') {
			
				if(!dateValid($("#X_birthDay").val() ,$("#X_birthMonth").val(),$("#X_birthYear").val())) {
					alert("Please enter a valid date of birth");
					return false;
				} else {
					$("#Person\\/BirthDate").val($("#X_birthYear").val() + "-" + $("#X_birthMonth").val() + "-" + $("#X_birthDay").val());
				}
	
			}
			
			return true;
		}
		
		// This function refactored 29/01/2010 uidyw, to aid debug.
		function SSDIF_Validate_Planned_Purchase_Date(monthInput, yearInput) {
			var monthVal, yearVal;
			var dayVal = "01"; // DC guidelines state to add 01 (1st day of month) to the month and year to build a valid date. 
			if (typeof(monthInput) === "undefined" || typeof(yearInput) === "undefined") {
				monthVal = $('#X_replaceMonth').val();
				yearVal = $('#X_replaceYear').val();
			}
			else {
				monthVal = $(monthInput).val();
				yearVal = $(yearInput).val();
			}
			if(!dateFuture(dayVal,monthVal,yearVal) || monthVal === "" || yearVal === "") { // dateFuture allows empty strings. We can't.
				alert("Please enter a valid planned purchase date");
				return false;
			}
			$('#ContactWithHonda\\/ProspectInterest\\/PlannedPurchaseDate').val(yearVal + "-" + monthVal + "-" + dayVal);
			return true;
		}
		
		function SSDIF_Validate_CurrentCar() {
				/*
				Check for :
				a. Full Registration Number
				b. Make
				c. Model
				d. Registration Year
				e. Private / Company
				f. Ownership start date

			*/
			
			if(	$("#CurrentProduct\\/Registration").val() != '' ||	selectSelected("CurrentProduct\\/CarData\\/Brand") || selectSelected("CurrentProduct\\/CarData\\/ModelGroup") || radioSelected("CurrentProduct/RetailCorporate") || selectSelected("CurrentProduct\\/RegYear") || selectSelected("X_currentCarOwnershipStartMonth") || selectSelected("X_currentCarOwnershipStartYear")) {
				


				// Check for either Registration or Registration Year
				if($("#CurrentProduct\\/Registration").val() == '' && !selectSelected("CurrentProduct\\/RegYear")){
					alert("Please enter your Full Registration Number or Registration Year");
					return false;
				}

				// Check Registration
				if($("#CurrentProduct\\/Registration").val() != '') {
					if(!SSDIF_Validate_Current_Car_Registration()) return false;
				}
				
				// Make and Model
				if(!selectSelected("CurrentProduct\\/CarData\\/Brand") || !selectSelected("CurrentProduct\\/CarData\\/ModelGroup")) {
					alert("Please select your current car's make and model");
					return false;
				}
				
				// Ownership Start Date
				if(!selectSelected("X_currentCarOwnershipStartMonth") || !selectSelected("X_currentCarOwnershipStartYear")) {
					alert("Please enter a ownership start date");
					return false;
				}
				
				if(!SSDIF_Validate_Ownership_Start_Date("#X_currentCarOwnershipStartMonth","#X_currentCarOwnershipStartYear")) return false;
				


				// Check Registration Year (needs to happen after Ownership Start Date)
				if(selectSelected("CurrentProduct\\/RegYear")) {
					if(!SSDIF_Validate_Registration_Year()) return false;
				}
				
				// Validate Private / Corporate
				if(radioSelected('CurrentProduct/RetailCorporate')) {
				$('#CurrentProduct\\/Relationship').removeAttr('disabled');
				if(radioSelectedValue('CurrentProduct/RetailCorporate') == 'C') {
						$('#CurrentProduct\\/Relationship').val('U');
					} else {
						$('#CurrentProduct\\/Relationship').val('O');
					}
				}					
				
				disableEmptyOptionalQuestions("9");	

				//Division and Product Segment			
				$("#CurrentProduct\\/Division,#CurrentProduct\\/ProductSegment").removeAttr("disabled");			
			} else {
				$("#CurrentProduct\\/Division, #CurrentProduct\\/ProductSegment").attr("disabled","disabled");
			}
			
			return true;
			
		}

		/* HUB Functionality Not needed yet
		function SSDIF_Validate_CurrentCar() {
				
				//Check for :
				//a. Full Registration Number
				//b. Make
				//c. Model
				//d. Registration Year
				//e. Private / Company
				//f. Ownership start date
				//g. Replacement Date
			
			
			// Check to see if any of the form has been filled it. If one part has, it all needs to be.
			if ($("#CurrentProduct\\/Registration").val() != '' ||	selectSelected("CurrentProduct\\/CarData\\/Brand") || selectSelected("CurrentProduct\\/CarData\\/ModelGroup") 
				|| radioSelected("CurrentProduct/RetailCorporate") || selectSelected("CurrentProduct\\/RegYear") || selectSelected("X_currentCarOwnershipStartMonth") 
				|| selectSelected("X_currentCarOwnershipStartYear") || selectSelected("X_currentCarReplacementDateMonth") || selectSelected("X_currentCarReplacementDateYear") ) {
				// Check for either Registration or Registration Year
				if($("#CurrentProduct\\/Registration").val() == '' && !selectSelected("CurrentProduct\\/RegYear")){
					alert("Please enter your Full Registration Number or Registration Year");
					return false;
				}

				// Check Registration
				if($("#CurrentProduct\\/Registration").val() != '') {
					if(!SSDIF_Validate_Current_Car_Registration()) return false;
				}
				
				// Make and Model
				if(!selectSelected("CurrentProduct\\/CarData\\/Brand") || !selectSelected("CurrentProduct\\/CarData\\/ModelGroup")) {
					alert("Please select your current car's make and model");
					return false;
				}
				
				// Ownership Start Date
				if(!selectSelected("X_currentCarOwnershipStartMonth") || !selectSelected("X_currentCarOwnershipStartYear")) {
					alert("Please enter a ownership start date");
					return false;
				}
				
				if(!SSDIF_Validate_Ownership_Start_Date("#X_currentCarOwnershipStartMonth","#X_currentCarOwnershipStartYear")) return false;
				
				if (arrayTest(ssdifCampaignValues["ReplacementDate"]) && !SSDIF_Validate_Replacement_Date("#X_currentCarReplacementDateMonth", "#X_currentCarReplacementDateYear")) return false;
							
				// Check Registration Year (needs to happen after Ownership Start Date)
				if(selectSelected("CurrentProduct\\/RegYear")) {
					if(!SSDIF_Validate_Registration_Year()) return false;
				}
				
				// Validate Private / Corporate
				if(radioSelected('CurrentProduct/RetailCorporate')) {
				$('#CurrentProduct\\/Relationship').removeAttr('disabled');
				if(radioSelectedValue('CurrentProduct/RetailCorporate') == 'C') {
						$('#CurrentProduct\\/Relationship').val('U');
					} else {
						$('#CurrentProduct\\/Relationship').val('O');
					}
				}					
				
				disableEmptyOptionalQuestions("9");	

				//Division and Product Segment			
				$("#CurrentProduct\\/Division,#CurrentProduct\\/ProductSegment").removeAttr("disabled");			
			} else {
				$("#CurrentProduct\\/Division, #CurrentProduct\\/ProductSegment").attr("disabled","disabled");
			}
			
			return true;
			
		}
		*/
		function SSDIF_Validate_Current_Car_Registration() {
			
			var regString = $("#CurrentProduct\\/Registration").val().toUpperCase().replace(/\ /g,"");
			return SSDIF_Validate_Registration(regString);
		}
		
		function SSDIF_Validate_Registration_Year() {
			var regYear = parseInt($("#CurrentProduct\\/RegYear").val(),10);
			var ownershipYear = parseInt($("#X_currentCarOwnershipStartYear").val(),10);
			
			if(regYear > ownershipYear) {
				alert("Please select a valid registration year");
				return false;
			}
			return true;
			
		}
		
		function SSDIF_Validate_Ownership_Start_Date(monthInput,yearInput) {			
			if(dateFuture(1,$(monthInput).val(),$(yearInput).val())) {
				alert("Please enter a valid ownership start date");
				return false;
			}
			$('#CurrentProduct\\/RelationshipStartDate').val($(yearInput).val() + "-" + $(monthInput).val() + "-01");
			return true;
		}
		
		function SSDIF_Validate_Replacement_Date(monthInput, yearInput){
			if (!dateFuture(1, $(monthInput).val(), $(yearInput).val())) {
				alert("Please enter a valid replacement date");
				return false;
			}
			var date = $(yearInput).val() + "-" + $(monthInput).val() + "-01"
			$('#CurrentProduct\\/ReplacementDate').val(date);

			// if Planned Car is shown, then also populate this area and hide that field.			
			if (arrayTest(ssdifCampaignValues["PlannedCar1"]) || arrayTest(ssdifCampaignValues["PlannedCar2"])) {
				$('#ContactWithHonda\\/ProspectInterest\\/PlannedPurchaseDate').val(date);
				$("#DIV_PlannedPurchaseDate").addClass("defaultHide");
			}
			return true;
		}
		
		function SSDIF_Validate_Private_Corporate_Prospect(createHiddenInputs) {
			var displayAlert = false;
						
			if(createHiddenInputs) {
				if(radioSelected('ContactWithHonda/ProspectInterest/CorporatePrivateUser')) {
					$('#ContactWithHonda\\/ProspectInterest\\/Relationship').removeAttr('disabled');
					if(radioSelectedValue('ContactWithHonda/ProspectInterest/CorporatePrivateUser') == 'C') {
						$('#ContactWithHonda\\/ProspectInterest\\/Relationship').val('U');
					} else {
						$('#ContactWithHonda\\/ProspectInterest\\/Relationship').val('O');
					}
				} else {
					displayAlert = true;
				}
			} else if(!radioSelected('X_corpPrivUser')) {
				displayAlert = true;
			}			
			
			if(displayAlert) {
				alert("Please select either Privately owned or Company Car");
				return false;
			}			
			return true;
		}	
		
		function SSDIF_Validate_New_Used_Prospect() {
			if(!radioSelected('X_newUsed')) {
				alert("Please select either New or Used");
				return false;			
			}
			return true;
		}
				
		function SSDIF_Validate_Preferred_Method_Contact() {
			if($('#Entity\\/PrefContactMedium' + ' option:selected').val() == '') { alert("Please select a preferred method of contact"); return false; }
			if($('#Entity\\/PrefContactMedium' + ' option:selected').val() == 'T') { if(!validateTelephone()) { return false; }}
			if($('#Entity\\/PrefContactMedium' + ' option:selected').val() == 'E') { if(!validateEmail()) { return false; }}
			return true;
		}
		
		function SSDIF_Validate_Telephone_Number_Type() {
			if(radioSelected('TelephoneEmail/PrefTelephone')) { if(!validateTelephone()) { return false; }}
			return true;
		}
		
		function SSDIF_Validate_Mandatory_Telephone_Number_Type() {
			if(!radioSelected('TelephoneEmail/PrefTelephone')) { alert("Please select a preferred telephone number type");  return false; }
			return true;
		}
				
		function SSDIF_Validate_Telephone() {
			if($('#X_phonenumber').val() != '') { if(!validateTelephone()) { return false; }}
			return true;
		}
		
		function SSDIF_Validate_Registration(regString) {
			
			regString = regString.replace(/\ /g,""); // Remove whitespace
			var regExPattern=/^([a-zA-Z0-9]{2,7})$/; // This matches the data capture guidelines (max 7 chars alphanumeric)
			if(regString.match(regExPattern) === null) {
				alert("Please enter a valid registration");
				return false;
			}
			return true;
		}
		
		function SSDIF_Validate_SMS() {
			if($('#TelephoneEmail\\/SMSNo').val() != '') { 
				if(!telephoneValidate($('#TelephoneEmail\\/SMSNo').val())) { 
					alert("Please enter a valid SMS number");
					return false; 
				} else {
					$('#CommPrefs_2\\/PrefSuppType').val('Y');
					checkMarketedByHonda();
				}
			} else {
				$('#CommPrefs_2\\/PrefSuppType').val('N');
				checkMarketedByHonda();
			}			
			
			return true;
		}
		
		
			
		function SSDIF_Validate_Mandatory_Telephone() {
			if(!validateTelephone()) { 
				return false; 
			}
			return true;
		}
			
		function SSDIF_Validate_Email_Newsletters() {
			if($('input[name="SubjectPrefs_1/PrefSuppType"]:checked, input[name="SubjectPrefs_2/PrefSuppType"]:checked, input[name="SubjectPrefs_3/PrefSuppType"]:checked').length) {
				if(!validateEmail()) { return false; }			
			} 
			return true;
		}
		
		function SSDIF_Validate_Email_Implicit() {
			if($('#TelephoneEmail\\/HomeEmail').val() != '') { 
				if(!validateEmail()) { 
					return false; 
				} else {
					$('#CommPrefs_1\\/PrefSuppType').removeAttr('disabled');
					$('#CommPrefs_1\\/CommPrefValue').removeAttr('disabled');				
					checkMarketedByHonda();
				}
			} else {
				$('#CommPrefs_1\\/PrefSuppType').attr("disabled","disabled");
				$('#CommPrefs_1\\/CommPrefValue').attr("disabled","disabled");
				checkMarketedByHonda();			
			}
			
			return true;
		}
		
		function SSDIF_Validate_Email_Explicit() {
			if(!emailCheck($('#TelephoneEmail\\/HomeEmail').val())) {
				alert("Please enter a valid email address");
				return false;
			}
			return true;
		}
		
		function SSDIF_Validate_Email_Optional() {
			if($('#TelephoneEmail\\/HomeEmail').val() != '') { 
				if(!emailCheck($('#TelephoneEmail\\/HomeEmail').val())) {
					alert("Please enter a valid email address");
					return false;
				}
			}
			
			return true;
		}
		
		function SSDIF_Validate_Email_Mandatory() {
			if(!emailCheck($('#TelephoneEmail\\/HomeEmail').val())) {
				alert("Please enter a valid email address");
				return false;
			}
			return true;
		}
		
		/**
		 *  Validates the telephone/email choice checkboxes, the user has to choose either or, the following checks are carried out:
		 *  - if both 'contactByTel' and 'contactByEmail' are not checked an appropriate error message is alerted.
		 */
		function SSDIF_Validate_Telephone_Email_Checkbox() {	
			if( ($("#contactByTel:checked").length == 0) && ($("#contactByEmail:checked").length == 0) ) {
				alert("Please choose either to be contacted by telephone or by email.");
				return false;
			}
			return true;
		}
		
		/**
		 *	Validates the contact day and time fields on a SSDIF (form), following checks are carried out:
		 *  - both 'contactDay' and 'contactTime' are selected (if not an appropriate error message is alerted)
		 *  - 'contactDay' is not selected (user is prompted to select a day of the week)
		 *  - 'contactTime' is not selected (user is promoted to select a time period)
		 */
		function SSDIF_Validate_Contact_Day_Time() {
			if( ($("#X_contactDay").val() == "") && ($("#X_contactTime").val() == "") ) {
				alert("Please select a day and time for us to contact you.");
				return false;
			} else if( ($("#X_contactDay").val() != "") && ($("#X_contactTime").val() == "") ) {
				alert("Please select a time for us to contact you.");	
				return false;
			} else if( ($("#X_contactDay").val() == "") && ($("#X_contactTime").val() != "") ) {
				alert("Please select a day for us to contact you.");	
				return false;
			}
			return true;
		}
		
		function SSDIF_Validate_Contact_Time() {
			if($("#X_contactTime").val() == "") {
				alert("Please select a time for us to contact you.");	
				return false;
			}
			return true;
		}

		function SSDIF_Validate_Telephone_Basic() {
			if(!telephoneValidate($('#telephoneNumber').val())) {
				alert("Please enter a valid telephone number");
				return false;
			}	
			return true;
		}
		
		
		
		/* Commented Out, because it includes new HUB functionality.
		function SSDIF_Validate_PlannedCar1() {
				//Check for :
				//a. Planned Purchase Date
				//b. New or Used
				//c. Private or Company
			
			
			// Possible Scenario: ReplacementDate flag = true. Date completed in Current car and is populated to plannedPurchase Year here.
			// If plannedPurchaseMonth and plannedPurchaseYear are selected & hidden input is already populated, but no other fields are, plannedPurchase date must have been populated from CurrentCar.
			
			if(	selectSelected("X_plannedPurchaseMonth") ||	selectSelected("X_plannedPurchaseYear") || radioSelected("ContactWithHonda/ProspectInterest/IntentNewUsed") || radioSelected("ContactWithHonda/ProspectInterest/CorporatePrivateUser")) {
				// Validate Planned Purchase Date, but only if it hasn't been populated from the CurrentCar replacement date.
				// If planned purchase date is the same as CurrentCar replacement date and the planned purchase date dropdowns haven't been selected,
				// assume this field has been populated from CurrentCar.
				if ($('#ContactWithHonda\\/ProspectInterest\\/PlannedPurchaseDate').val() !== $('#CurrentProduct\\/ReplacementDate').val() && 
				!selectSelected("X_plannedPurchaseMonth") 
				&& !selectSelected("X_plannedPurchaseYear")) {
					if(!selectSelected("X_plannedPurchaseMonth") || !selectSelected("X_plannedPurchaseYear")) {
						alert("Please enter a valid planned purchase date");
						return false;
					}
					if(!SSDIF_Validate_Planned_Purchase_Date("#X_plannedPurchaseMonth","#X_plannedPurchaseYear")) return false;
				}				
				// Validate New / Used
				if(!radioSelected("ContactWithHonda/ProspectInterest/IntentNewUsed")) {
					alert("Please select whether your next purchase would be either New or Used");
					return false;
				}
				
				// Validate Private / Corporate
				if(!SSDIF_Validate_Private_Corporate_Prospect(true)) return false;
				disableEmptyOptionalQuestions("10");

				$("#ContactWithHonda\\/ProspectInterest\\/Division, #ContactWithHonda\\/ProspectInterest\\/ProductSegment, #ContactWithHonda\\/ProspectInterest\\/CarData\\/Brand, #ContactWithHonda\\/ProspectInterest\\/CarData\\/ModelGroup").removeAttr("disabled");
			} else {
				$("#ContactWithHonda\\/ProspectInterest\\/Division, #ContactWithHonda\\/ProspectInterest\\/ProductSegment, #ContactWithHonda\\/ProspectInterest\\/CarData\\/Brand, #ContactWithHonda\\/ProspectInterest\\/CarData\\/ModelGroup").attr("disabled","disabled");
			}
			
			return true;
		
		}
		*/
		
		function SSDIF_Validate_PlannedCar1() {
			/*
				Check for :
				a. Planned Purchase Date
				b. New or Used
				c. Private or Company
			*/
			



			if(	selectSelected("X_plannedPurchaseMonth") ||	selectSelected("X_plannedPurchaseYear") || radioSelected("ContactWithHonda/ProspectInterest/IntentNewUsed") || radioSelected("ContactWithHonda/ProspectInterest/CorporatePrivateUser")) {
				// Validate Planned Purchase Date
				if(!selectSelected("X_plannedPurchaseMonth") ||	!selectSelected("X_plannedPurchaseYear")) {
					alert("Please enter a valid planned purchase date");
					return false;
				}
				if(!SSDIF_Validate_Planned_Purchase_Date("#X_plannedPurchaseMonth","#X_plannedPurchaseYear")) return false;
				



				// Validate New / Used
				if(!radioSelected("ContactWithHonda/ProspectInterest/IntentNewUsed")) {
					alert("Please select whether your next purchase would be either New or Used");
					return false;
				}
				
				// Validate Private / Corporate
				if(!SSDIF_Validate_Private_Corporate_Prospect(true)) return false;
				disableEmptyOptionalQuestions("10");

				$("#ContactWithHonda\\/ProspectInterest\\/Division, #ContactWithHonda\\/ProspectInterest\\/ProductSegment, #ContactWithHonda\\/ProspectInterest\\/CarData\\/Brand, #ContactWithHonda\\/ProspectInterest\\/CarData\\/ModelGroup").removeAttr("disabled");
			} else {
				$("#ContactWithHonda\\/ProspectInterest\\/Division, #ContactWithHonda\\/ProspectInterest\\/ProductSegment, #ContactWithHonda\\/ProspectInterest\\/CarData\\/Brand, #ContactWithHonda\\/ProspectInterest\\/CarData\\/ModelGroup").attr("disabled","disabled");
			}
			
			return true;
		
		}
		
		
		function SSDIF_Validate_PlannedCar2() {
			/*
				Check for :
				a. Planned Purchase Date
				b. New or Used
				c. Private or Company
				d. Type of car
				e. Fuel
			*/
			
			if(	selectSelected("X_plannedPurchaseMonth") ||	selectSelected("X_plannedPurchaseYear") || radioSelected("ContactWithHonda/ProspectInterest/IntentNewUsed") || radioSelected("ContactWithHonda/ProspectInterest/CorporatePrivateUser") ||	selectSelected("ContactWithHonda\\/Questions_11\\/Responses\\/Response") ||	selectSelected("ContactWithHonda\\/ProspectInterest\\/CarData\\/FuelType")) {
				if(!SSDIF_Validate_PlannedCar1()) return false;
				
				// Validate Type of Car
				if(!selectSelected("ContactWithHonda\\/Questions_11\\/Responses\\/Response")) {
					alert("Please select what type of car your next purchase would be");
					return false;
				} else {
					$("#ContactWithHonda\\/Questions_11\\/QuestionCode").removeAttr("disabled");
				}
				
				// Validate Fuel
				if(!selectSelected("ContactWithHonda\\/ProspectInterest\\/CarData\\/FuelType")) {
					alert("Please select what type of fuel your next purchase would have");
					return false;
				}
			} else {
				$("#ContactWithHonda\\/ProspectInterest\\/Division, #ContactWithHonda\\/ProspectInterest\\/ProductSegment, #ContactWithHonda\\/ProspectInterest\\/CarData\\/Brand, #ContactWithHonda\\/ProspectInterest\\/CarData\\/ModelGroup, #ContactWithHonda\\/Questions_11\\/Responses\\/Response, #ContactWithHonda\\/Questions_11\\/QuestionCode, #ContactWithHonda\\/ProspectInterest\\/CarData\\/FuelType").attr("disabled","disabled");
			}
			
			return true;
		}
		
		function SSDIF_Validate_Email_Optin() {
			// If email is entered then make the user select their email preference
			if($('#TelephoneEmail\\/HomeEmail').val() != '') { 
				if(!radioSelected('CommPrefs_1/PrefSuppType')) {
					alert("Please select whether you are happy to receive emails other than e-news");
					return false;
				}
			}
			
			if(radioSelected('CommPrefs_1/PrefSuppType')) {
				if(radioSelectedValue('CommPrefs_1/PrefSuppType') == 'Y') {
					if(!validateEmail()) { return false; }
				}
				$("#CommPrefs_1\\/CommPrefValue").removeAttr("disabled");
			} else {
				$("#CommPrefs_1\\/CommPrefValue").attr("disabled","disabled");
			}
			return true;
		}
		
		function SSDIF_Validate_Email_Newsletter_Optin() {
			// If email is entered then make the user select their email newsletter preference
			if($('#TelephoneEmail\\/HomeEmail').val() != '') { 
				if(!radioSelected('SubjectPrefs_1/PrefSuppType')) {
					alert("Please select whether you are happy to receive e-news");
					return false;
				}
			}
			
			if(radioSelected('SubjectPrefs_1/PrefSuppType')) {
				if(radioSelectedValue('SubjectPrefs_1/PrefSuppType') == 'Y') {
					if(!validateEmail()) { return false; }
				}
				$("#SubjectPrefs_1\\/SubjectPrefValue").removeAttr("disabled");				
			} else {
				$("#SubjectPrefs_1\\/SubjectPrefValue").attr("disabled","disabled");
			}
			return true;
		}
		
		function SSDIF_Validate_Dream_Magazine_Optin() {
			if(radioSelected('SubjectPrefs_4/PrefSuppType')) {
				if(radioSelectedValue('SubjectPrefs_4/PrefSuppType') == 'Y') {
					if(!validateEmail()) { return false; }
				}
				$("#SubjectPrefs_4\\/SubjectPrefValue").removeAttr("disabled");				
			} else {
				$("#SubjectPrefs_4\\/SubjectPrefValue").attr("disabled","disabled");
			}
			return true;
		}
		
		

/*******************************************************************************************/
/************************** SSDIF - VALIDATION FUNCTIONS ***********************************/
/*******************************************************************************************/
	function initSSDIFReset() {
		$("#"+formName + " input, #"+formName + " select").each(function() {
			resetInputArray.push(new Array(this,$(this).val(),$(this).attr("disabled")));		
		});
	}

	function resetSSDIFForm() {		
		// Reset Values
		for(inputPos = 0; inputPos < resetInputArray.length; inputPos++) {
			$(resetInputArray[inputPos][0]).val(resetInputArray[inputPos][1]);
			
			if(resetInputArray[inputPos][2]) {
				$(resetInputArray[inputPos][0]).attr("disabled","disabled");
			} else {
				$(resetInputArray[inputPos][0]).removeAttr("disabled");
			}
		}
	}

	function toggleCompany(theSelection,companyDiv,companyText,companyCode) {
		if(radioSelectedValue(theSelection) == 'C') {
			$('#'+companyDiv).show();
			$('#'+companyText).removeAttr('disabled');
			$('#'+companyCode).removeAttr('disabled');
		} else {
			$('#'+companyDiv).hide();
			$('#'+companyText).attr('disabled','disabled');
			$('#'+companyCode).attr('disabled','disabled');
		}
	}

	function toggleCommPref(theSelection) {
		if($('#'+theSelection).val() == 'Y') {
			$('#'+theSelection).val('N');
		} else {
			$('#'+theSelection).val('Y');
		}		
			
		checkMarketedByHonda();
	}
	
	function checkMarketedByHonda() {
		var yesPrefs = false;
		
		$("[id^=CommPrefs]").each(function(i) {
			if($(this).attr("id").indexOf("PrefSuppType") > -1) {
				if(($(this).val() == 'Y') && (!$(this).attr("disabled")) && (($(this).is("input[type='checkbox']") && $(this).is(':checked')) || ($(this).is("input[type='radio']") && $(this).is(':checked')) || ($(this).not("input[type='checkbox']").length && $(this).not("input[type='radio']").length) )) {
						yesPrefs = true;
				}
			}
		});
		
		if(yesPrefs) {
			$("#Entity\\/MarketedByHonda").val("Y");
		} else {
			$("#Entity\\/MarketedByHonda").val("");
		}	
	}
	
	function toggleSubjectPref(theSelection,hiddenElement) {
		if(radioSelected(theSelection)) {
			$('#'+hiddenElement).removeAttr('disabled');
		} else {
			$('#'+hiddenElement).attr('disabled','disabled');			
		}
		checkMarketedByHonda();
	}

	function validateEmail() {
		// Validate Email
		if(!emailCheck($('#TelephoneEmail\\/HomeEmail').val())) {
			alert("Please enter a valid email address");
			return false;
		} 
		return true;
	}
	
	
	function validateTelephone() {
		if(!telephoneValidate($('#X_phonenumber').val())) {
			alert("Please enter a valid telephone number");
			return false;
		}
		
		if(!radioSelected('TelephoneEmail/PrefTelephone')) {
			alert("Please select your telephone number type");
			return false;
		}
		
		switch($('input[name="TelephoneEmail/PrefTelephone"]:checked').val()) {
			case 'D' : {
				$('#TelephoneEmail\\/DaytimeNo').val(removeAllSpaces($('#X_phonenumber').val()));
				$('#TelephoneEmail\\/DaytimeNo').removeAttr('disabled');
				$('#TelephoneEmail\\/EveningNo').attr('disabled','disabled');
				$('#TelephoneEmail\\/MobileNo').attr('disabled','disabled');
				break;
			}
			case 'E' : {
				$('#TelephoneEmail\\/EveningNo').val(removeAllSpaces($('#X_phonenumber').val()));
				$('#TelephoneEmail\\/EveningNo').removeAttr('disabled');
				$('#TelephoneEmail\\/DaytimeNo').attr('disabled','disabled');
				$('#TelephoneEmail\\/MobileNo').attr('disabled','disabled');
				break;
			}
			case 'M' : {
				$('#TelephoneEmail\\/MobileNo').val(removeAllSpaces($('#X_phonenumber').val()));
				$('#TelephoneEmail\\/MobileNo').removeAttr('disabled');
				$('#TelephoneEmail\\/DaytimeNo').attr('disabled','disabled');
				$('#TelephoneEmail\\/EveningNo').attr('disabled','disabled');
				break;
			}
		}
		return true;
	}
	
	/**
	 * Checks whether the question is empty. If it is, it will disable the question and the response.
	 * Param : Comma-separated list of question numbers
	 */
	function disableEmptyOptionalQuestions(questionNumbers) {
	
		var questions = questionNumbers.split(",");
		
		for(questionPos = 0; questionPos < questions.length; questionPos++) {
			if($("#ContactWithHonda\\/Questions_"+questions[questionPos]+"\\/Responses\\/ResponseText").val() == "") {
				$("#ContactWithHonda\\/Questions_"+questions[questionPos]+"\\/QuestionCode").attr('disabled','disabled');
				$("#ContactWithHonda\\/Questions_"+questions[questionPos]+"\\/Responses\\/ResponseText").attr('disabled','disabled');				
			}			
		}	
	}
	
	function getDealerByPostcode(postcode,destination) {
		postcode = postcode.toString().replace(/\+/g, "").replace(/^\s*/, "").replace(/\s*$/, "").replace(/%20/g, "").replace(/ /g, "");
		postcode = postcode.toUpperCase().substring(0,postcode.length-3) + " "  + postcode.toUpperCase().substring(postcode.length-3);
		var isDealerFound = false;
		
		$.ajax({url:'/_assets/behaviour/getglobalvar.asp?var=ENTERPRISE', async:false, success:function(urlPath){
			$.ajax({url:'/_assets/behaviour/loader.asp?url=' + urlPath.toString() + 'GetDealerForTerritory?postcodePrefix=' + postcode, async:false, success:function(territoryXML){
				var regex = new RegExp('^.*Dealership="([A-Z]*[a-z]*[0-9]* *)"/>.*$', 'm');
				var dealership = "";
					
					if(territoryXML.indexOf("Dealership=") > -1) {
						dealership = regex.exec(territoryXML)[1];
						$(destination).val(dealership);
						isDealerFound = true;
					} else {
						isDealerFound = false;
						//clear hidden postcode fields
						$('#Address\\/Postcode1, #Address\\/Postcode2').val("");
					}					

			}});
		}});		
		
		return isDealerFound;
	}
	
	function setProspectInterestCarDetailsViaID(inputModelID,inputBodyID,inputBadgeID) {

		var actualBadge = inputBadgeID;
		var matchOne = inputModelID;
		var matchTwo = inputModelID + "_" + inputBodyID;
		var matchThree = inputModelID + "_" + inputBodyID;
		
		var actualMatch;

		if(inputBadgeID != "") {
			actualBadge = inputBadgeID.split(",")[0];
			matchThree = matchThree + "_" + actualBadge;
		}
		
		$("#ContactWithHonda\\/ProspectInterest\\/Division, #ContactWithHonda\\/ProspectInterest\\/ProductSegment").removeAttr("disabled");
		
		// Set Brand
		$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Brand").val("HO");
		$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Brand").removeAttr("disabled");
		
		$.ajax({url:'/_assets/data/carData.xml', async:false, success:function(xmlDoc){
																			   
			$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/ModelGroup").removeAttr("disabled");
			$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/BodyStyle").removeAttr("disabled");
			$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Doors").removeAttr("disabled");
			
			if($(xmlDoc).find("mbbitem[id='"+matchThree+"']").length > 0) {
				actualMatch = "mbbitem[id='"+matchThree+"']";				
		   	} else if($(xmlDoc).find("mbbitem[id='"+matchTwo+"']").length > 0) {
				actualMatch = "mbbitem[id='"+matchTwo+"']";
			} else if($(xmlDoc).find("mbbitem[id='"+matchOne+"']").length > 0) {
				actualMatch = "mbbitem[id='"+matchOne+"']";
		  	}
			
			$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/ModelGroup").val($(xmlDoc).find(actualMatch).parent().parent().find("modelgroup").eq(0).text());			
			$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Doors").val($(xmlDoc).find(actualMatch).parent().parent().find("doors").eq(0).text());						
			$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/BodyStyle").val($(xmlDoc).find(actualMatch).parent().parent().find("bodystyle").eq(0).text());									
			}
	   	});
		
	}
	
	function setProspectInterestCarDetails(inputModelGroup,inputBodyStyle,inputDoors,inputTransmission,inputFuelType) {		
		$("#ContactWithHonda\\/ProspectInterest\\/Division, #ContactWithHonda\\/ProspectInterest\\/ProductSegment").removeAttr("disabled");
		
		// Set Brand
		$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Brand").val("HO");
		$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Brand").removeAttr("disabled");
		
		// Set ModelGroup
		if(inputModelGroup != null) {
			$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/ModelGroup").removeAttr("disabled");
				
			$.ajax({url:'/SSDiffService/lovService.do?codeType=213&startFilter=HO&startDescFilter='+inputModelGroup, async:false, success:function(xmlDoc){
				if($(xmlDoc).find("LookupValue").length == 1) {
					$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/ModelGroup").val($(xmlDoc).find("Value").text());
				} else if($(xmlDoc).find("LookupValue").length > 0) {
					$(xmlDoc).find("Description").each(function() {
						var currentNode = $(this).text().toUpperCase();
						
						if(currentNode == inputModelGroup.toUpperCase()) {
							$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/ModelGroup").val($(this).parent().find("Value").text());
						}
						
					});		
				} else {
					$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/ModelGroup").attr("disabled","disabled");
				}
			}});
		}
		
		// Set BodyStyle
		if(inputBodyStyle != null) {		
			$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/BodyStyle").removeAttr("disabled");
			
			$.ajax({url:'/SSDiffService/lovService.do?codeType=11&startDescFilter='+inputBodyStyle, async:false, success:function(xmlDoc){
				if($(xmlDoc).find("LookupValue").length == 1) {
					$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/BodyStyle").val($(xmlDoc).find("Value").text());
				} else if($(xmlDoc).find("LookupValue").length > 0) {
					$(xmlDoc).find("Description").each(function() {
						var currentNode = $(this).text().toUpperCase();
						
						if(currentNode == inputBodyStyle.toUpperCase()) {
							$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/BodyStyle").val($(this).parent().find("Value").text());
						}
						
					});		
				} else {
					$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/BodyStyle").attr("disabled","disabled");
				}
			}});
		}
		
		// Set Doors
		if(inputDoors != null) {	
			$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Doors").removeAttr("disabled");
			
			if(inputDoors != "") {
				$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Doors").val(inputDoors);
			} else {
				$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Doors").attr("disabled","disabled");
			}
		}
		
		// Set Transmission		
		if(inputTransmission != null) {	
			$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Transmission").removeAttr("disabled");
		
			$.ajax({url:'/SSDiffService/lovService.do?codeType=283&startDescFilter='+inputTransmission, async:false, success:function(xmlDoc){
				if($(xmlDoc).find("LookupValue").length == 1) {
					$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Transmission").val($(xmlDoc).find("Value").text());
				} else if($(xmlDoc).find("LookupValue").length > 0) {
					$(xmlDoc).find("Description").each(function() {
						var currentNode = $(this).text().toUpperCase();
						
						if(currentNode == inputTransmission.toUpperCase()) {
							$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Transmission").val($(this).parent().find("Value").text());
						}
						
					});		
				} else {
					$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/Transmission").attr("disabled","disabled");
				}
			}});
		}
		
		// Set FuelType
		if(inputFuelType != null) {	
			$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/FuelType").removeAttr("disabled");
		
			$.ajax({url:'/SSDiffService/lovService.do?codeType=70&startDescFilter='+inputFuelType, async:false, success:function(xmlDoc){
				if($(xmlDoc).find("LookupValue").length == 1) {
					$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/FuelType").val($(xmlDoc).find("Value").text());
				} else if($(xmlDoc).find("LookupValue").length > 0) {
					$(xmlDoc).find("Description").each(function() {
						var currentNode = $(this).text().toUpperCase();
						
						if(currentNode == inputFuelType.toUpperCase()) { // DW: Removed spurious .val()
							$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/FuelType").val($(this).parent().find("Value").text());
						}
						
					});		
				} else {
					$("#ContactWithHonda\\/ProspectInterest\\/CarData\\/FuelType").attr("disabled","disabled");
				}
			}});
		}

	
	}
	
	function setProspectInterestCarDetailsUsedCars(inputModelGroup,inputBodyStyle,inputTransmission,inputFuelType) {
		setProspectInterestCarDetails(inputModelGroup,inputBodyStyle,null,inputTransmission,inputFuelType);
	}
	
/*******************************************************************************************/
/**************************** SSDIF - BROCHURE REQUEST *************************************/
/*******************************************************************************************/	
	function buildCarDataTestDrive(mbb_model,mbb_body,mbb_badge) {
		
		if(!$(carDataXML).find("mbbitem[id='"+mbb_model + "_" + mbb_body + "_" + mbb_badge + "']").length) {
			if(!$(carDataXML).find("mbbitem[id='"+mbb_model + "_" + mbb_body + "']").length) {
				if(!$(carDataXML).find("mbbitem[id='"+mbb_model+"']").length) {
				} else {
					processCarDataTestDrive(mbb_model);
				}
			} else {
				processCarDataTestDrive(mbb_model + "_" + mbb_body);
			}	
		} else {
			processCarDataTestDrive(mbb_model + "_" + mbb_body + "_" + mbb_badge);
		}
		
	}
	
	function processCarDataTestDrive(searchString) {
		var carDataArray = new Array('<input type="hidden" name="ContactWithHonda/TestDrive/CarData/Brand" id="ContactWithHonda/TestDrive/CarData/Brand" value="HO" />',
		'<input type="hidden" name="ContactWithHonda/TestDrive/CarData/ModelGroup" id="ContactWithHonda/TestDrive/CarData/ModelGroup" />',
		'<input type="hidden" name="ContactWithHonda/TestDrive/CarData/Trim" id="ContactWithHonda/TestDrive/CarData/Trim" value="" />',
		'<input type="hidden" name="ContactWithHonda/TestDrive/CarData/Doors" id="ContactWithHonda/TestDrive/CarData/Doors" />',
		'<input type="hidden" name="ContactWithHonda/TestDrive/CarData/EngineSizeCC" id="ContactWithHonda/TestDrive/CarData/EngineSizeCC" value="" />',
		'<input type="hidden" name="ContactWithHonda/TestDrive/CarData/ModelYear" id="ContactWithHonda/TestDrive/CarData/ModelYear" />',
		'<input type="hidden" name="ContactWithHonda/TestDrive/CarData/BodyStyle" id="ContactWithHonda/TestDrive/CarData/BodyStyle" />',
		'<input type="hidden" name="ContactWithHonda/TestDrive/CarData/FuelType" id="ContactWithHonda/TestDrive/CarData/FuelType" />',
		'<input type="hidden" name="ContactWithHonda/TestDrive/CarData/Transmission" id="ContactWithHonda/TestDrive/CarData/Transmission" value="" />',		
		'<input type="hidden" name="ContactWithHonda/TestDrive/Division" id="ContactWithHonda/TestDrive/Division" value="20" />',
		'<input type="hidden" name="ContactWithHonda/TestDrive/ProductSegment" id="ContactWithHonda/TestDrive/ProductSegment" value="080" />',		
		'<input type="hidden" name="ContactWithHonda/ProspectInterest/CarData/Brand" id="ContactWithHonda/ProspectInterest/CarData/Brand" value="HO" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest/CarData/ModelGroup" id="ContactWithHonda/ProspectInterest/CarData/ModelGroup" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest/CarData/Trim" id="ContactWithHonda/ProspectInterest/CarData/Trim" value="" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest/CarData/Doors" id="ContactWithHonda/ProspectInterest/CarData/Doors" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest/CarData/EngineSizeCC" id="ContactWithHonda/ProspectInterest/CarData/EngineSizeCC" value="" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest/CarData/ModelYear" id="ContactWithHonda/ProspectInterest/CarData/ModelYear" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest/CarData/BodyStyle" id="ContactWithHonda/ProspectInterest/CarData/BodyStyle" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest/CarData/FuelType" id="ContactWithHonda/ProspectInterest/CarData/FuelType" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest/CarData/Transmission" id="ContactWithHonda/ProspectInterest/CarData/Transmission" value="" />');		
		
		$(carDataXML).find("mbbitem[id='"+searchString+"']").each(function(){
			for(arrayNum = 0; arrayNum < carDataArray.length; arrayNum++) {
				var hidden = $(carDataArray[arrayNum]);
			
				switch(arrayNum) {
					case 1 : {
						$(hidden).val($(this).parents("brochure").find("modelgroup").text()); 
						break;
					}
					case 3 : {
						$(hidden).val($(this).parents("brochure").find("doors").text()); 
						break;
					}
					case 5 : {
						$(hidden).val($(this).parents("brochure").find("modelyear").text()); 
						break;
					}
					case 6 : {
						$(hidden).val($(this).parents("brochure").find("bodystyle").text()); 
						break;
					}
					case 7 : {
						$(hidden).val($(this).parents("brochure").find("fueltype").text()); 
						break;
					}
					case 12 : {
						$(hidden).val($(this).parents("brochure").find("modelgroup").text()); 
						break;
					}
					case 14 : {
						$(hidden).val($(this).parents("brochure").find("doors").text()); 
						break;
					}
					case 16 : {
						$(hidden).val($(this).parents("brochure").find("modelyear").text()); 
						break;
					}
					case 17 : {
						$(hidden).val($(this).parents("brochure").find("bodystyle").text()); 
						break;
					}
					case 18 : {
						$(hidden).val($(this).parents("brochure").find("fueltype").text()); 
						break;
					}
				}
				$('#'+formName).append(hidden);
			}
		});
	}
	
	function buildCarBrochureElements() {	

		var brochureArray = new Array('<input type="hidden" name="ContactWithHonda/FulfilmentRequest_~/RequestType" id="ContactWithHonda/FulfilmentRequest_~/RequestType" value="B" />',
		'<input type="hidden" name="ContactWithHonda/FulfilmentRequest_~/RequestItemService" id="ContactWithHonda/FulfilmentRequest_~/RequestItemService" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/Division" id="ContactWithHonda/ProspectInterest_~/Division" value="20" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/ProductSegment" id="ContactWithHonda/ProspectInterest_~/ProductSegment" value="080" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/PlannedPurchaseDate" id="ContactWithHonda/ProspectInterest_~/PlannedPurchaseDate"/>',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/CarData/Brand" id="ContactWithHonda/ProspectInterest_~/CarData/Brand" value="HO" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/CarData/ModelGroup" id="ContactWithHonda/ProspectInterest_~/CarData/ModelGroup" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/CarData/Trim" id="ContactWithHonda/ProspectInterest_~/CarData/Trim" value="" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/CarData/Doors" id="ContactWithHonda/ProspectInterest_~/CarData/Doors" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/CarData/EngineSizeCC" id="ContactWithHonda/ProspectInterest_~/CarData/EngineSizeCC" value="" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/CarData/ModelYear" id="ContactWithHonda/ProspectInterest_~/CarData/ModelYear" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/CarData/BodyStyle" id="ContactWithHonda/ProspectInterest_~/CarData/BodyStyle" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/CarData/FuelType" id="ContactWithHonda/ProspectInterest_~/CarData/FuelType" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/CarData/Transmission" id="ContactWithHonda/ProspectInterest_~/CarData/Transmission" value="" />',		
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/CorporatePrivateUser" id="ContactWithHonda/ProspectInterest_~/CorporatePrivateUser" value="" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/Relationship" id="ContactWithHonda/ProspectInterest_~/Relationship" value="" />',
		'<input type="hidden" name="ContactWithHonda/ProspectInterest_~/IntentNewUsed" id="ContactWithHonda/ProspectInterest_~/IntentNewUsed" value="" />');
		
		/*
			The elements that need filling in are :
			1 - Brochure Code
			4 - Planned Purchase date : yyyy-mm-01
			6 - Model Group
			8 - Doors
			10 - Model Year
			11 - Body Style
			12 - Fuel Type		
			14 - Corporate / Private
			15 - Corporate / Private
			16 - New / Used
		*/

		
		var queryString = unescape(getHttpGetParameters("brochures")).toString().replace("#","").split(",");
		queryString = queryString.concat(getHttpGetParameters("acc").toString().replace("#","").split(","));
		var fulfilElementNum = 0;
		var prospectElementNum = 0;
		for(brochureNum = 0; brochureNum < queryString.length; brochureNum++) {
			
			var currentBrochure = queryString[brochureNum];
				$(carDataXML).find("brochure[code='" + currentBrochure + "']").each(function(){		
						var isAccessory = false;
							
						if($(this).find("brand").text() == '') {
							isAccessory = true;							
						} else {
							prospectElementNum++;
						}
						
						fulfilElementNum++;
						
						for(arrayNum = 0; arrayNum < brochureArray.length; arrayNum++) {

							var addElement = true;							
							
							if(isAccessory && arrayNum >= 2) {
								addElement = false;
							} 
							
							if(addElement) {				
								var hidden;
								
								if(arrayNum < 2) {
									hidden = $(brochureArray[arrayNum].replace(/\~/g,(fulfilElementNum)));
								} else {
									hidden = $(brochureArray[arrayNum].replace(/\~/g,(prospectElementNum)));
								}
								
								
								switch(arrayNum) {
									case 1 : {
										$(hidden).val(currentBrochure); 
										break;
									}
									case 4 : {										
										$(hidden).val($('#X_replaceYear').val() + "-" + $('#X_replaceMonth').val() + "-01");																 						
										break;
									}
									case 6 : {
										$(hidden).val($(this).find("modelgroup").text()); 
										break;
									}
									case 8 : {
										$(hidden).val($(this).find("doors").text()); 
										break;
									}
									case 10 : {
										$(hidden).val($(this).find("modelyear").text()); 
										break;
									}
									case 11 : {
										$(hidden).val($(this).find("bodystyle").text()); 
										break;
									}
									case 12 : {
										$(hidden).val($(this).find("fueltype").text()); 
										break;
									}
									case 14 : {
										$(hidden).val(radioSelectedValue('X_corpPrivUser'));
										break;									
									}
									case 15 : {
										if(radioSelectedValue('X_corpPrivUser') == 'C') {
											$(hidden).val('U');
										} else {
											$(hidden).val('O');
										}
										break;
									}
									case 16 : {
										$(hidden).val(radioSelectedValue('X_newUsed'));
									}
								}
						        $('#'+formName).append(hidden);
							}
						}
					});
			//}
		}
	}
	
	/**** JQUERY ****/
	
	$(document).ready(function() {


		
				
		// CommPrefs - Email (Old)
		if($('#CommPrefs_1\\/PrefSuppType').length) {
			$('#CommPrefs_1\\/PrefSuppType').livequery('click',function() {
				toggleSubjectPref('CommPrefs_1/PrefSuppType','CommPrefs_1\\/CommPrefValue');		
			});			
		}
		
		// CommPrefs - Email (New - Radio Buttons)
		if($('#CommPrefs_1\\/PrefSuppType_Yes').length) {
			$('#CommPrefs_1\\/PrefSuppType_Yes, #CommPrefs_1\\/PrefSuppType_No').livequery('click',function() {
				checkMarketedByHonda();	
			});			
		}
		
		// CommPrefs - Post
		if($('#X_CommPrefs_4\\/PrefSuppType').length) {
			$('#X_CommPrefs_4\\/PrefSuppType').livequery('click',function() {
				toggleCommPref('CommPrefs_4\\/PrefSuppType');		
			});
		}
		
		// CommPrefs - Telephone
		if($('#X_CommPrefs_5\\/PrefSuppType').length) {
			$('#X_CommPrefs_5\\/PrefSuppType').livequery('click',function() {
				toggleCommPref('CommPrefs_5\\/PrefSuppType');		
			});
		}		
		
		
		// Newsletter - Honda (Old)
		if($('#SubjectPrefs_1\\/PrefSuppType').length) {
			$('#SubjectPrefs_1\\/PrefSuppType').livequery('click',function() {
				toggleSubjectPref('SubjectPrefs_1/PrefSuppType','SubjectPrefs_1\\/SubjectPrefValue');		
			});
		}
		
		// Newsletter - Motorcycles
		if($('#SubjectPrefs_2\\/PrefSuppType').length) {
			$('#SubjectPrefs_2\\/PrefSuppType').livequery('click',function() {
				toggleSubjectPref('SubjectPrefs_2/PrefSuppType','SubjectPrefs_2\\/SubjectPrefValue');		
			});
		}
		
		// Newsletter - Corporate
		if($('#SubjectPrefs_3\\/PrefSuppType').length) {
			$('#SubjectPrefs_3\\/PrefSuppType').livequery('click',function() {
				toggleSubjectPref('SubjectPrefs_3/PrefSuppType','SubjectPrefs_3\\/SubjectPrefValue');		
			});
		}
		
		// Dream Magazine
		if($('#SubjectPrefs_4\\/PrefSuppType').length) {
			$('#SubjectPrefs_4\\/PrefSuppType').livequery('click',function() {
				toggleSubjectPref('SubjectPrefs_4/PrefSuppType','SubjectPrefs_4\\/SubjectPrefValue');		
			});
		}
		
		// Preferred method of contact
		if($('#Entity\\/PrefContactMedium').length) {	
			$('#Entity\\/PrefContactMedium').empty();	
			$('#Entity\\/PrefContactMedium').append('<option value="">Please select ...</option>');
			$('#Entity\\/PrefContactMedium').append('<option value="M">Post</option>');
			$('#Entity\\/PrefContactMedium').append('<option value="E">Email</option>');
			$('#Entity\\/PrefContactMedium').append('<option value="T">Telephone</option>');
		}
		
		
		// Title
		if($('#X_title').length) {
			$('#X_title').livequery('change',function() {
				titleOtherCheck('#X_title','#otherTitleDiv');
			});
		}
		
		// Load the Car Data XML file
		$.get('/_assets/data/carData.xml', function(xml) {
			carDataXML = xml;			
		});
	
	});
	
	function fillPrefMethodOfContact() {
		if($('#Entity\\/PrefContactMedium').length) {	
			$('#Entity\\/PrefContactMedium').empty();
			$('#Entity\\/PrefContactMedium').append('<option value="">Please select ...</option>');
			$('#Entity\\/PrefContactMedium').append('<option value="M">Post</option>');
			$('#Entity\\/PrefContactMedium').append('<option value="E">Email</option>');
			$('#Entity\\/PrefContactMedium').append('<option value="T">Telephone</option>');
		}
	}

/*******************************************************************************************/
/**************************************** QAS **********************************************/
/*******************************************************************************************/	

	var qasServiceUrl	= "/honda-utility/addressFinder.do"
	
	var QASAddressList = "dAddressList";
	
	var qas_houseTextBox;
	var qas_postcodeTextBox;
	var qas_addressList;
	var addressArray = new Array();
	var addressSelected = 0;
	
	function qas_parseAddresses(strParam) {
	
		var counter = 0;
		
	 
			 $.get(qasServiceUrl+"?"+strParam, function(xmldoc){
			
				var str = "";
				
				var count = $(xmldoc).find("count").text();
				var found = $(xmldoc).find("found").text();
				
				qas_clearList();
				
				var i = 0;		
				
				$(xmldoc).find("picklistItem, addressItem").each(function() {												 			
	
					var thisItem = this;
	
					var addressHouseNo 		= 		qas_readValue(thisItem,"addressHouseNo");
					
					var addressStreet 		= 		qas_readValue(thisItem,"addressStreet");
					var addressDistrict 	= 		qas_readValue(thisItem,"addressDistrict");
					
					var addressArea			=		qas_readValue(thisItem,"addressArea");
					
					var addressTown 		= 		qas_readValue(thisItem,"addressTown");
					var addressCounty 		= 		qas_readValue(thisItem,"addressCounty");
					var addressPostCode 	= 		qas_readValue(thisItem,"addressPostCode");
					
					var monikerId			=		qas_readValue(thisItem,"qasApprovedAddress");
					
					qas_addToList(addressHouseNo,addressStreet,addressDistrict,addressArea,addressTown,addressCounty,addressPostCode,monikerId);
				
					i++;
				});
				
				if ($(xmldoc).find("picklistItem, addressItem").length>1) {
					
					qas_displayList();
				}
				else if($(xmldoc).find("picklistItem, addressItem").length == 0) {
					alert("Sorry, we couldn't find that address. Please try again");
				}
				
				if (count==1) qas_setAddress(0);
			});
	}
	
	
	function qas_readValue(node,name) {
		if($(node).find(name).length) {
			return $(node).find(name).text();
		}
		else {
			return "";
		}
		
	}
	
	function qas_clearList() {
		addressArray.length = 0;
	}
	
	function qas_addToList(num,street,district,area,town,county,pc,monikerId) {
		newAddress = new Array(num,street,district,area,town,county,pc,monikerId);
		addressArray.push(newAddress);
		
	}
	
	function qas_displayList() {
		qas_listStr = "";
		for (i = 0; i<addressArray.length; i++) {
			// Trim this down
			addressArray[i][0] = addressArray[i][0].substring(0,addressArray[i][0].indexOf(","));
		
			qas_listStr += "<a href=\"javascript:qas_retrieveAddress('" + addressArray[i][7] + "');\" class=\"qas\">" + addressArray[i][0] + "</a><br>";
		}
		$(qas_addressList).html(qas_listStr).show();
	}
	
	function qas_retrieveAddress(i) {
		qas_clearList();
	
		$.get(qasServiceUrl+"?monikerId="+i, function(xmldoc){
			$(xmldoc).find("addressItem").each(function() {		
				var thisItem = this;

				var addressHouseNo 		= 		qas_readValue(thisItem,"addressHouseNo");
				
				var addressStreet 		= 		qas_readValue(thisItem,"addressStreet");
				var addressDistrict 	= 		qas_readValue(thisItem,"addressDistrict");
				
				var addressArea			=		qas_readValue(thisItem,"addressArea");
				
				var addressTown 		= 		qas_readValue(thisItem,"addressTown");
				var addressCounty 		= 		qas_readValue(thisItem,"addressCounty");
				var addressPostCode 	= 		qas_readValue(thisItem,"addressPostCode");
				
				var monikerId			=		qas_readValue(thisItem,"qasApprovedAddress");
							
				qas_addToList(addressHouseNo,addressStreet,addressDistrict,addressArea,addressTown,addressCounty,addressPostCode,monikerId);
				
				qas_setAddress(0); 
			});
		});
		
		
	}
	
	function qas_setAddress(i) {
		addressSelected = i;
		qas_AddressSelected();
		$(qas_addressList).hide();
	}
	
	function qas_getTextValue(obj) {
		return obj.options[obj.selectedIndex].text;
	}
		
	
	//public functions
	
	function qas_getHouse() {
		return addressArray[addressSelected][0];
	}
	
	function qas_getStreet() {
		return addressArray[addressSelected][1];
	}
	
	function qas_getDistrict() {
		return addressArray[addressSelected][2];
	}
	
	function qas_getArea() {
		return addressArray[addressSelected][3];
	}
	
	function qas_getTown() {
		return addressArray[addressSelected][4];
	}
	
	function qas_getCounty() {
		return addressArray[addressSelected][5];
	}
	
	function qas_getPostcode() {
		return addressArray[addressSelected][6];
	}
	
	function qas_getMonikerId() {
		return addressArray[addressSelected][7]
	}
	
	function qas_Submit() {
		
		qas_houseTextBox 		= $('#'+formName + ' #X_house');
		qas_postcodeTextBox 	= $('#'+formName + ' #X_postcode');
		qas_addressList 		= $('#'+QASAddressList);			
		
		$(qas_addressList).hide();
		
		var formFilled = true;
		
		if ($(qas_postcodeTextBox).val().length==0) {
			formFilled = false;
		}
		 if ($(qas_houseTextBox).val().length==0) {
			formFilled = false;
		}
		
		pc = $(qas_postcodeTextBox).val();
		testPC = isValidPostcode(pc);
		if(!testPC){formFilled=false;}
		
		if (formFilled) {	
			qas_parseAddresses('house='+$(qas_houseTextBox).val()+'&postcode='+$(qas_postcodeTextBox).val());
		}
		else {
			alert("Please enter a house number/name and a postcode");
		}
		
	}
	
	function qas_AddressesReturned() {
		alert("addresses returned");
	}
	
	function qas_AddressSelected() {
		$('#Address\\/Address1').val(qas_getHouse());
		$('#Address\\/Address2').val(qas_getStreet());
		$('#Address\\/Address3').val(qas_getDistrict());
		$('#Address\\/Address4').val(qas_getArea());
		$('#Address\\/Town').val(qas_getTown());

		if($('#Address\\/County').length > 0) {
			$('#Address\\/County').val(qas_getCounty());
		} 
		
		$('#Address\\/Postcode1').val($(qas_postcodeTextBox).val().toUpperCase().replace(' ','').substring(0,$(qas_postcodeTextBox).val().replace(' ','').length-3));
		$('#Address\\/Postcode2').val($(qas_postcodeTextBox).val().toUpperCase().replace(' ','').substring($(qas_postcodeTextBox).val().replace(' ','').length-3));
	}

	// This function adds a star if the optional testCondition is true and there isn't already one there.
	(function($){$.fn.appendStar = function(testCondition) {
		if (typeof(testCondition) === "undefined" || testCondition) {
			this.each(function(){
				var element = $(this);
				var text = element.text();
				// check to see if there is a star in the last position ...
				if (text.indexOf("*", (text.length - 1)) === -1) {
					//... if not, then add it:
					element.append("*");
				}
			});
		}
		return this;
	}})(jQuery);typeof(testCondition) === "undefined" || testCondition

/* Dynamic Comms and Campaign Code Support 
 * ---------------------------------------
 * Enables marketers to alter the Campaign and Comms codes dependant upon the source of the visitor by supplying different URLs to different mediums
 * 
 * - Enabled by setting DynamicCampaignId to true 
 * - Reads campaignid from query string (or from passed parameter, for future support)
 * - campaignid MUST be 12 alphanumeric characters long (alpha need to be upper case):
 * 		- Division (one letter)
 * 		- Activity Type (one letter)
 * 		- Sequence Number (four digits)
 * 		- Cell Ref (two digits)
 * 		- Outbound medium (one letter)
 * 		- Data Source (two digits)
 * 		- Outbound Execution (one letter)
 * 		
 * 		Reg exp needs to match:
 * 		- Start of string, letter, letter, four digits, two digits, letter, two digits, letter. End of string. See regexp below.
 * - there should be values specified in the document already
 */
var ssdifDynamicCampaignId = function(passedCampaignId) {
	if (ssdifCampaignValues.DynamicCampaignId !== true) { // If it's not enabled, exit with error.
		return false;
	}
	// read string
		// if id is passed into function, use that, otherwise get from query string:
	if (typeof(passedCampaignId) === "undefined" || passedCampaignId === null) {
		campaignid = getHttpGetParameters("campaignid")[0]; // Need to get first element in the returned array, it doesn't return as a string.
	} else {
		campaignid = passedCampaignId;
	}	
	
	// check string (confirm it is string first)
	if (typeof(campaignid) !== "string") { // this prevents errors when trying to access the toUpperCase method on non strings
		return false;
	}
	// output needs to be uppercase, but input in either allowed:
	campaignid = campaignid.toUpperCase();
	var campaignid = removeAllSpaces(campaignid); // keep it trim - uses standard ssdif method
	// see comments above for the reasons behind this regular expression. 
	// Note the extensive use of round brackets, these create capture groups in the output, meaning this line splits as well as checking the string 
	var regexp = /^([A-Z])([A-Z])([0-9]{4})([0-9]{2})([A-Z])([0-9]{2})([A-Z])$/;
	var output = regexp.exec(campaignid); // run the regexp and store capture groups in array. output[0] is the full match, output[1] to [7] are the capture groups...
	
	// is the input string valid? (if the regexp doesn't match, it returns null
	if (output === null) { // no match	
		return false
	}
	
	// split string (uses previously created regular expression capture groups)
	var division = output[1];
	var activityType = output[2];
	var sequenceNumber = output[3];
	var cellRef = output[4];
	var outboundMedium = output[5];
	var dataSource = output[6];
	var outboundExecution = output[7];
	
	// write string to JS Object: (in case it gets reinitialised) 
	
	ssdifCampaignValues['ContactWithHonda/CampaignDivision'] = division;
	ssdifCampaignValues['ContactWithHonda/ActivityType'] = activityType;
	ssdifCampaignValues['ContactWithHonda/SequenceNumber'] = sequenceNumber;
	ssdifCampaignValues['ContactWithHonda/CellRef'] = cellRef;
	ssdifCampaignValues['ContactWithHonda/OutboundMedium'] = outboundMedium;
	ssdifCampaignValues['ContactWithHonda/DataSource'] = dataSource;
	ssdifCampaignValues['ContactWithHonda/OutboundExecution'] = outboundExecution;
	
	// write string to DOM: (so it gets used on submit)
	$("#ContactWithHonda\\/CampaignDivision").val(division);
	$("#ContactWithHonda\\/ActivityType").val(activityType);
	$("#ContactWithHonda\\/SequenceNumber").val(sequenceNumber);
	$("#ContactWithHonda\\/CellRef").val(cellRef);
	$("#ContactWithHonda\\/OutboundMedium").val(outboundMedium);
	$("#ContactWithHonda\\/DataSource").val(dataSource);
	$("#ContactWithHonda\\/OutboundExecution").val(outboundExecution);
	
	return true
}
	