/*
	
	Details:
	========
	
	Note: (optional) elements do not need to passed in if you are not using them
	
	submit_destinationId,
	submit_campaignId,
	submit_redirect (optional) - will default to current URL if not passed in. Use <REMOVE> if you want to remove the input completely.
	AlternateSubmitAction (optional - will change the action on the form),
	ContactWithHonda/CampaignDivision,
	ContactWithHonda/ActivityType,
	ContactWithHonda/SequenceNumber,
	ContactWithHonda/CellRef,
	ContactWithHonda/OutboundMedium,
	ContactWithHonda/DealerCode (optional),
	SetDealerCodeByPostcode (optional - will set the DealerCode based on the customers postcode),
	ContactWithHonda/CRCode (optional - defaults to AH09),
	ContactWithHonda/Comment (optional),
	CustomComment (optional) - this can be text, javascript object etc.. Will be appended to ContactWithHonda/Comment,
	VisibleComment (optional - specify MaxLength),
	VisibleCommentLabel (optional),
	ContactWithHonda/DataSource,
	ContactWithHonda/OutboundExecution,
	ContactWithHonda/ContactType (optional),
	ContactWithHonda/ResponseType,
	ContactWithHonda/ResponseStatus,
	ContactWithHonda/InboundExecution,
	TouchClarity_Logging_Code (optional), this gets called immediately before form submit
	MultipageTracking (optional - true/false) - should the Touch Clarity logging be called when multiform "next" buttons are used?
	MultipageTrackingURL (optional (but required if MultipageTracking is true) - URL) - The URL to pass into the tc_log function. Will have the page number appended to it.
	Telephone_Mandatory (optional - value should be true),
	Email_Mandatory (optional - value should be true),
	ENewsletter_Hidden (optional - value should be true, this will default a hidden element to 'Y'),
	Dream_Magazine (optional - value shoud be true),
	DateOfBirth (optional - value should be true),
	SMSNumber (optional - value should be true),
	PlannedCar1 (optional - value should be true),
	PlannedCar2 (optional - value should be true, will also activate PlannedCar1, DO NOT USE WITH SetProspectInterestCarDetails, Brochures or UsedCars),
	CurrentCar (optional - value should be true),
	ReplacementDate (optional - value should be true), Shows the replacement date within the Current car section. Only use if CurrentCar === true
	CurrentInsurance (optional - true/false) - should insurance expiry date be asked? Only use if CurrentCar === true
	MinimalForm (optional - value should be true) - only shows the basic minimal form,
	ContactTime (optional - value should be true) - display the preferred contact time,
	SetProspectInterestCarDetails (optional - value should (IN THIS ORDER) MODEL NAME, BODY STYLE, DOORS, TRANSMISSION, FUEL TYPE) (DO NOT USE WITH PlannedCar2),
	SetProspectInterestCarDetailsById (ModelID,BodyID,BadgeID('s)),	
	RunAfterValidation (optional - value should be name of function, return false to stop form submitting or true to continue),
	HiddenSubmit (optional - true) - will submit the form to a hidden Iframe,
	HideAddress (optional - true) - will hide the address inputs and relevant communication preferences,
	RunAfterSubmit (optional - value should be name of function. This will only work if HiddenSubmit = true),
	UsedCars (optional - value should (IN THIS ORDER) MODEL NAME, BODY STYLE, TRANSMISSION, FUEL TYPE, REGISTRATION NUMBER) (DO NOT USE WITH PlannedCar1 or PlannedCar2),
	FadeForm (optional - true/false) - .fadeOut() the form after submit rather than .slideUp(). This works around a Firefox issue that causes long pages to flicker as the form slides and the browser tries to continuously adjust the scroll position to match. 
	RegLookup (optional - jQuery compatible selector of the Car Registration input box): Enables a lookup of the car registration and returning of vehicle specifics to the form. Requires additional config in regMaps.responseOutput) example selector: #CurrentProduct\\/Registration
	OnlineOrder (optional - value should be GENPO,PRODUCT,ORDER TYPE,DIVISION,SEGMENT,PROCEED XSL FILE PATH)
	Brochures (optional - value should be an Array containing business area and an array of brochures),
	DealerPreferences (optional -  true/false Enables the Dealer Preferences dropdown) NOTE: This was requested, developed, tested locally and then removed from the spec. needs proper testing before use.
	CustomQuestions (optional - value should be an Array containing an Array for each question required e.g.: 
		[
			[
				"QUESTION_NUMBER",
				"QUESTION_CODE",
				"QUESTION_LABEL",
				"SELECTOR_NAME",
				"PREPEND/APPEND/BEFORE/AFTER",
				"MANDATORY - TRUE/FALSE",
				"VALIDATION_TEXT",
				"SECTION_NUMBER 1 -3, USE 3 FOR SINGLE PAGE FORMS",
				"HIDDEN QUESTION - TRUE/FALSE [optional]",
				"PREFIL VALUE - TEXT/JS VARIABLE/JS FUNCTION ... [optional]",
				"DROPDOWN - Object [optional]"
			],
			[
				"QUESTION_NUMBER",
				"QUESTION_CODE",
				"QUESTION_LABEL",
				"SELECTOR_NAME",
				"PREPEND/APPEND/BEFORE/AFTER",
				"MANDATORY - TRUE/FALSE",
				"VALIDATION_TEXT",
				"SECTION_NUMBER 1 -3, USE 3 FOR SINGLE PAGE FORMS",
				"HIDDEN QUESTION - TRUE/FALSE [optional]", 
				"PREFIL VALUE - TEXT/JS VARIABLE/JS FUNCTION ... [optional]",
				"DROPDOWN - Object [optional]"
			]
		]
	
	Example:
	========
	
	var ssdifCampaignValues=new Array();
	ssdifCampaignValues['submit_destinationId']='2';
	ssdifCampaignValues['submit_campaignId']='101';
	ssdifCampaignValues['submit_redirect']='/some/url';
	ssdifCampaignValues['AlternateSubmitAction'] =  '/onlinePurchase/purchase/';
	ssdifCampaignValues['ContactWithHonda/CampaignDivision']='C';
	ssdifCampaignValues['ContactWithHonda/ActivityType']='M';
	ssdifCampaignValues['ContactWithHonda/SequenceNumber']='1038';
	ssdifCampaignValues['ContactWithHonda/CellRef']='00';
	ssdifCampaignValues['ContactWithHonda/OutboundMedium']='W';
	ssdifCampaignValues['ContactWithHonda/DealerCode']='ARN377';
	ssdifCampaignValues['SetDealerCodeByPostcode']=true;
	ssdifCampaignValues['ContactWithHonda/CRCode']='AB04';
	ssdifCampaignValues]'ContactWithHonda/Comment']='Used Cars Callback';
	ssdifCampaignValues['CustomComment'] = "Civic 3.9% Offer";
	ssdifCampaignValues['VisibleComment'] = 150;
	ssdifCampaignValues['VisibleCommentLabel'] = "Please enter a comment";
	ssdifCampaignValues['ContactWithHonda/DataSource']='01';
	ssdifCampaignValues['ContactWithHonda/OutboundExecution']='A';
	ssdifCampaignValues['ContactWithHonda/ContactType']='L';
	ssdifCampaignValues['ContactWithHonda/ResponseType']='A';
	ssdifCampaignValues['ContactWithHonda/ResponseStatus']='V';
	ssdifCampaignValues['ContactWithHonda/InboundExecution']='X';
	ssdifCampaignValues['TouchClarity_Logging_Code']='/cars/insight/update/done';
	ssdifCampaignValues['MultipageTracking'] = true;
	ssdifCampaignValues['MultipageTrackingURL']='/cars/insight/update/page';
	ssdifCampaignValues['Telephone_Mandatory']=true;
	ssdifCampaignValues['Email_Mandatory']=true;
	ssdifCampaignValues['ENewsletter_Hidden']=true;
	ssdifCampaignValues['Dream_Magazine']=true;
	ssdifCampaignValues['DateOfBirth']=true;
	ssdifCampaignValues['SMSNumber']=true;
	ssdifCampaignValues['PlannedCar1']=true;
	ssdifCampaignValues['PlannedCar2']=true;
	ssdifCampaignValues['CurrentCar']=true;
	ssdifCampaignValues["ReplacementDate"] = true;
	ssdifCampaignValues['MinimalForm']=true;
	ssdifCampaignValues['ContactTime']=true;
	ssdifCampaignValues['SetProspectInterestCarDetails'] = 'FR-V,MPV,5,Manual,Diesel';
	ssdifCampaignValues['SetProspectInterestCarDetailsById'] = '10413|10729|10127,10128';	
	ssdifCampaignValues['RunAfterValidation'] = 'doSomethingElse()';
	ssdifCampaignValues['HiddenSubmit'] = true;
	ssdifCampaignValues['HideAddress'] = true;
	ssdifCampaignValues['RunAfterSubmit']='runSomethingNow()';
	ssdifCampaignValues['UsedCars']= 'FR-V,MPV,Manual,Diesel,RN05CCT';
	ssdifCampaignValues['FadeForm']=true;
	ssdifCampaignValues['RegLookup']="#ContactWithHonda\\/Questions_104\\/Responses\\/ResponseText";
	ssdifCampaignValues['OnlineOrder'] = "006,EC2100,1,garden,lawnmowers,/garden/_assets/transforms/proceed.xsl";
	ssdifCampaignValues['Brochures'] = ["CARS",["CRZ,JAZZ"]] or ["CARS",["CRZ","JAZZ"]]
	ssdifCampaignValues['CustomQuestions'] = [
												[
													"99",
													"QC099",
													"What is your favourite colour?",
													"DIV_PlannedCar2",
													"AFTER",
													true,
													"Please enter your favourite colour",
													"2", 
													false, 
													getFavColour(),
													{
														"red": "#FF0000",
														"green": "#00FF00",
														"blue": "#0000FF",
														"name": "value"
													}
												],
										      	[
										      		"190",
										      		"QC176",
										      		"How large is your fleet?",
										      		"DIV_DateOfBirth",
										      		"BEFORE",
										      		false,
										      		"",
										      		"3", 
										      		true, 
										      		"5 cars",
										      		{
										      			"1 car" : "A",
										      			"2-50 cars" : "B",
										      			"More than 50" : "C"
										      		}
										      	]
											 ];
	*/

	
	// Variables for SSDIFF JavaScript
	var formName = 'ssdifEntryForm';
	var QASAddressList = 'dAddressList';
	var defaultComment = 'Digital Platform SSDIF';
	var SECTION_ONE_VALIDATED = false;
	var SECTION_TWO_VALIDATED = false;
	var ssdifOriginal; // used for storing a backup of the form HTML in order for it to be reloaded if the options array changes.

	$(document).ready(function(){
		ssdifInit();
		if(typeof(ssdifMultipageTracking) !== "undefined" && ssdifMultipageTracking.test()) {
			ssdifMultipageTracking.init(); // This needs to be called AFTER the ssdif init statement, see note in function
		}
	});
	
	function ssdifInit(){
		$('#ssdifFormContainer.ssdifVisible').remove();
		$('#ssdifFormContainer').show().addClass("ssdifVisible");
		ssdifOriginal = $('#ssdifFormContainer').html(); // create back up of form.
		ssdifSetup();
	}
	
	function ssdifSetup() {
		$('#ssdifFormContainer').children().unbind();	
		$('#ssdifFormContainer').html(ssdifOriginal); // reload form from original backup
		$('#submit_redirect').val(window.location);
		
		// Refresh the Preferred method of contact - this is for Product Panels
		fillPrefMethodOfContact();

		var lovArray = [];	

		/***********************************************/
		/**************  Mandatory Values  *************/
		/***********************************************/
		
		// Initialise Campaign Values
		$('#submit_destinationId').val(ssdifCampaignValues["submit_destinationId"]);
		$('#submit_campaignId').val(ssdifCampaignValues["submit_campaignId"]);
		
		$('#ContactWithHonda\\/CampaignDivision').val(ssdifCampaignValues["ContactWithHonda/CampaignDivision"]);
		$('#ContactWithHonda\\/ActivityType').val(ssdifCampaignValues["ContactWithHonda/ActivityType"]);
		$('#ContactWithHonda\\/SequenceNumber').val(ssdifCampaignValues["ContactWithHonda/SequenceNumber"]);
		$('#ContactWithHonda\\/CellRef').val(ssdifCampaignValues["ContactWithHonda/CellRef"]);
		$('#ContactWithHonda\\/OutboundMedium').val(ssdifCampaignValues["ContactWithHonda/OutboundMedium"]);
		$('#ContactWithHonda\\/DataSource').val(ssdifCampaignValues["ContactWithHonda/DataSource"]);
		$('#ContactWithHonda\\/OutboundExecution').val(ssdifCampaignValues["ContactWithHonda/OutboundExecution"]);
		$('#ContactWithHonda\\/ResponseType').val(ssdifCampaignValues["ContactWithHonda/ResponseType"]);
		$('#ContactWithHonda\\/ResponseStatus').val(ssdifCampaignValues["ContactWithHonda/ResponseStatus"]);
		$('#ContactWithHonda\\/InboundExecution').val(ssdifCampaignValues["ContactWithHonda/InboundExecution"]);	
			
		// Initialise Contact Date
		$('#ContactWithHonda\\/ContactDate').val(getCurrentDate(true,true,true));
		
		/***********************************************/
		/***********  Mandatory Values - END ***********/
		/***********************************************/
		
		/***********************************************/
		/**************  Optional Values  **************/
		/***********************************************/
		
		// Check for submit_redirect
		if(arrayTest(ssdifCampaignValues["submit_redirect"])) { 
			$('#submit_redirect').val(ssdifCampaignValues["submit_redirect"]);	

			if(ssdifCampaignValues["submit_redirect"] == '<REMOVE>') $('#submit_redirect').remove();
		}

		// Check for AlternateSubmitAction
		if(arrayTest(ssdifCampaignValues["AlternateSubmitAction"])) $('#ssdifEntryForm').attr("action",ssdifCampaignValues["AlternateSubmitAction"]);
		
		// Check for ContactWithHonda/DealerCode
		if(arrayTest(ssdifCampaignValues["ContactWithHonda/DealerCode"])) $('#ContactWithHonda\\/DealerCode').val(ssdifCampaignValues["ContactWithHonda/DealerCode"]);
		
		// Check for ContactWithHonda/CRCode
		if(arrayTest(ssdifCampaignValues["ContactWithHonda/CRCode"])) $('#ContactWithHonda\\/CRCode').val(ssdifCampaignValues["ContactWithHonda/CRCode"]);	
		
		// Check for ContactWithHonda/ContactType
		if(arrayTest(ssdifCampaignValues["ContactWithHonda/ContactType"])) $('#ContactWithHonda\\/ContactType').val(ssdifCampaignValues["ContactWithHonda/ContactType"]);
		
		// Check for ContactWithHonda/Comment
		if(arrayTest(ssdifCampaignValues["ContactWithHonda/Comment"])) $('#ContactWithHonda\\/Comment').val(ssdifCampaignValues["ContactWithHonda/Comment"]);
		
		// Check for VisibleComment
		if(arrayTest(ssdifCampaignValues["VisibleComment"])) { 
			$('#DIV_Comment').removeClass("defaultHIDE");
			
			if (arrayTest(ssdifCampaignValues["VisibleCommentLabel"])) 	$('#DIV_Comment label').text(ssdifCampaignValues["VisibleCommentLabel"]);
			
			$('#charsRemaining').html('You have ' + (parseInt(ssdifCampaignValues["VisibleComment"],10) - $(this).val().length) + ' characters remaining');

			$('#X_Comment').livequery('keyup', function() {
				if($(this).val().length > parseInt(ssdifCampaignValues["VisibleComment"],10)){
		            $(this).val($(this).val().substr(0, parseInt(ssdifCampaignValues["VisibleComment"],10)));
					alert("Sorry, this must be less than " + ssdifCampaignValues["VisibleComment"] + " characters");
		        }
				$(this).parent().find('#charsRemaining').html('You have ' + (parseInt(ssdifCampaignValues["VisibleComment"],10) - $(this).val().length) + ' characters remaining');
			});
		}
        
		// Check for Telephone_Mandatory
		$('#phonenumberLabel, #telephonePrefLabel').appendStar(arrayTest(ssdifCampaignValues["Telephone_Mandatory"]));
		
		// Check for Email_ Mandatory
		$('#emailLabel, #enewsHeading, #emailPrefHeading').appendStar(arrayTest(ssdifCampaignValues["Email_Mandatory"]));
		
		// Check for ENewsletter_Hidden
		if(arrayTest(ssdifCampaignValues["ENewsletter_Hidden"])) { 
			$('#DIV_ENews').addClass("defaultHIDE");
			$('#SubjectPrefs_1\\/PrefSuppType_Yes').attr("checked","checked");
			$('#SubjectPrefs_1\\/SubjectPrefValue').removeAttr("disabled");
		}
		
		// Check for Dream Magazine
		if(arrayTest(ssdifCampaignValues["Dream_Magazine"])) { 
			$('#DIV_DreamMagazineOptIn').removeClass("defaultHIDE");
		}
		
		// Check for DateOfBirth
		if(arrayTest(ssdifCampaignValues["DateOfBirth"])) { 
			initDateOfBirth("#X_birthDay","#X_birthMonth","#X_birthYear",18);
			$('#DIV_DateOfBirth').removeClass("defaultHIDE");
		}
		
		// Check for SMSNumber
		if(arrayTest(ssdifCampaignValues["SMSNumber"])) { 
			$('#DIV_SMSNumber').removeClass("defaultHIDE");
			$('#CommPrefs_2\\/PrefSuppType').removeAttr("disabled");
			$('#CommPrefs_2\\/CommPrefValue').removeAttr("disabled");
		}
		
		// Check for PlannedCar1 or PlannedCar2
		if(arrayTest(ssdifCampaignValues["PlannedCar1"]) || arrayTest(ssdifCampaignValues["PlannedCar2"])) { 
			$("#DIV_PlannedPurchaseDate #plannedPurchaseDateTitle").after($('#DIV_PlannedPurchaseDate_Independent').html());
			$('#DIV_PlannedPurchaseDate_Independent').empty();
			$('#DIV_PlannedCar1, .DIV_PlannedCar1, #DIV_PlannedPurchase').removeClass("defaultHIDE");
			initMonth($('#X_plannedPurchaseMonth'));
			initYearList('#X_plannedPurchaseYear',0,7,true);

			$('#ContactWithHonda\\/ProspectInterest\\/CorporatePrivateUser_Private, #ContactWithHonda\\/ProspectInterest\\/CorporatePrivateUser_Company').livequery('click', function() {
				toggleCompany('ContactWithHonda/ProspectInterest/CorporatePrivateUser','DIV_PrivateCorporateProspect_Company','ContactWithHonda\\/Questions_10\\/Responses\\/ResponseText','ContactWithHonda\\/Questions_10\\/QuestionCode')
			});
		}
		
		// Check for PlannedCar2
		if(arrayTest(ssdifCampaignValues["PlannedCar2"])) { 
			$('#DIV_PlannedCar2').removeClass("defaultHIDE");
			lovArray[lovArray.length] = new Array('281',$("#" + formName + " #ContactWithHonda\\/Questions_11\\/Responses\\/Response").get(0));
			lovArray[lovArray.length] = new Array('70',$("#" + formName + " #ContactWithHonda\\/ProspectInterest\\/CarData\\/FuelType").get(0));
		}
		
		// Check for CurrentCar
		if(arrayTest(ssdifCampaignValues["CurrentCar"])) { 
			
			
			$('#DIV_CurrentCar, .DIV_CurrentCar').removeClass("defaultHIDE");
			// Make & Model
			lovArray[lovArray.length] = new Array('219',$("#" + formName + " #CurrentProduct\\/CarData\\/Brand").get(0));
			$('#CurrentProduct\\/CarData\\/Brand').livequery('change', function() {
				updateMakeModel("#CurrentProduct\\/CarData\\/Brand","#CurrentProduct\\/CarData\\/ModelGroup");
			});
			
			// Registration Year
			initYearList("#CurrentProduct\\/RegYear",-30,30,false);
			
			// Private / Company
			$('#CurrentProduct\\/RetailCorporate_Private, #CurrentProduct\\/RetailCorporate_Company').livequery('click', function() {
				toggleCompany('CurrentProduct/RetailCorporate','DIV_PrivateCorporateCurrentCar_Company','ContactWithHonda\\/Questions_9\\/Responses\\/ResponseText','ContactWithHonda\\/Questions_9\\/QuestionCode')
			});

			// Ownership start date					
			initMonth($('#X_currentCarOwnershipStartMonth'),true);
			initYearList('#X_currentCarOwnershipStartYear',-30,30,false,true);
			
			if (arrayTest(ssdifCampaignValues["ReplacementDate"])) {
				// Replacement Date
				$("#DIV_ReplacementDate").show();
				initMonth($('#X_currentCarReplacementDateMonth'), true);
				initYearList('#X_currentCarReplacementDateYear', 0, 7, true);
			}
			
			if(arrayTest(ssdifCampaignValues.CurrentInsurance)) {
				$("#DIV_CurrentInsurance").show();
				initMonth($('#X_currentCarInsuranceDateMonth'), true);
				initYearList('#X_currentCarInsuranceDateYear', 0, 7, true);
			}
			
		}
		
		// Check for MinimalForm - look for [MinimalForm] for other exclusions
		if(arrayTest(ssdifCampaignValues["MinimalForm"])) { 
			$('#DIV_Address, #DIV_PrefContactMethod, #DIV_Telephone, #contactDetailsHeader, #contactPreferencesHeader, #DIV_DPAPostTelephone').css('display','none');			
			$('#X_CommPrefs_4\\/PrefSuppType, #CommPrefs_4\\/CommPrefValue, #CommPrefs_4\\/PrefSuppType, #X_CommPrefs_5\\/PrefSuppType, #CommPrefs_5\\/CommPrefValue, #CommPrefs_5\\/PrefSuppType').attr("disabled","disabled");
						
		}
		
		// Check for ContactTime		
		if(arrayTest(ssdifCampaignValues["ContactTime"])) {
			$('#DIV_ContactTime').removeClass("defaultHIDE");
		}

		// Check for HideAddress
		if(arrayTest(ssdifCampaignValues["HideAddress"])) {
			$('#DIV_Address, #DIV_DPAPost').css('display','none');
			$('#Entity\\/PrefContactMedium option[value="M"]').remove();
			$('#X_CommPrefs_4\\/PrefSuppType, #CommPrefs_4\\/CommPrefValue, #CommPrefs_4\\/PrefSuppType').attr("disabled","disabled");
		}
		
		// Check for CustomQuestions
		if(arrayTest(ssdifCampaignValues["CustomQuestions"])) { 
			$.each(ssdifCampaignValues["CustomQuestions"], function( intIndex, questionArray ){				
				
				var questionContentArray = []; 
				
				// Only add the label if it isn't hidden.
				if (!questionArray[8]) {
					questionContentArray.push('<label for="ContactWithHonda/Questions_'+questionArray[0]+'/Responses/ResponseText" class="ssdifLabel">'+questionArray[2]);
					if(questionArray[5]) { // is it required?
						questionContentArray.push("*"); 
					}
					questionContentArray.push('</label>');
				}
				
				var elementName = "ContactWithHonda/Questions_"+questionArray[0]+"/Responses/ResponseText";
				
				// Check for the dropdown options
				if (arrayTest(questionArray[10])) {
					questionContentArray.push('<select name="' + elementName + '" id="' + elementName + '" >');
					for (var option in questionArray[10]) {
						questionContentArray.push('<option value="' + questionArray[10][option] + '"');
						// Allow for default selection.
						if (arrayTest(questionArray[9]) && questionArray[9] == questionArray[10][option]) {
							questionContentArray.push(' selected="selected"');
						}
						questionContentArray.push('>' + option + '</option>');
					}
					questionContentArray.push("</select>");
					
				}
				else {
				
					questionContentArray.push('<input name="' + elementName + '" id="' + elementName + '" ');
					
					// Allow for hidden inputs
					if (questionArray[8]) {
						questionContentArray.push('type="hidden"');
					}
					else {
						questionContentArray.push('type="text"');
					}
					
					// Allow for prefilled values
					if (arrayTest(questionArray[9])) {
						questionContentArray.push(' value="' + questionArray[9] + '" ');
					}
					
					questionContentArray.push('class="ssdifEntry ssdifInput"/>');
				}
				
				// Add in the question code, to identify what the question actually is...
				questionContentArray.push('<input name="ContactWithHonda/Questions_'+questionArray[0]+'/QuestionCode" id="ContactWithHonda/Questions_'+questionArray[0]+'/QuestionCode" value="'+questionArray[1]+'" type="hidden"/>');	
				
				// Add in wrapper & combine the array.
				questionContent = '<div id="CustomQuestionWrapper_'+questionArray[0]+'" class="customQuestionWrapper">'+questionContentArray.join("")+'</div>';
				
				switch(questionArray[4]) {
					case "PREPEND": {
						$(questionArray[3]).prepend(questionContent);
						break;
					}
					case "APPEND": {
						$(questionArray[3]).append(questionContent);
						 break;				
					}
					case "BEFORE": {
						$(questionArray[3]).before(questionContent);
						break;
					}
					case "AFTER": {
						$(questionArray[3]).after(questionContent);
						break;
					}			
				}			
			});			
		}

		// Check for and set up RegLookup.
		if(arrayTest(ssdifCampaignValues["RegLookup"])) {
			if (typeof(regLookup) !== "undefined") {
				regLookup.init(ssdifCampaignValues["RegLookup"]);
			}
		}
		// Check for OnlineOrder			
		if(arrayTest(ssdifCampaignValues["OnlineOrder"])) {
		    var onlineOrderArray = ssdifCampaignValues["OnlineOrder"].split(",");
		    var builder = [];
		    
			builder.push(['<input id="OnlineOrder/Genpo" name="OnlineOrder/Genpo" value="', onlineOrderArray[0], '" type="hidden"/>'].join(''));
			builder.push(['<input id="OnlineOrder/Product" name="OnlineOrder/Product" value="', onlineOrderArray[1], '" type="hidden"/>'].join(''));
			builder.push(['<input id="OnlineOrder/OrderType" name="OnlineOrder/OrderType" value="', onlineOrderArray[2], '" type="hidden"/>'].join(''));
			builder.push(['<input id="OnlineOrder/Division" name="OnlineOrder/Division" value="', onlineOrderArray[3], '" type="hidden"/>'].join(''));
			builder.push(['<input id="OnlineOrder/Segment" name="OnlineOrder/Segment" value="', onlineOrderArray[4], '" type="hidden"/>'].join(''));
			builder.push(['<input id="X_proceedPageXslPath" name="X_proceedPageXslPath" value="', onlineOrderArray[5], '" type="hidden"/>'].join(''));
			
			$("#ssdifEntryForm").append(builder.join(''));
		}
		
		if (arrayTest(ssdifCampaignValues["DynamicCampaignId"])) ssdifDynamicCampaignId();

		if(arrayTest(ssdifCampaignValues["Brochures"])) {
			if(!arrayTest(ssdifCampaignValues["PlannedCar1"]) || !arrayTest(ssdifCampaignValues["PlannedCar2"])) {
				$("#DIV_Brochure_PlannedPurchaseDate #brochurePlannedPurchaseDateTitle").after($('#DIV_PlannedPurchaseDate_Independent').html());
				$('#DIV_PlannedPurchaseDate_Independent').empty();
				initMonth($('#X_plannedPurchaseMonth'));
				initYearList('#X_plannedPurchaseYear',0,7,true);
				$("#brochurePlannedPurchaseDateTitle").appendStar(true);
				$("#DIV_Brochure_PlannedPurchaseDate").removeClass("defaultHIDE");
			}			
		}
								
		/***********************************************/
		/***********  Optional Values - END  ***********/
		/***********************************************/
		
		lovArray[lovArray.length] = new Array('TITLE',$("#" + formName + " #X_title").get(0));
		lovService(true,lovArray);	
		
		// Multi-page functions
		$("#ssdifSectionOne .nextButtonDiv .nextButton").click(function() {
			if(!validateSectionOne()) return false;
			
			SECTION_ONE_VALIDATED = true;

			$("#ssdifSectionOne").fadeOut(500, function() {
				if(arrayTest(ssdifCampaignValues["CurrentCar"])) { 
					$("#ssdifSectionTwo").fadeIn(500)
				} else {
					$("#ssdifSectionThree").fadeIn(500);
				}
			});	
		});
		
		$("#ssdifSectionTwo .nextButtonDiv .nextButton").click(function() {
			if(!validateSectionTwo()) return false;
		
			SECTION_TWO_VALIDATED = true;
		
			$("#ssdifSectionTwo").fadeOut(500, function() {
				$("#ssdifSectionThree").fadeIn(500);
			});	
		});
		
		$("#ssdifSectionTwo .prevButtonDiv .prevButton").click(function() {
			$("#ssdifSectionTwo").fadeOut(500, function() {
				$("#ssdifSectionOne").fadeIn(500);
			});	
		});
		
		$("#ssdifSectionThree .prevButtonDiv .prevButton").click(function() {
			$("#ssdifSectionThree").fadeOut(500, function() {
				if(arrayTest(ssdifCampaignValues["CurrentCar"])) { 
					$("#ssdifSectionTwo").fadeIn(500);
				} else {
					$("#ssdifSectionOne").fadeIn(500);
				}
			});	
		});

		$('#' + formName).submit(function() {


		    if (!SECTION_ONE_VALIDATED) {
		        if (!validateSectionOne()) return false;
		    }

		    if (!SECTION_TWO_VALIDATED) {
		        if (!validateSectionTwo()) return false;
		    }



		    // Check for PlannedCar1 or PlannedCar2
		    if (arrayTest(ssdifCampaignValues["PlannedCar1"]) || arrayTest(ssdifCampaignValues["PlannedCar2"])) {
		        if (arrayTest(ssdifCampaignValues["PlannedCar2"])) {
		            if (!SSDIF_Validate_PlannedCar2()) return false;
		        } else {
		            if (!SSDIF_Validate_PlannedCar1()) return false;
		        }
		    }
			
			// Check for Brochure - Planned Purchase Date
			if(arrayTest(ssdifCampaignValues["Brochures"])) {
				var validatePurchaseDate = true;
				// If PlannedCar1 or PlannedCar2 then don't validate planned purchase date
				if (arrayTest(ssdifCampaignValues["PlannedCar1"]) || arrayTest(ssdifCampaignValues["PlannedCar2"])) { validatePurchaseDate = false; }
				
				if (!buildBrochureElements(ssdifCampaignValues["Brochures"][0],ssdifCampaignValues["Brochures"][1],validatePurchaseDate)) return false;				
			}

		    /** THIS SECTION TO BE LEFT AT BOTTOM */
		    $("#formWorking").removeClass("defaultHIDE");

		    // Check for SetProspectInterestCarDetails
		    if (arrayTest(ssdifCampaignValues["SetProspectInterestCarDetails"])) {
		        $("#submitButton").attr('disabled', 'disabled');


		        $("#ssdifEntryForm").append([
		            '<input id="ContactWithHonda/ProspectInterest/CarData/Doors" name="ContactWithHonda/ProspectInterest/CarData/Doors" type="hidden"/>',
		            '<input id="ContactWithHonda/ProspectInterest/CarData/Transmission" name="ContactWithHonda/ProspectInterest/CarData/Transmission" type="hidden"/>',
		            '<input id="ContactWithHonda/ProspectInterest/CarData/BodyStyle" name="ContactWithHonda/ProspectInterest/CarData/BodyStyle" type="hidden"/>'
		        ].join(''));

		        // As FuelType is asked in PlannedCar2 we need to remove it and replace it with our Hidden element, THESE SHOULD NOT BOTH BE IN THE SAME FORM
		        $("#ssdifEntryForm #ContactWithHonda\\/ProspectInterest\\/CarData\\/FuelType").remove();

		        $("#ssdifEntryForm").append('<input id="ContactWithHonda/ProspectInterest/CarData/FuelType" name="ContactWithHonda/ProspectInterest/CarData/FuelType" type="hidden"/>');
		        var carDetailsArray = ssdifCampaignValues["SetProspectInterestCarDetails"].split(",");
		        setProspectInterestCarDetails(carDetailsArray[0], carDetailsArray[1], carDetailsArray[2], carDetailsArray[3], carDetailsArray[4]);
		    }

		    // Check for SetProspectInterestCarDetailsById
		    if (arrayTest(ssdifCampaignValues["SetProspectInterestCarDetailsById"])) {
		        $("#submitButton").attr('disabled', 'disabled');

		        $("#ssdifEntryForm").append([
		            '<input id="ContactWithHonda/ProspectInterest/CarData/Doors" name="ContactWithHonda/ProspectInterest/CarData/Doors" type="hidden"/>',
		            '<input id="ContactWithHonda/ProspectInterest/CarData/BodyStyle" name="ContactWithHonda/ProspectInterest/CarData/BodyStyle" type="hidden"/>'
		        ].join(''));

		        var carDetailsArray = ssdifCampaignValues["SetProspectInterestCarDetailsById"].split("|");
		        setProspectInterestCarDetailsViaID(carDetailsArray[0], carDetailsArray[1], carDetailsArray[2]);
		    }

		    if (arrayTest(ssdifCampaignValues["UsedCars"])) {
		        $("#submitButton").attr('disabled', 'disabled');

		        // Remove all elements before re-creating them				
		        $("#ssdifEntryForm #ContactWithHonda\\/ProspectInterest\\/CarData\\/Brand").remove();
		        $("#ssdifEntryForm #ContactWithHonda\\/ProspectInterest\\/Division").remove();
		        $("#ssdifEntryForm #ContactWithHonda\\/ProspectInterest\\/ProductSegment").remove();
		        $("#ssdifEntryForm #ContactWithHonda\\/ProspectInterest\\/CorporatePrivateUser").remove();
		        $("#ssdifEntryForm #ContactWithHonda\\/ProspectInterest\\/IntentNewUsed").remove();
		        $("#ssdifEntryForm #ContactWithHonda\\/ProspectInterest\\/Relationship").remove();
		        $("#ssdifEntryForm #ContactWithHonda\\/ProspectInterest\\/CarData\\/ModelGroup").remove();
		        $("#ssdifEntryForm #ContactWithHonda\\/ProspectInterest\\/CarData\\/BodyStyle").remove();
		        $("#ssdifEntryForm #ContactWithHonda\\/ProspectInterest\\/CarData\\/Transmission").remove();
		        $("#ssdifEntryForm #ContactWithHonda\\/ProspectInterest\\/CarData\\/FuelType").remove();
		        $("#ssdifEntryForm #ContactWithHonda\\/ProspectInterest\\/SpecialRequirement_2").remove();

		        var build = [];

		        build.push('<input value="HO" name="ContactWithHonda/ProspectInterest/CarData/Brand" type="hidden"/>');
		        build.push('<input value="20" id="ContactWithHonda/ProspectInterest/Division" name="ContactWithHonda/ProspectInterest/Division" type="hidden"/>');
		        build.push('<input value="080" id="ContactWithHonda/ProspectInterest/ProductSegment" name="ContactWithHonda/ProspectInterest/ProductSegment" type="hidden"/>');
		        build.push('<input value="R" id="ContactWithHonda/ProspectInterest/CorporatePrivateUser" name="ContactWithHonda/ProspectInterest/CorporatePrivateUser" type="hidden"/>');
		        build.push('<input value="Used" id="ContactWithHonda/ProspectInterest/IntentNewUsed" name="ContactWithHonda/ProspectInterest/IntentNewUsed" type="hidden"/>');
		        build.push('<input value="O" id="ContactWithHonda/ProspectInterest/Relationship" name="ContactWithHonda/ProspectInterest/Relationship" type="hidden"/>');
		        build.push('<input id="ContactWithHonda/ProspectInterest/CarData/ModelGroup" name="ContactWithHonda/ProspectInterest/CarData/ModelGroup" type="hidden"/>');
		        build.push('<input id="ContactWithHonda/ProspectInterest/CarData/BodyStyle" name="ContactWithHonda/ProspectInterest/CarData/BodyStyle" type="hidden"/>');
		        build.push('<input id="ContactWithHonda/ProspectInterest/CarData/Transmission" name="ContactWithHonda/ProspectInterest/CarData/Transmission" type="hidden"/>');
		        build.push('<input id="ContactWithHonda/ProspectInterest/CarData/FuelType" name="ContactWithHonda/ProspectInterest/CarData/FuelType" type="hidden"/>');
		        build.push('<input id="ContactWithHonda/ProspectInterest/SpecialRequirement_2" name="ContactWithHonda/ProspectInterest/SpecialRequirement_2" type="hidden"/>');

		        $("#ssdifEntryForm").append(builder.join(''));

		        var carDetailsArray = ssdifCampaignValues["UsedCars"].split("|");

		        // Set the Registration Number
		        $("#ContactWithHonda\\/ProspectInterest\\/SpecialRequirement_2").val(carDetailsArray[4]);

		        //MODEL NAME, BODY STYLE, TRANSMISSION, FUEL TYPE, REGISTRATION NUMBER
		        setProspectInterestCarDetailsUsedCars(carDetailsArray[0], carDetailsArray[1], carDetailsArray[2], carDetailsArray[3]);
		    }

		    // Check for CustomeQuestions
		    if (!validateCustomQuestions("3")) return false;

		    // *** MAKE THIS LAST *** Check for SetDealerCodeByPostcode
		    if (arrayTest(ssdifCampaignValues["SetDealerCodeByPostcode"])) {
		        $("#submitButton").attr('disabled', 'disabled');
		        if (!getDealerByPostcode($('#Address\\/Postcode1').val() + " " + $('#Address\\/Postcode2').val(), '#ContactWithHonda\\/DealerCode')) {
		            // no dealer found for postcode
		            alert("Sorry, we couldn't find a dealer for your postcode. Please try again or call our \nCustomer Contact Centre on: 0845 200 8000");
		            $("#submitButton").removeAttr('disabled');
		            $("#formWorking").addClass("defaultHIDE");
		            return false;
		        }
		    }

		    $("#submitButton").attr('disabled', 'disabled');

		    // Check for an After Validation JavaScript function			
		    if (arrayTest(ssdifCampaignValues["RunAfterValidation"])) {
		        if (!eval(ssdifCampaignValues["RunAfterValidation"])) {
		            $("#submitButton").removeAttr('disabled');
		            $("#formWorking").addClass("defaultHIDE");
		            return false;
		        }
		    }

		    // Check for Hidden Submit
		    if (arrayTest(ssdifCampaignValues["HiddenSubmit"])) {
		        $('#' + formName).attr('target', 'ssdifHiddenIFrame');
		        $('#submit_redirect').attr("disabled", "disabled");

		        // Check for an After Hidden Submit JavaScript function			
		        if (arrayTest(ssdifCampaignValues["RunAfterSubmit"])) {
		            $('#' + formName).unbind("submit");
		            $('#' + formName).submit();
		            eval(ssdifCampaignValues["RunAfterSubmit"])
		            return false;
		        }

		        // Which animation to use to hide the form? Slide is default, but this causes a flicker when long forms are scrolled in FF.				
		        if (arrayTest(ssdifCampaignValues["FadeForm"]) && ssdifCampaignValues["FadeForm"] === true) {
		            $('#ssdifFormContainer').fadeOut(800);
		        } else {
		            $('#ssdifFormContainer').slideUp(800);
		        }
		    }

		    if (arrayTest(ssdifCampaignValues["TouchClarity_Logging_Code"])) { tc_log(ssdifCampaignValues["TouchClarity_Logging_Code"]); }
		    return true;
		});
	}
	
	function validateSectionOne() {
		if(!SSDIF_Validate_Title()) return false;
		
		if(!SSDIF_Validate_Forename_Surname()) return false;
		
		// [MinimalForm] EXCLUDE
		if(!arrayTest(ssdifCampaignValues["MinimalForm"])) { 
			if (!ssdifCampaignValues['HideAddress']) {
				if(!SSDIF_Validate_Address()) return false;		
			}
		}
		
		// Check for DateOfBirth
		if(arrayTest(ssdifCampaignValues["DateOfBirth"])) { 
			if(!SSDIF_Validate_Date_Of_Birth()) return false;
		}
		
		// [MinimalForm] EXCLUDE
		if(!arrayTest(ssdifCampaignValues["MinimalForm"])) { 
			if(!SSDIF_Validate_Preferred_Method_Contact()) return false;
		}
		
		// Check for Telephone_Mandatory
		if(arrayTest(ssdifCampaignValues["Telephone_Mandatory"])) { 
			if(!SSDIF_Validate_Mandatory_Telephone()) return false;
			if(!SSDIF_Validate_Mandatory_Telephone_Number_Type()) return false;
		} else {			
			if(!SSDIF_Validate_Telephone_Number_Type()) return false;
			if(!SSDIF_Validate_Telephone()) return false;
		}
		
		// Check for SMSNumber
		if(arrayTest(ssdifCampaignValues["SMSNumber"])) { 
			if(!SSDIF_Validate_SMS()) return false;
		}
		
		// Check for Email Mandatory
		if(arrayTest(ssdifCampaignValues["Email_Mandatory"])) { 
			if(!SSDIF_Validate_Email_Mandatory()) return false;		
		} else {
			if(!SSDIF_Validate_Email_Optional()) return false;		
		}
		
		// Check for Email Opt-in
		if(!SSDIF_Validate_Email_Optin()) return false;			
		
		// Only validate email newsletter if it's not hidden
		if(!arrayTest(ssdifCampaignValues["ENewsletter_Hidden"])) { 
			if(!SSDIF_Validate_Email_Newsletter_Optin()) return false;	
		}
	
		// Check for Dream Magazine
		if(arrayTest(ssdifCampaignValues["Dream_Magazine"])) { 
			if(!SSDIF_Validate_Dream_Magazine_Optin()) return false;	
		}

		// Check for ContactTime
		var comment = $('#ContactWithHonda\\/Comment');
		
		if(arrayTest(ssdifCampaignValues["ContactTime"])) {
			if(!SSDIF_Validate_Contact_Time()) { 
				return false;
			} else {					
				if(comment.val() == defaultComment) {
					comment.val("Contact Preference: " + $('#X_contactTime').find(":selected").val());
				} else {
					comment.val(comment.val() + " Contact Preference: " + $('#X_contactTime').find(":selected").val());
				}
			}			
		}
		
		// Check for CustomComment
		if (arrayTest(ssdifCampaignValues["CustomComment"])) {
		    
			if(comment.val() == defaultComment) {
				comment.val(ssdifCampaignValues["CustomComment"]);
			} else {
				comment.val(comment.val() + " " + ssdifCampaignValues["CustomComment"]);
			}
		}
		
		// Check for VisibleComment
		if(arrayTest(ssdifCampaignValues["VisibleComment"])) {

			if(comment.val() == defaultComment) {
				comment.val($("#X_Comment").val().replace(/\n/g," ").replace(/\£/g,"gbp").replace(/&/g,"and"));
			} else {
				comment.val(comment.val() + " " + $("#X_Comment").val().replace(/\n/g," ").replace(/\£/g,"gbp").replace(/&/g,"and"));
			}
		}
		
		// Check for CustomeQuestions
		if(!validateCustomQuestions("1")) return false;	
		
		return true;
	}
	
	function validateSectionTwo() {
		// Check for CurrentCar
		if(arrayTest(ssdifCampaignValues["CurrentCar"])) { 				
			if(!SSDIF_Validate_CurrentCar()) return false;				
		}
		
		// Check for CustomeQuestions
		if(!validateCustomQuestions("2")) return false;
			
		return true;
	}
	
	
	// 30/06/2010 uirwg: moved to ssdifUtils
	/*function arrayTest(arrayElement) {
		if(typeof(arrayElement) == 'undefined') return false;
		if(arrayElement == "") return false;
		
		return true;
	}*/
	
	// Use sectionNumber of 3 for all Single page questions, otherwise you sectionNumber 1 - 3 for Multi-page forms
	function validateCustomQuestions(sectionNumber) {
		if(arrayTest(ssdifCampaignValues["CustomQuestions"])) { 
			
			var validationError = false;
			
			$.each(ssdifCampaignValues["CustomQuestions"], function( intIndex, questionArray ){
			
				if(questionArray[7] = sectionNumber) {
					if(questionArray[5]) {
						alert(questionArray[6]);
						validationError = true;
						return false;			
					} else {
						disableEmptyOptionalQuestions(questionArray[0]);
					}
				}
			});
			
			if(validationError) { return false; } else { return true; }
		} else {
			return true;
		}
	}

		ssdifMultipageTracking = {
		// Tracking should be sent in accordance with the page view model:
		// Every time a different page of the form is displayed a tracking request should be sent
		// To avoid duplicate calls on the first page, the page number is not sent if it = 1.
		bindNextElements: "",
		bindPrevElements: "",
		pageText: "page",
		init: function(){
			// These bind functions need to occur AFTER the bind that triggers the validation, since we use the output of that validation below.
			this.bindNextElements = $("button.nextButton");
			this.bindNextElements.click(function(){
				ssdifMultipageTracking.track("next");
			});
			this.bindPrevElements = $("button.prevButton");
			this.bindPrevElements.click(function(){
				ssdifMultipageTracking.track("prev");
			});
		},
		test: function(){
			return (typeof(ssdifCampaignValues) === "object" 
					&& ssdifCampaignValues['MultipageTracking'] === true 
					&& typeof(ssdifCampaignValues['MultipageTrackingURL']) !== "undefined");
		},
		track: function(dir){
			var pageNo = this.getPage(dir); // Gets current page number, returns -1 if validation failed
			if (pageNo !== -1) {
				// Adjust pageNo to get the number of the page that will be shown:
				if (dir === "next") {
					pageNo++;
				} else if (dir === "prev") {
					pageNo--;
				}
				url = ssdifCampaignValues['MultipageTrackingURL'];
				if (pageNo !== 1) { // The first page can't have the page number on it (to make the logging call consistent with the automatic initial call)
					url = url + this.pageText + pageNo
				}
				doLogging(url); // Uses all tracking functions;
			}	
		},
		getPage: function(dir){
			var pageNo, validated;
			switch($("#ssdifEntryForm>div:visible").attr("id")) {
				case "ssdifSectionOne":
				    pageNo = 1;
					validated = SECTION_ONE_VALIDATED; // Use global variable to get validation step.
					break;
				case "ssdifSectionTwo":
				    pageNo = 2;
					validated = SECTION_TWO_VALIDATED;
					break;
				case "ssdifSectionThree":
				    pageNo = 3;
					validated = true; // N/A
					break;
			}
			if (validated || dir === "prev") { // ignore validation state of current page if going back a step.
				return pageNo;
			} else {
				return -1;
			}
		}
	};
