/**
 * sp_paf
 * Handles the request and processsing of post code data
 * Now will only request post code data if the code is identified
 * as a post code, else it will automaticially drop down the 
 * addresss form.
 */
// holds an instance of XMLHttpRequest
var SPLxmlHttp = SPLcreateXmlHttpRequestObject();

//
var basePath = "/sp";

// creates an XMLHttpRequest instance
function SPLcreateXmlHttpRequestObject() {
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  
  // this should work for all browsers except IE6 and older
  try {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e) {
    // assume IE6 or older
    var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
                                    'MSXML2.XMLHTTP.5.0',
                                    'MSXML2.XMLHTTP.4.0',
                                    'MSXML2.XMLHTTP.3.0',
                                    'MSXML2.XMLHTTP',
                                    'Microsoft.XMLHTTP');
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) {
      try { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
  // return the created object or display an error message
  if (!xmlHttp) {
    alert("Error creating the XMLHttpRequest object.");
  }
  else { 
    return xmlHttp;
  }
}


// function called when the state of the HTTP request changes
function SPLhandleRequestStateChange() {
  try {
	  // when readyState is 4, we are ready to read the server response
	  if (SPLxmlHttp.readyState == 4) {
	    // continue only if HTTP status is "OK"
	    if (SPLxmlHttp.status == 200) {
	      try {
	    	  // do something with the response from the server
	    	  SPLhandleServerResponse();
	      }
	      catch(e) {
	    	  //display error message
	    	  //alert("Error reading the response: " + e.toString());
	      }
	    } 
	    else {
	      // display status message
	      alert("There was a problem retrieving the data:\n" + SPLxmlHttp.statusText);
	    }
	  }
   }
   catch(e) {
	   //ignore
   }
}

/**
 * 
 * @param postcode
 * @return
 */
function SPLGetAddressData(postcode) {
	//validate the postcode first
	/*
	var re = new RegExp("(^gir\s0aa$)|(^[a-pr-uwyz]((\d{1,2})|([a-hk-y]\d{1,2})|(\d[a-hjks-uw])|([a-hk-y]\d[abehmnprv-y]))\s\d[abd-hjlnp-ux-z]{2}$)");
	var m = postcode.match(re);
	if(m == null) {
		if (Drupal.SPPayments == 'order-occ') {
			addElement("search-area1", "That is not a post code, please enter your full address");
			$('#address-slider1').slideDown(200);
		} 
		else {
			addElement("search-area", "That is not a post code, please enter your full address");
			$('#address-slider').slideDown(200);
		}
		return;
	}
	*/
	
	//depending on the form, hide the relevent visible form
	if (Drupal.SPPayments == 'order-occ') {
		$('#address-slider1:visible').slideUp(200);
	} else {
		$('#address-slider:visible').slideUp(200);
	}
	
	if (SPLxmlHttp) {
		//try to connect to the server
		try {
			//initiate reading a file from the server
			base = "http://" + location.hostname + basePath;
			SPLxmlHttp.open("GET", base+"/js/paf1/" + escape(postcode), true);
			SPLxmlHttp.onreadystatechange = SPLhandleRequestStateChange;
			SPLxmlHttp.send(null);
		}
		//display the error in case of failure
		catch (e) {
			//alert("Can't connect to server:\n" + e.toString());
			//Suppress error, since can be cause by two calls at once
		}
	}
} 

/**
 * 
 * @param AddressCombo
 * @return
 */
function SPLAddressChange(AddressCombo) {
	if (SPLxmlHttp) {
		try {
			base = "http://"+location.hostname + basePath;
			SPLxmlHttp.open("GET", base+"/js/paf2/" + AddressCombo.options[AddressCombo.selectedIndex].value, true);
			SPLxmlHttp.onreadystatechange = SPLhandleRequestStateChange;
			SPLxmlHttp.send(null);
		}
		catch (e) {
			//alert("Can't connect to server:\n" + e.toString());
			//Suppress error, since can be cause by two calls at once
		}
	}
 
	if (Drupal.SPPayments == 'order-occ') {
		$("#search-area1").slideUp(200);
	} 
	else {
		$("#search-area").slideUp(200);
	}   
} 

/**
 * IE7 compatible
 * @param parent
 * @param content
 * @return
 */
function addElement(parent, content) {
	var newdiv = document.createElement("div");
	newdiv.innerHTML = content;
	var container = document.getElementById(parent);
	while(container.hasChildNodes()){
		container.removeChild(container.lastChild);
	}
	container.appendChild(newdiv);
	$("#" + parent).show();
}
 
/**
 * 
 * @return
 */
function SPLhandleServerResponse() {
	var Credits="", 
		COMP="", 
		LINE1="",
		LINE2="",
		LINE3="",
		TOWN="",
		COUNTY="",
		POSTCODE="",
		COUNTRY="",
		MultiLineAddress="";
	var XMLresponse = SPLxmlHttp.responseText;
  
	//if we get a select then display it
	if (XMLresponse.indexOf("</select>")>0) {
		if (Drupal.SPPayments == 'order-occ') {
			addElement("search-area1", "<label style='font-weight: bold'>Please select your address:</label><br/>" + XMLresponse);
		} 
		else {
			addElement("search-area", "<label style='font-weight: bold'>Please select your address:</label><br/>" + XMLresponse);
		}
	}
	else {	
		//handle errors
		if (XMLresponse.indexOf("Cannot find Postcode") != -1) {
			if (Drupal.SPPayments == 'order-occ') {
				addElement("search-area1", "Postcode not found. Please ensure you've entered it correctly.");
			} 
			else {
				addElement("search-area", "Postcode not found. Please ensure you've entered it correctly.");
			}
		} 
		else if (XMLresponse.indexOf("<line1>")==-1) {
			if (Drupal.SPPayments == 'order-occ') {
				addElement("search-area1", "No data. Please ensure to enter correct postcode.");
			} 
			else {
				addElement("search-area", "No data. Please ensure to enter correct postcode.");
			}
		}
		//handle complete address
		else {
			var xmlResponse = SPLxmlHttp.responseXML;
			xmlRoot = xmlResponse.documentElement;

			if (xmlRoot.getElementsByTagName("credits_display_text").item(0).firstChild) {
				Credits = xmlRoot.getElementsByTagName("credits_display_text").item(0).firstChild.data ;
			}

			if (xmlRoot.getElementsByTagName("organisation").item(0).firstChild) {
				COMP = xmlRoot.getElementsByTagName("organisation").item(0).firstChild.data;
			}

			if (xmlRoot.getElementsByTagName("line1").item(0).firstChild) {
				LINE1 = xmlRoot.getElementsByTagName("line1").item(0).firstChild.data;
			}

			if (xmlRoot.getElementsByTagName("line2").item(0).firstChild) {
				LINE2 = xmlRoot.getElementsByTagName("line2").item(0).firstChild.data;
			}

			if (xmlRoot.getElementsByTagName("line3").item(0).firstChild) {
				LINE3 = xmlRoot.getElementsByTagName("line3").item(0).firstChild.data;
			}

			if (xmlRoot.getElementsByTagName("town").item(0).firstChild) {
				TOWN = xmlRoot.getElementsByTagName("town").item(0).firstChild.data;
			}

			if (xmlRoot.getElementsByTagName("county").item(0).firstChild) {
				COUNTY = xmlRoot.getElementsByTagName("county").item(0).firstChild.data;
			}

			if (xmlRoot.getElementsByTagName("postcode").item(0).firstChild) {
				POSTCODE = xmlRoot.getElementsByTagName("postcode").item(0).firstChild.data;
			}

			if (xmlRoot.getElementsByTagName("country").item(0).firstChild) {
				COUNTRY = xmlRoot.getElementsByTagName("country").item(0).firstChild.data;
			}
		 
			//populate the form
			if (Drupal.SPPayments == 'order-occ') {
				$("#edit-sp-payments-organisation1").val(COMP);
				$("#edit-sp-payments-postcode1").val(POSTCODE);
				$("#edit-sp-payments-address11").val(LINE1);
				$("#edit-sp-payments-address21").val(LINE2);
				$("#edit-sp-payments-address31").val(LINE3);
				$("#edit-sp-payments-town1").val(TOWN);
				$("#edit-sp-payments-county1").val(COUNTY);
				$("#edit-sp-payments-country1").val(COUNTRY);
				
				$('#address-slider1:hidden').slideDown(200);
			} 
			else {
				$("#edit-profile-organisation").val(COMP);
				$("#edit-profile-postcode").val(POSTCODE);
				$("#edit-profile-address-line1").val(LINE1);
				$("#edit-profile-address-line2").val(LINE2);
				$("#edit-profile-address-line3").val(LINE3);
				$("#edit-profile-town").val(TOWN);
				$("#edit-profile-county").val(COUNTY);
						
				$("#edit-sp-payments-organisation").val(COMP);
				$("#edit-sp-payments-postcode").val(POSTCODE);
				$("#edit-sp-payments-address1").val(LINE1);
				$("#edit-sp-payments-address2").val(LINE2);
				$("#edit-sp-payments-address3").val(LINE3);
				$("#edit-sp-payments-town").val(TOWN);
				$("#edit-sp-payments-county").val(COUNTY);
				$("#edit-sp-payments-country").val(COUNTRY);
				
				$('#address-slider:hidden').slideDown(200);
			}
	  
			// Multi line
			if (COMP!="") {MultiLineAddress = MultiLineAddress  + COMP + "\n"}
			if (LINE1!="") {MultiLineAddress = MultiLineAddress + LINE1 + "\n"}
			if (LINE2!="") {MultiLineAddress = MultiLineAddress + LINE2 + "\n"}
			if (LINE3!="") {MultiLineAddress = MultiLineAddress + LINE3 + "\n"}
			if (TOWN!="") {MultiLineAddress = MultiLineAddress + TOWN + "\n"}
			if (COUNTY!="") {MultiLineAddress = MultiLineAddress + COUNTY + "\n"}
			if (POSTCODE!="") {MultiLineAddress = MultiLineAddress + POSTCODE + "\n"}
			if (COUNTRY!="") {MultiLineAddress = MultiLineAddress + COUNTRY + "\n"}
			document.getElementById("memo").value = MultiLineAddress;
		}
	}
}

 

