var account_code 					= 'BONAP11112';
var license_code 					= 'WM28-JM74-AB39-XY88';
var pcaServiceUrl 					= 'https://services.postcodeanywhere.co.uk/inline.aspx?'
var mb3IdPrefix 					= '';
var removalFields					= false;
var messageNoIslandPostcodesAllowed = "Unfortunately we don't deliver to the Channel Islands.\nPlease read our terms and conditions for further information.";
var disallowedPostcodes 			= new Array('je', 'gy');


/**
 *	checks the postcode: no delivery to Channel Islands
 *
 *	@param	string	str_postcode	the provided postcode
 *	@return	boolean	returnValue		true || false
 */
function checkPostcode(str_postcode) {
	var postcode = str_postcode.toLowerCase();	
	var returnValue = true;
	var postcodePrefix = postcode.substr(0, 2);
	var numberOfDisallowedPostcodes = disallowedPostcodes.length;
	for (var i = 0; i < numberOfDisallowedPostcodes; i ++) {
		if (postcodePrefix === disallowedPostcodes[i]) {
			returnValue = false;
		} // end: if
	}
	return returnValue;
} // end: function

/**
 *	initiates a call to get a selection of addresses matching to the give zipcode
 *
 *	@param	string	elementId	the id of the zipcode inputfield
 *	@return	void
 */
function pcaByPostcodeBegin(id, flag) {
	
	// start pca
	mb3IdPrefix = id;

	// switch as the new removal fields having different names/ids
	if (flag) {
		var postcode = document.getElementById(mb3IdPrefix+"[newzip]").value;
	} else {
		var postcode = document.getElementById(mb3IdPrefix+"[zip]").value;
	} // end: if

	// check postcode: no delivery to Channel Islands
	if (checkPostcode(postcode) === true) {
		var scriptTag = document.getElementById("pcaScriptTag");
	    var headTag = document.getElementsByTagName("head").item(0);
	    var strUrl = "";

		document.getElementById("pcaDivLoading"+mb3IdPrefix).style.visibility = 'visible';

		//Build the url
		strUrl = pcaServiceUrl;
		strUrl += "&action=lookup";
		strUrl += "&type=by_postcode";
		strUrl += "&postcode=" + escape(postcode);
		strUrl += "&account_code=" + escape(account_code);
		strUrl += "&license_code=" + escape(license_code);
		strUrl += "&callback=pcaByPostcodeEnd";
		
		//Make the request
		if (scriptTag) {
		    //The following 2 lines perform the same function and are interchangeable
		    headTag.removeChild(scriptTag);
		    //scriptTag.parentNode.removeChild(scriptTag);
		} // end: if

		scriptTag = document.createElement("script");
		scriptTag.src = strUrl
		scriptTag.type = "text/javascript";
		scriptTag.id = "pcaScriptTag";
		headTag.appendChild(scriptTag);
	} else {
		// display error message
		alert(messageNoIslandPostcodesAllowed);
	} // end: if
} // end: function

/**
 *	Fetches the return address data and sets them into the selectbox
 *
 *	@return	void
 */
function pcaByPostcodeEnd() {
	document.getElementById("pcaDivLoading"+mb3IdPrefix).style.visibility = 'hidden';

	//Test for an error
	if (pcaIsError) {
	    //Show the error message
	    alert(pcaErrorMessage);
	} else {

	    //Check if there were any items found
	    if (pcaRecordCount==0) {
	    	alert("Sorry, no matching items found");
	    } else {

			document.getElementById("pcaDivSelectaddress"+mb3IdPrefix).style.display = '';

			var selectaddress = document.getElementById("pcaSelectaddress"+mb3IdPrefix);

			for (i=selectaddress.options.length-1; i>=0; i--) {
				selectaddress.options[i] = null;
			} // end: for

			selectaddress.options[0] = new Option('please select');

			for (i=0; i<pca_id.length; i++) {
				selectaddress.options[selectaddress.length] = new Option(pca_description[i], pca_id[i]);
			} // end: for
	   	} // end: if
	} // end: if
} // end: function

