// START BILLING ADDRESS LOOKUP CODE

function billingAddressesByPostcodeToPA(Key, SearchTerm, PreferredLanguage, Filter, UserName) {
    var scriptTag = document.getElementById("PCA6d35cfc188f1451f9cfdf1b5d751a716");
    var headTag = document.getElementsByTagName("head").item(0);
    var strUrl = "";

	//Build the url
    strUrl = "https://services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/Find/v1.10/json.ws?";
    strUrl += "&Key=" + encodeURI(Key);
    strUrl += "&SearchTerm=" + encodeURI(SearchTerm);
    strUrl += "&PreferredLanguage=" + encodeURI(PreferredLanguage);
    strUrl += "&Filter=" + encodeURI(Filter);
    strUrl += "&UserName=" + encodeURI(UserName);
	strUrl += "&CallbackFunction=billingAddressesByPostcodeFromPA";

	//Make the request
	if (scriptTag) {
		try {
			headTag.removeChild(scriptTag);
		} catch (e) {
			// Ignore
		}
	}
	scriptTag = document.createElement("script");
	scriptTag.src = strUrl
	scriptTag.type = "text/javascript";
	scriptTag.id = "PCA6d35cfc188f1451f9cfdf1b5d751a716";
	headTag.appendChild(scriptTag);
}

function billingAddressesByPostcodeFromPA(response) {
	//Test for an error
	if (response.length==1 && typeof(response[0].Error) != 'undefined') {
		//Show the error message
		alert(response[0].Description);
	} else {
		//Check if there were any items found
		if (response.length==0) {
			alert("Sorry, we could not find any addresses for this postcode. Please enter your address manually instead.");
		} else {
			// Populate dropdown menu with choice of addresses
			document.getElementById('postcodelookupaddresslist_b').style.display = "block";
			document.getElementById('postcodelookupaddress_b').innerHTML = "";
			document.getElementById('postcodelookupaddress_b').options.add(
				new Option("--- Please Select ---", "")
			);
			for (var i=0;i<response.length;i++) {
			    document.getElementById('postcodelookupaddress_b').options.add(
					new Option(response[i].StreetAddress + ", " + response[i].Place, response[i].Id)
				);
			}
		}
	}
}

function billingAddressByIdToPA(Key, Id, PreferredLanguage, UserName) {	
	if(Id == "") {
		clearBillingAddress();
	} else {
		var scriptTag = document.getElementById("PCAa73f9bc2b60d4e4cbd595512478a3291");
		var headTag = document.getElementsByTagName("head").item(0);
		var strUrl = "";

		//Build the url
		strUrl = "https://services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/RetrieveById/v1.10/json.ws?";
		strUrl += "&Key=" + encodeURI(Key);
		strUrl += "&Id=" + encodeURI(Id);
		strUrl += "&PreferredLanguage=" + encodeURI(PreferredLanguage);
		strUrl += "&UserName=" + encodeURI(UserName);
		strUrl += "&CallbackFunction=billingAddressByIdFromPA";
		
		//Make the request
		if (scriptTag) {
			try {
				headTag.removeChild(scriptTag);
			} catch (e) {
				//Ignore
			}
		}
		scriptTag = document.createElement("script");
		scriptTag.src = strUrl
		scriptTag.type = "text/javascript";
		scriptTag.id = "PCAa73f9bc2b60d4e4cbd595512478a3291";
		headTag.appendChild(scriptTag);
	}
}

function billingAddressByIdFromPA(response) {
    //Test for an error
    if (response.length==1 && typeof(response[0].Error) != 'undefined') {
        //Show the error message
        alert(response[0].Description);
    } else {
        //Check if there were any items found        
		if (response.length==0) {
			alert("Sorry, we could not find any addresses for this postcode. Please enter your address manually instead.");
        } else {
			document.getElementById('b_company').value = response[0].Company;
			document.getElementById('b_address1').value = response[0].Line1;
			document.getElementById('b_address2').value = response[0].Line2;
			document.getElementById('b_address3').value = response[0].Line3;
			document.getElementById('b_town').value = response[0].PostTown;
			document.getElementById('b_county').value = response[0].County;
			document.getElementById('b_postcode').value = response[0].Postcode;
			document.getElementById('b_country').value = getGSOCountryByPostcode(response[0].Postcode);
        }
    }
}

// END BILLING ADDRESS LOOKUP CODE
// START DELIVERY ADDRESS LOOKUP CODE

