/*! This file takes a vehicle registration number, passes it to a web service that returns the vehicles' details */
// Notes: 
// 	1) this only caters for one instance of the lookup occuring on each page.
//	2)	this version doesn't cater the Current Car section of the SSDIF forms yet - it only accepts text boxes as the target for autocompletion. 

// Default Data, change in regMaps.responseOutput if you need to.

if (typeof(regMaps) === "undefined") { // check if it already exists
	regMaps = {};
}
regMaps.responseOutputDefault = [ // Defaults to Current Car lookup.
	// ["xml","html", "default"]
	["make","#CurrentProduct\\/CarData\\/Brand"], // the human friendly make
	["custom_field_make_code",""], 	// the machine friendly make
	["model","#CurrentProduct\\/CarData\\/ModelGroup"], // human friendly make
	["custom_field_model_code",""], // the machine friendly make
	["body",""], // Doors 
	["engine_size",""], // Engine
	["transmission",""], // Transmission
	["fuel",""], // Fuel Type
	["keeper_start_date","#X_currentCarOwnershipStartMonth"], // Ownership Start date (MM & YYYY)
	["first_registered","#CurrentProduct\\/RegYear"] // First Registration Date (YYYY)
];

regLookup = {
	/* OLD TEST URL: serviceURL: "https://www.mycarcheck.com/feed/getxml", // test URL: https://www.mycarcheck.com/feed/getxml?username=hicklinslade&mode=test&vrm=rv59eyz
	serviceParams: {
		username: "hicklinslade",
		// key: "", // Not needed in Test mode?
		mode: "test", // either test or live. TODO: NEEDS CHANGING BEFORE GO LIVE	
		vrm: "REPLACEWITHREGSTRING" // This is the vehicle registration... For testing, use: rv59eyz
	}, */
	currentLookups: 0, // Used inconjunction with the maxLookups below.
	maxLookups: 3, // Specified the maximum number of registration lookups per page load.
	serviceURL: "https://feed.cdlvis.com/feed/getxml",
	serviceParams: {
		username: "hondauk",
		mode: "test", // This should be 'live' when the site is out of testing
		key: "JUD4B8DEM",
		vrm: "REPLACEWITHREGSTRING"
	},
	previousRegString: "", // This is used to prevent duplicate lookups.
	proxyURL: "/_assets/behaviour/loader.asp", // To facilitate cross domain AJAX requests, we need to proxy them via a server-side script.
	proxyParams: {
		type: "xml",
		url: "REPLACEWITHSERVICEURL" //This string gets replaced with the service URL
	},
	statusIndicator: "",
	buttonHTML: '<div id="regLookupWrapper"><a style="margin:10px 10px 10px 115px;" id="regLookupGo" class="callToAction" href="#findvehicle">Find Vehicle</a><img style="display:none;margin-top:10px;" id="regLookupIndicator" src="/_assets/presentation/toolbox/loading-small.gif"></div>',
	init: function(element) {
		$element = $(element); // Passed variable should refer to the input field for the registration, it may or may not already be a jQuery object.
		
		// Insert "Find Car button"
		$element.after(this.buttonHTML);
		
		// Bind click event
		$("#regLookupGo").bind("click", function(e){
			regString = $element.val();
			
			if (regString !== regLookup.previousRegString) { // Prevent duplicate lookups (which cost money) by comparing against the previous string and ignoring the request if they match.
				regLookup.doLookup(regString);
				regLookup.previousRegString = regString; 
			}
			e.preventDefault();
		});
		
	},

	doLookup: function(regString) {
		if (++regLookup.currentLookups <= regLookup.maxLookups) { // increments the current lookup number and then compares it to the maximum look up number. If current lookup is more than the max permissable lookup, then it errors.
			// Validation (use SSDIF if available)
			if (!regLookup.validate(regString)) {
				return false;
			}
			// Build URL
			var serviceURL = encodeURIComponent(regLookup.serviceURL + "?" + $.param(regLookup.serviceParams).replace("REPLACEWITHREGSTRING", regString));
			var params = "?" + $.param(regLookup.proxyParams).replace("REPLACEWITHSERVICEURL", serviceURL);
			var url = regLookup.proxyURL + params;
			
			// Generate Call
			$("#regLookupIndicator").show(); // display indicator
			$.ajax({
				type: "GET",
				url: url,
				contentType: "xml",
				success: function(responseXML){
					if (responseXML !== "") { //TODO: Catch other errors here to save time when parsing? Errors are caught later, it'd just bring the catch forward
						// Parse Response
						regLookup.parseResponse(responseXML);
						$("#regLookupIndicator").hide(); // hide indicator
					}
					else {
						regLookup.error();
						$("#regLookupIndicator").hide(); // hide indicator
					}
				},
				error: function(response){
					regLookup.error();
					$("#regLookupIndicator").hide(); // hide indicator
				}
			});
		} else {
			regLookup.error("Please enter the vehicle's details manually.");
			return false;
		}
	},
	
	validate: function(regString) {
		if ($.isFunction(SSDIF_Validate_Registration)) {
			return SSDIF_Validate_Registration(regString); // if the SSDIF Validation function exists, use it (that way we get the benefit of the latest updates to SSDIF)
		} else {
			// This is a duplicate of the code used in SSDIF. It's included here in case of use outside of an SSDIF form.
			var regExPattern=/^([a-zA-Z0-9]{2,7})$/; // This matches the data capture guidelines as of Feb 2010 (max 7 chars alphanumeric)
			if(regString.match(regExPattern) === null) {
				alert("Please enter a valid registration");
				return false;
			}
			return true;
		}
	},

	parseResponse: function(responseXML){
		//console.log("parsing response");
		// Read Response -> Output mapping data file
		if (typeof(regMaps) !== "undefined") {
			var dataMap = regMaps.responseOutput || regMaps.responseOutputDefault;
		} else {
			return false;
		}
		//console.log("data map loaded");
		var elements = dataMap.length - 1;
		var counter = 0; // See if any records have been updated.
		for (var i = 0; i <= elements; i++) {
			//console.log("data map element");
			if (dataMap[i].length === 2) {
				//var xmlElement = $(responseXML).find(dataMap[i][0]); // input (response)
				var xmlElement = $(dataMap[i][0], responseXML); // input (response)
				var htmlElement = $(dataMap[i][1]); // output (Output)
				// Verify Data
				var xmlSelector = dataMap[i][0];
				if ( // This is complicated if statement, so could probably have been written better...
						( // Check EITHER:
							dataMap[i][0] !== "" && // check that neither input element is a blank string 
							dataMap[i][1] !== "" && // (blank strings match the document object and trick the next test, which we don't want.)
							xmlElement.length === 1 && 
							htmlElement.length === 1 && // and that both selectors match one and only one element.
							xmlElement.text() !== "" // check that the xmlElement contains some text
						) 
					) {
					
					var data;
					
					// Output data to fields.
					data = xmlElement.text();						

					// Our data supplier has heavyoil instead of diesel in their data, we want diesel in ours.
					if (data === "HEAVY OIL") {
						data = "DIESEL";
					}

					// Write Data and update counter if successful
					if (regLookup.writeData(htmlElement, data)) {
						counter++; // Yes! Data has been found and written successfully
					}
				} 
			}
			else { // Data isn't in the correct format (responseOutput is malformed)
				regLookup.error();
			}
		}
		if (counter === 0) {// If counter hasn't been updated (i.e. no data was written to the DOM)
			//console.log("no data written");
			regLookup.error();
		}
	},
	
	writeData: function(htmlElement, data){
		//console.log("Writing Data: "+data + " Element");
		//console.log(htmlElement);
		// Check type. Options are:
		//					- Regular input box
		//					- Regular Dropdown
		//					- Month/Year Dropdown
		//					- Current Car Dropdown
		
		if (htmlElement.is(":text")) { // Regular input
			//console.log("text");
			htmlElement.val(data);
		} else if (htmlElement.is("select")) { // dropdown
			//console.log("select");
			var text = htmlElement.find(":first-child").text().toLowerCase();
			if (text === "month" || text === "year") { // month/year
				//console.log("month or year");
				// We have a year or month dropdown. See if we can find a year or month drop down associated.
					var yearElement = htmlElement.parent().find("option:contains(Year)").parents("select");
					var monthElement = htmlElement.parent().find("option:contains(Month)").parents("select");
				
				// parse data to isolate month and year
					// date format is: YYYY-MM-DD, dates that are not applicable to a given reg are sent as 0000-00-00.
					if (data !== "0000-00-00" && data !== "") {
						var date = data.split("-");
						var year = date[0];
						var month = date[1];
						// populate month and year dropdowns
						populateDropdown(monthElement, month); // set month
						populateDropdown(yearElement, year); // set year
					}
			} else if (htmlElement.attr("id") === "CurrentProduct/CarData/ModelGroup") { // Current Car Model Dropdown
				//console.log("dropdown")
				// Trigger AJAX lookup to populate model options tags (assume SSDIF)
				updateMakeModel($("#CurrentProduct\\/CarData\\/Brand"), htmlElement, data); // SSDIF internal function
				// populate dropdown
				
			} else { // Regular
				//console.log("regular dropdown")
				// populate dropdown
				populateDropdown(htmlElement, data);
			}
		} else {
			//regLookup.error("unmatched type");
			return false;
		}
		return true;
	},
	
	error: function(message) {
		if (typeof(message) === "undefined") {
			message = "We were unable to find your vehicle's details"; // Standard generic error message.
		}
		alert(message);
	}
};