/**
 *	initiates a call to get the address data to the selected address id
 *
 *	@param	string	id	the prefix of the input ids
 *	@return	void
 */
function pcaFetchBegin(id, flag) {


	removalFields = flag;
	mb3IdPrefix = id;
	var address_id = document.getElementById("pcaSelectaddress"+mb3IdPrefix).value;
	var scriptTag = document.getElementById("pcaScriptTag");
	var headTag = document.getElementsByTagName("head").item(0);
	var strUrl = "";

	//Build the url
	strUrl = pcaServiceUrl;
	strUrl += "&action=fetch";
	strUrl += "&id=" + escape(address_id);
	strUrl += "&account_code=" + escape(account_code);
	strUrl += "&license_code=" + escape(license_code);
	strUrl += "&style=raw";
	strUrl += "&callback=pcaFetchEnd";

	//Make the request
	if (scriptTag) {
	    //The following 2 lines perform the same function and are interchangeable
	    headTag.removeChild(scriptTag);
	    //scriptTag.parentNode.removeChild(scriptTag);
	} // end: if

	scriptTag = document.createElement("script");
	scriptTag.src = strUrl
	scriptTag.type = "text/javascript";
	scriptTag.id = "pcaScriptTag";
	headTag.appendChild(scriptTag);

	document.getElementById("pcaDivSelectaddress"+mb3IdPrefix).style.display = 'none';

} // end: if

/**
 *	Fetches the return addressdata and sets them into the address inputfields
 *
 *	@return	void
 */
function pcaFetchEnd() {
	//Test for an error
	if (pcaIsError)
	 {
	    //Show the error message
	    alert(pcaErrorMessage);
	 }
	else
	 {
		//Check if there were any items found
		if (pcaRecordCount==0) {
			alert("Sorry, no matching items found");
		} else {

			var city 		= '' + pca_post_town[0];
			var state 		= '' + pca_county[0];
			var housenumber	= '' + pca_building_number[0];

			var company		= '' + pca_organisation_name[0];

			if (pca_building_flat[0]!='') {
				var flat = '' + pca_building_flat[0];
			} else {
				var flat = '' + pca_sub_building_name[0];
			} // end: if

			var housename	= '' + pca_building_name[0];
			// build address2(in the form called housename) from company, flat and housename
			// use trim for the case that one of the fields was not set.
			var address2 	= trim(company + ' ' + (trim (flat + ' ' + housename)));

			var street1		= '' + pca_dependent_thoroughfare_name[0] + ' ' + pca_dependent_thoroughfare_descriptor[0];
			var street2		= '' + pca_thoroughfare_name[0] + ' ' + pca_thoroughfare_descriptor[0];
			var address1	= trim (trim(street1) + ' ' + trim(street2));

			// reduce string to the maxlength according to the revise
			address1 	= address1.substr(0,30);
			address2 	= address2.substr(0,45);
			housenumber = housenumber.substr(0,5);
			state 		= state.substr(0,30);
			city 		= city.substr(0,35);

			// switch as the new removal fields having different names/ids
			if (removalFields) {
				document.getElementById(mb3IdPrefix+"[newaddress2]").value 		= address2;
				document.getElementById(mb3IdPrefix+"[newhousenumber]").value 	= housenumber;
				document.getElementById(mb3IdPrefix+"[newaddress1]").value 		= address1;
				document.getElementById(mb3IdPrefix+"[newstate]").value 		= state;
				document.getElementById(mb3IdPrefix+"[newcity]").value 			= city;
			} else {
				document.getElementById(mb3IdPrefix+"[address2]").value 	= address2;
				document.getElementById(mb3IdPrefix+"[housenumber]").value 	= housenumber;
				document.getElementById(mb3IdPrefix+"[address1]").value 	= address1;
				document.getElementById(mb3IdPrefix+"[state]").value 		= state;
				document.getElementById(mb3IdPrefix+"[city]").value 		= city;
			} // end: if
		} // end: if
	} // end: if
} // end: function

/**
 *	Removes leading and trailing spaces from the given string
 *
 *	@param	string	string
 *	@return	string
 */
function trim (string) {

	return string.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
} // end: function trim