function deliveryAddressesByPostcodeToPA(Key, SearchTerm, PreferredLanguage, Filter, UserName) {
    var scriptTag = document.getElementById("PCA6d35cfc188f1451f9cfdf1b5d751a716");
    var headTag = document.getElementsByTagName("head").item(0);
    var strUrl = "";

	//Build the url
    strUrl = "https://services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/Find/v1.10/json.ws?";
    strUrl += "&Key=" + encodeURI(Key);
    strUrl += "&SearchTerm=" + encodeURI(SearchTerm);
    strUrl += "&PreferredLanguage=" + encodeURI(PreferredLanguage);
    strUrl += "&Filter=" + encodeURI(Filter);
    strUrl += "&UserName=" + encodeURI(UserName);
	strUrl += "&CallbackFunction=deliveryAddressesByPostcodeFromPA";

	//Make the request
	if (scriptTag) {
		try {
			headTag.removeChild(scriptTag);
		} catch (e) {
			// Ignore
		}
	}
	scriptTag = document.createElement("script");
	scriptTag.src = strUrl
	scriptTag.type = "text/javascript";
	scriptTag.id = "PCA6d35cfc188f1451f9cfdf1b5d751a716";
	headTag.appendChild(scriptTag);
}

function deliveryAddressesByPostcodeFromPA(response) {
	//Test for an error
	if (response.length==1 && typeof(response[0].Error) != 'undefined') {
		//Show the error message
		alert(response[0].Description);
	} else {
		//Check if there were any items found
		if (response.length==0) {
			alert("Sorry, we could not find any addresses for this postcode. Please enter your address manually instead.");
		} else {
			// Populate dropdown menu with choice of addresses
			document.getElementById('postcodelookupaddresslist_d').style.display = "block";
			document.getElementById('postcodelookupaddress_d').innerHTML = "";
			document.getElementById('postcodelookupaddress_d').options.add(
				new Option("--- Please Select ---", "")
			);
			for (var i=0;i<response.length;i++) {
			    document.getElementById('postcodelookupaddress_d').options.add(
					new Option(response[i].StreetAddress + ", " + response[i].Place, response[i].Id)
				);
			}
		}
	}
}

function deliveryAddressByIdToPA(Key, Id, PreferredLanguage, UserName) {	
	if(Id == "") {
		clearDeliveryAddress();
	} else {
		var scriptTag = document.getElementById("PCAa73f9bc2b60d4e4cbd595512478a3291");
		var headTag = document.getElementsByTagName("head").item(0);
		var strUrl = "";

		//Build the url
		strUrl = "https://services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/RetrieveById/v1.10/json.ws?";
		strUrl += "&Key=" + encodeURI(Key);
		strUrl += "&Id=" + encodeURI(Id);
		strUrl += "&PreferredLanguage=" + encodeURI(PreferredLanguage);
		strUrl += "&UserName=" + encodeURI(UserName);
		strUrl += "&CallbackFunction=deliveryAddressByIdFromPA";
		
		//Make the request
		if (scriptTag) {
			try {
				headTag.removeChild(scriptTag);
			} catch (e) {
				//Ignore
			}
		}
		scriptTag = document.createElement("script");
		scriptTag.src = strUrl
		scriptTag.type = "text/javascript";
		scriptTag.id = "PCAa73f9bc2b60d4e4cbd595512478a3291";
		headTag.appendChild(scriptTag);
	}
}

function deliveryAddressByIdFromPA(response) {
    //Test for an error
    if (response.length==1 && typeof(response[0].Error) != 'undefined') {
        //Show the error message
        alert(response[0].Description);
    } else {
        //Check if there were any items found        
		if (response.length==0) {
			alert("Sorry, we could not find any addresses for this postcode. Please enter your address manually instead.");
        } else {
			document.getElementById('d_company').value = response[0].Company;
			document.getElementById('d_address1').value = response[0].Line1;
			document.getElementById('d_address2').value = response[0].Line2;
			document.getElementById('d_address3').value = response[0].Line3;
			document.getElementById('d_town').value = response[0].PostTown;
			document.getElementById('d_county').value = response[0].County;
			document.getElementById('d_postcode').value = response[0].Postcode;
			document.getElementById('d_country').value = getGSOCountryByPostcode(response[0].Postcode);
        }
    }
}

// END DELIVERY ADDRESS LOOKUP CODE
// START MISC FUNCTIONS CALLED FROM BOTH

function getGSOCountryByPostcode(postcode) {
	// The Golf Shop splits UK into 3 categories:
	//		* UK (Mainland Excluding Scottish Highlands)		ID: United Kingdom
	//		* UK (Scottish Highlands)							ID: Scottish Highlands
	//		* UK Islands (Guernsey | Jersey | Isle of Man)		ID: UK Islands
	// 
	// Depending on the Postcode returned from PostcodeAnywhere, we need to decide which of these
	// categories (or Northern Ireland) the "Country" dropdown menu should display
	
	var scottishHighlandAll = new Array("HS","IV","KW");
	
	var scottishHighlandSpecific = new Array("AB30","AB31","AB32","AB33","AB34","AB35","AB36","AB37","AB38","AB44","AB45","AB46","AB47","AB48","AB49","AB50","AB51","AB52","AB53","AB54",
	"AB55","AB56","FK17","FK18","FK19","FK20","FK21","G83","PH17","PH18","PH19","PH20","PH21","PH22","PH23","PH24","PH25","PH26","PH27","PH28","PH29","PH30","PH31","PH32","PH33","PH34",
	"PH35","PH36","PH37","PH38","PH39","PH40","PH41","PH42","PH43","PH44","PH45","PH46","PH47","PH48","PH49","PH50");
	
	var islandAll = new Array("JE","GY","IM","ZE");
	
	var islandSpecific = new Array("TR21","TR22","TR23","TR24","TR25","KA27","KA28","PO30","PO31","PO32","PO33","PO34","PO35","PO36","PO37","PO38","PO39","PO40","PO41","PA20","PA21",
	"PA22","PA23","PA24","PA25","PA26","PA27","PA28","PA29","PA30","PA31","PA32","PA33","PA34","PA35","PA36","PA37","PA38","PA39","PA40","PA41","PA42","PA43","PA44","PA45","PA46",
	"PA47","PA48","PA49","PA50","PA51","PA52","PA53","PA54","PA55","PA56","PA57","PA58","PA59","PA60","PA61","PA62","PA63","PA64","PA65","PA66","PA67","PA68","PA69","PA70","PA71",
	"PA72","PA73","PA74","PA75","PA76","PA77","PA78","PA79","PA80");
	
	var nirelandAll = new Array("BT");
	
	var isScottishHighland = false;
	var isIsland = false;
	var isNireland = false;
	
	if(postcode.length > 3) {
		var startPostcode = trim(postcode.substring(0, (postcode.length - 3)));
	} else {
		var startPostcode = trim(postcode);
	}
	
	for (var i=0;i<scottishHighlandAll.length;i++) {
		if(postcode.substring(0,scottishHighlandAll[i].length) == scottishHighlandAll[i]) {
			isScottishHighland = true;
			break;
		}
	}
	for (var i=0;i<scottishHighlandSpecific.length;i++) {
		if(startPostcode == scottishHighlandSpecific[i]) {
			isScottishHighland = true;
			break;
		}
	}
	
	for (var i=0;i<islandAll.length;i++) {
		if(postcode.substring(0,islandAll[i].length) == islandAll[i]) {
			isIsland = true;
			break;
		}
	}
	for (var i=0;i<islandSpecific.length;i++) {
		if(startPostcode == islandSpecific[i]) {
			isIsland = true;
			break;
		}
	}
	
	for (var i=0;i<nirelandAll.length;i++) {
		if(postcode.substring(0,nirelandAll[i].length) == nirelandAll[i]) {
			isNireland = true;
			break;
		}
	}
	
	if(isScottishHighland) {
		return 'Scottish Highlands';
	} else if(isIsland) {
		return 'UK Islands';
	} else if(isNireland) {
		return 'Northern Ireland';
	} else {
		return 'United Kingdom';
	}
}

function clearBillingAddress() {
	document.getElementById('b_company').value = "";
	document.getElementById('b_address1').value = "";
	document.getElementById('b_address2').value = "";
	document.getElementById('b_address3').value = "";
	document.getElementById('b_town').value = "";
	document.getElementById('b_county').value = "";
	document.getElementById('b_country').value = "";
}

function clearDeliveryAddress() {
	document.getElementById('d_company').value = "";
	document.getElementById('d_address1').value = "";
	document.getElementById('d_address2').value = "";
	document.getElementById('d_address3').value = "";
	document.getElementById('d_town').value = "";
	document.getElementById('d_county').value = "";
	document.getElementById('d_country').value = "";
}

function trim(str) {
    str = str.toString();
    var begin = 0;
    var end = str.length - 1;
    while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; }
    while (end > begin && str.charCodeAt(end) < 33) { --end; }
    return str.substr(begin, end - begin + 1);
}

// END MISC FUNCTIONS CALLED FROM BOTH
