/* address lookup for AU and NZ
Australian addresses:
street
suburb, state postcode

enter suburb --> suggest suburb, state, postcode (handleSuburbCompletionRequest)

NZ addresses:
urban addresses
street
suburb
town/city postcode

enter suburb --> suggest suburb, state, postcode (handleSuburbCompletionRequest)
enter state --> if suburb is empty, suggest state, postcode (handleStateCompletionRequest)

rural addresses
enter suburb + state --> suggest state, postcode (handleStateCompletionRequest)

Comments have been added to functions modified/created for ePages

*/

//init
var WebServerScriptUrlSSL=window.location.protocol+'//'+window.location.host+window.location.pathname;
var browserDetected = identifyBrowser();
addLoadListener(initAutoComplete);
// this will be shown in status/error messages. It is "state" for "AU", "town/city" for "NZ"
var stateLbl	= "state";
var lastAddressType;

var debug = 1;

// This will disable the return key in the City and State fields to prevent users from accidentaly submitting
// the form when choosing a City in the drop-down
function stopRKey(evt) {
	var evt  = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	// if return key has been pressed
	if (evt.keyCode == 13) { 
 		var target			= getEventTarget(evt);
		var addressType 	= target.id.split(".");
		var addressField	= addressType[1];
 		if (addressField == "City" || addressField == "State") {
 			blurAutoComplete(evt);
 			return false;
 		}
	}
	return true;
}

document.onkeypress = stopRKey;

// This will add the events to the relevant fields if they exist and initialise variables
function initAutoComplete()
{
 	// add id attributes to all the relevant input fields
 	var aInputNames	= new Array("City", "State", "Zipcode", "CountryID", 
		"ShippingCity", "ShippingState", "ShippingZipcode", "ShippingCountryID");

	var aInputIDs	= new Array("BillingAddress.City", "BillingAddress.State", "BillingAddress.ZipCode", "BillingAddress.CountryID",
		"ShippingAddress.City", "ShippingAddress.State", "ShippingAddress.ZipCode", "ShippingAddress.CountryID");
	
	
	for (var i=0; i<aInputNames.length; i++) {
		addIdAttribute(aInputNames[i], aInputIDs[i]);
	}
	
	
	// add span elements to all the relevant fields to show status/error
	addFieldStatus("BillingAddress.City");
	addFieldStatus("BillingAddress.State");
	addFieldStatus("ShippingAddress.City");
	addFieldStatus("ShippingAddress.State");
	
	if (document.getElementById("BillingAddress.City") ) {
 		var countryID = document.getElementById("BillingAddress.CountryID").value;
		// 554 is NZ, 36 is AU
		if (countryID == "554") {
			stateLbl = "town/city";
		}
		// add method when form is submitted
		addOnSubmit("BillingAddress.City");
	}
	
 	if (document.getElementById("BillingAddress.City") ) {
		var suburb = document.getElementById("BillingAddress.City");
		suburb.setAttribute("autocomplete", "off");
		attachEventListener(suburb, "keydown", keydownAutoComplete, false);
		attachEventListener(suburb, "blur", blurAutoComplete, false);
		checkUrbanRural("BillingAddress"); 
   }
	
  if (document.getElementById("ShippingAddress.City") ) {
	var  shipSuburb = document.getElementById("ShippingAddress.City");
	// if delivery address is visible
	if (shipSuburb.disabled==false) {
		shipSuburb.setAttribute("autocomplete", "off");
		attachEventListener(shipSuburb, "keydown", keydownAutoComplete, false);
		attachEventListener(shipSuburb, "blur", blurAutoComplete, false);
		checkUrbanRural("ShippingAddress"); 
	}
  }	

   if (document.getElementById("BillingAddress.State") ) {
		var  state = document.getElementById("BillingAddress.State");
		if (state.disabled==false) {
			state.setAttribute("autocomplete", "off");
			attachEventListener(state, "keydown", keydownAutoComplete, false);
			attachEventListener(state, "blur", blurAutoComplete, false);
		}
	}
	
	if (document.getElementById("ShippingAddress.State") ) {
		var  shipState = document.getElementById("ShippingAddress.State");
		if (shipState.disabled==false) {
			shipState.setAttribute("autocomplete", "off");
			attachEventListener(shipState, "keydown", keydownAutoComplete, false);
			attachEventListener(shipState, "blur", blurAutoComplete, false);
		}
	}
  
  return true;
}

function setLastAddressType(addressType)
{
  	if (!addressType) {
		addressType = "BillingAddress";
	}
  	lastAddressType = addressType;
    return true;
}

function keydownAutoComplete(event)
{
  if (typeof event == "undefined")
  {
    event = window.event;
  }

  switch(event.keyCode)
  {
    case 9:     // tab
    case 13:    // enter
    case 16:    // shift
    case 17:    // ctrl
    case 18:    // alt
    case 20:    // caps lock
    case 27:    // esc
    case 33:    // page up
    case 34:    // page down
    case 35:    // end
    case 36:    // home
    case 37:    // left arrow
    case 39:    // right arrow
      break;

    case 38:    // up arrow

      var target = getEventTarget(event);
	 // addressType can be billing or shipping
	 var addressType	= getAddressType(target);

      var autoCompleteDropdown = document.getElementById(addressType + "_autoCompleteDropdown");
      if (autoCompleteDropdown != null)
      {
        var childLis = autoCompleteDropdown.childNodes;
        var selected = false;

        for (var i = 0; i < childLis.length; i++)
        {
          if (childLis[i].className == "hover")
          {
            selected = true;

            if (i > 0)
            {
              childLis[i].className = "";
              childLis[i - 1].className = "hover";

              target.value = childLis[i - 1].firstChild.nodeValue;
            }

            break;
          }
        }

        if (!selected)
        {
          childLis[0].className = "hover";

          target.value = childLis[0].firstChild.nodeValue;
        }
      }

      stopDefaultAction(event);

      break;

    case 40:    // down arrow
      var target = getEventTarget(event);
	 // addressType can be billing or shipping
	  var addressType	= getAddressType(target);
      var autoCompleteDropdown = document.getElementById(addressType + "_autoCompleteDropdown");

      if (autoCompleteDropdown != null)
      {
        var childLis = autoCompleteDropdown.childNodes;
        var selected = false;

        for (var i = 0; i < childLis.length; i++)
        {
          if (childLis[i].className == "hover")
          {
            selected = true;

            if (i < childLis.length - 1)
            {
              childLis[i].className = "";
              childLis[i + 1].className = "hover";

              target.value = childLis[i + 1].firstChild.nodeValue;
            }

            break;
          }
        }

        if (!selected)
        {
          childLis[0].className = "hover";

          target.value = childLis[0].firstChild.nodeValue;
        }
      }

      stopDefaultAction(event);

      break;

    case 8:     // backspace
    case 46:    // delete
	var addressType	= getAddressType(getEventTarget(event));
	var eventID		= getEventID(getEventTarget(event));
		
      if (typeof autoCompleteTimer != "undefined")
      {
        clearTimeout(autoCompleteTimer);
      }
	 // this will check/change the urban/rural label if needed
    // checkUrbanRural(addressType);
     autoCompleteTimer = setTimeout("generateDropdown(false,'" + addressType + "','" + eventID  + "')", 800);

      break;

    default:

      if (typeof autoCompleteTimer != "undefined")
      {
        clearTimeout(autoCompleteTimer);
      }

      var target = getEventTarget(event);
  	 // addressType can be billing or shipping
	  var addressType	= getAddressType(target);

	  var eventID		= getEventID(getEventTarget(event));
      var inputRanges = "false";

      if (typeof target.createTextRange != "undefined" || typeof target.setSelectionRange != "undefined")
      {
        inputRanges = "true";
		autoCompleteTimer = setTimeout("generateDropdown(true,'" + addressType + "','" + eventID  + "')", 800);

      }
	  else {
		autoCompleteTimer = setTimeout("generateDropdown(false,'" + addressType + "','" + eventID  + "')", 800);
	  }
  }

 return true;
}

// generate the drop-down with suburb, state, postcode
function handleSuburbCompletionRequest( Doc, doAutoComplete, addressType) {
		  closeDropdown(addressType);
		  setLastAddressType(addressType);
		  document.getElementById(addressType + ".City_status").innerHTML ="";

          // Grab the response text and kill any trailing whitespace
          var completion 	= Doc.replace(/\s*$/g, "");
          // completion is suburb,state,postcode
          // replace all ',' with '|'
		  completion 	= Doc.replace(/,/g, "|");
		  var aSuburbs		= completion.split("\n");
		  // Last element is empty so we must get rid of it
		  aSuburbs.pop();
		  
       	  var input = document.getElementById(addressType + ".City");
       	 
		  var newUl = document.createElement("ul");
		  newUl.setAttribute("id", addressType + "_autoCompleteDropdown");
		  newUl.autoCompleteInput = input;
		  newUl.style.position = "absolute";
		  newUl.style.left = getPosition(input)[0] + "px";
		  newUl.style.top = getPosition(input)[1] + input.offsetHeight - 2 + "px";
		  newUl.style.width = input.offsetWidth - 3 + "px";
		  
		  // loop through the array of suburbs to add them to the drop-down (as a <li> element)
		  for (var i = 0; i < aSuburbs.length; i++) {
     			var newLi 	= document.createElement("li");
    		 	
    		 	var aSuburb	= aSuburbs[i].split("|");
    		 	// show as suburb, state postcode
    		 	newLi.appendChild(document.createTextNode(aSuburb[0] + ", " + aSuburb[1] + " " + aSuburb[2]));
     			if (browserDetected != "ie5mac") {
        			attachEventListener(newLi, "mouseover", mouseoverDropdown, false);
       				attachEventListener(newLi, "mouseout", mouseoutDropdown, false);
        			attachEventListener(newLi, "mousedown", mousedownDropdown, false);
      			}

      			newUl.appendChild(newLi);
    			
  			}
  			
  			
  			if (newUl.firstChild != null) {
   				 document.getElementsByTagName("body")[0].appendChild(newUl);
  			}

  			if (typeof doAutoComplete != "undefined" && doAutoComplete) {
    			autoComplete(addressType, "City");
  			}
  		
  		return true;

  }
  
// generate the drop-down with state, postcode
  function handleStateCompletionRequest( Doc, doAutoComplete, addressType) {
		closeDropdown(addressType);
    	setLastAddressType(addressType);

		document.getElementById(addressType + ".State_status").innerHTML ="";

		if (Doc.length) {
          // Grab the response text and kill any trailing whitespace
          var completion 	= Doc.replace(/\s*$/g, "");
		  // completion is state,postcode
          // replace all ',' with '|'
		  completion 	= Doc.replace(/,/g, "|");
		  var aStates		= completion.split("\n");
		  // Last element is empty so we must get rid of it
		  aStates.pop();
		  
       	  var input = document.getElementById(addressType + ".State");
       	 
		  var newUl = document.createElement("ul");
		  newUl.setAttribute("id", addressType + "_autoCompleteDropdown");
		  newUl.autoCompleteInput = input;
		  newUl.style.position = "absolute";
		  newUl.style.left = getPosition(input)[0] + "px";
		  newUl.style.top = getPosition(input)[1] + input.offsetHeight - 2 + "px";
		  newUl.style.width = input.offsetWidth - 3 + "px";
		  // loop through the array of states to add them to the drop-down (as a <li> element)
		  for (var i = 0; i < aStates.length; i++) {
     			var newLi 	= document.createElement("li");
    		 	
    		 	var aState	= aStates[i].split("|");
    		 	newLi.appendChild(document.createTextNode(aState[0] + " - " + aState[1]));
     			if (browserDetected != "ie5mac") {
        			attachEventListener(newLi, "mouseover", mouseoverDropdown, false);
       				attachEventListener(newLi, "mouseout", mouseoutDropdown, false);
        			attachEventListener(newLi, "mousedown", mousedownDropdown, false);
      			}

      			newUl.appendChild(newLi);
    			
  			}
  			
  			
  			if (newUl.firstChild != null) {
   				 document.getElementsByTagName("body")[0].appendChild(newUl);
  			}

  			if (typeof doAutoComplete != "undefined" && doAutoComplete) {
    			autoComplete(addressType, "State");
  			}

  		}
  		else {
  			// No state found for that suburb
  			// change style of InputBlock to show error
  			changeDialogError(addressType + ".City");
			document.getElementById(addressType + ".City_status").innerHTML = "<span class=\"status error\">Suburb <strong>" + document.getElementById(addressType + ".City").value + "</strong> not found in " + stateLbl + " <strong>" + document.getElementById(addressType + ".State").value + "</strong>: please check suburb</span>";
			document.getElementById(addressType + ".ZipCode").value = '';

		}
  		
  		
  		return true;

  }
  
// this will call the right function to generate the drop-down depending on the country
// and the information entered
function generateDropdown(doAutoComplete, addressType, eventID)
{
  closeDropdown(addressType);  
  
  // for AU: if value entered is suburb, suggest suburb, state, postcode
  if ( document.getElementById(addressType + ".CountryID").value == "36") {
		if  (eventID == addressType + ".City") {
			suggestSuburbStatePostcode(doAutoComplete, addressType, eventID);
		}
  }
 
 // for NZ
  else if ( document.getElementById(addressType + ".CountryID").value == "554") {
  	var type = document.getElementById(addressType + ".type");
  	checkUrbanRural(addressType); 

	// if address is urban
	if (type.value == 'urban') {
		// normal case: look by suburb, suggest suburb, state, postcode
		if (eventID == addressType + ".City") {
			suggestSuburbStatePostcode(doAutoComplete, addressType, eventID);
		}
		// if state has been entered AND suburb is empty (some entries have no suburb!) suggest state, postcode
		else if ( (eventID == addressType + ".State") 
					&& (!document.getElementById(addressType + ".City").value.length) ) {
			suggestStatePostcode(doAutoComplete, addressType, type, eventID)
		}
	}
	// if address is rural and state has been entered
  	else if ( (type.value == 'rural') &&  (eventID == addressType + ".State") ) {
			// check that it starts with RD before sending the request
			// indexOf should return "0" as that's where RD should start
			if (	!( document.getElementById(addressType + ".City").value.indexOf("RD ", 0)) ) {
				suggestStatePostcode(doAutoComplete, addressType, type, eventID);
  				removeDialogError(addressType + ".City");
				document.getElementById(addressType + ".City_status").innerHTML = "";

			}
			else {
				// change style of InputBlock to show error
  				changeDialogError(addressType + ".City");
				document.getElementById(addressType + ".City_status").innerHTML = "<span class=\"status error\">Rural address must be <br /> <strong>RD + rural delivery number</strong></span>";
			}
  	}
  }
		  
  return true;
}

function autoComplete(addressType, addressField)
{
  var input = document.getElementById(addressType + "." + addressField);
  var cursorMidway = false;

  if (typeof document.selection != "undefined")
  {
    var range = document.selection.createRange();

    if (range.move("character", 1) != 0)
    {
      cursorMidway = true;
    }

  }
  else if (typeof input.selectionStart != "undefined" && input.selectionStart < input.value.length)
  {
    cursorMidway = true;
  }

  var originalValue = input.value;
  var autoCompleteDropdown = document.getElementById(addressType + "_autoCompleteDropdown");
 

  if (autoCompleteDropdown != null && !cursorMidway)
  {
  	autoCompleteDropdown.firstChild.className = "hover";
    input.value = autoCompleteDropdown.firstChild.firstChild.nodeValue;

    if (typeof input.createTextRange != "undefined")
    {
      var range = input.createTextRange();
      range.moveStart("character", originalValue.length);
      range.select();
    }
    else if (typeof input.setSelectionRange != "undefined")
    {
      input.setSelectionRange(originalValue.length, input.value.length);
    }

    if (autoCompleteDropdown.childNodes.length == 1)
    {
      setTimeout("closeDropdown('" + addressType +"');", 10);
    }		
  }

  return true;
}

function mouseoverDropdown(event)
{
  if (typeof event == "undefined")
  {
    event = window.event;
  }

  var target = getEventTarget(event);
  var addressType	= getAddressType(target);

  while (target.nodeName.toLowerCase() != "li")
  {
    target = target.parentNode;
  }

  var childLis = target.parentNode.childNodes;

  for (var i = 0; i < childLis.length; i++)
  {
    childLis[i].className = "";
  }

  target.className = "hover";

  return true;
}

function mouseoutDropdown(event)
{
  if (typeof event == "undefined")
  {
    event = window.event;
  }

  var target = getEventTarget(event);
  var addressType	= getAddressType(target);

  while (target.nodeName.toLowerCase() != "li")
  {
    target = target.parentNode;
  }

  target.className = "";

  return true;
}

function mousedownDropdown(event)
{
  if (typeof event == "undefined")
  {
    event = window.event;
  }

  var target = getEventTarget(event);
  var addressType	= getAddressType(target);

  while (target.nodeName.toLowerCase() != "li")
  {
    target = target.parentNode;
  }

  target.parentNode.autoCompleteInput.value = target.firstChild.nodeValue;
 
  autoFillPostcodeAndState(addressType);

  return true;
}

function blurAutoComplete(event)
{
  if (typeof autoCompleteTimer != "undefined")
  {
    clearTimeout(autoCompleteTimer);
  }

  var target	= getEventTarget(event);
  var addressType = getAddressType(target);
  checkUrbanRural(addressType);
  closeDropdown(addressType);
  autoFillPostcodeAndState(addressType);

  return true;
}

function closeDropdown(addressType)
{
  var autoCompleteDropdown = document.getElementById(addressType + "_autoCompleteDropdown");

  if (autoCompleteDropdown != null)
  {
    autoCompleteDropdown.parentNode.removeChild(autoCompleteDropdown);
  }

  return true;
}

function addLoadListener(fn)
{
  if (typeof window.addEventListener != 'undefined')
  {
    window.addEventListener('load', fn, false);
  }
  else if (typeof document.addEventListener != 'undefined')
  {
    document.addEventListener('load', fn, false);
  }
  else if (typeof window.attachEvent != 'undefined')
  {
    window.attachEvent('onload', fn);
  }
  else
  {
    var oldfn = window.onload;
    if (typeof window.onload != 'function')
    {
      window.onload = fn;
    }
    else
    {
      window.onload = function()
      {
        oldfn();
        fn();
      };
    }
  }
}

function attachEventListener(target, eventType, functionRef, capture)
{
  if (typeof target.addEventListener != "undefined")
  {
    target.addEventListener(eventType, functionRef, capture);
  }
  else if (typeof target.attachEvent != "undefined")
  {
    target.attachEvent("on" + eventType, functionRef);
  }
  else
  {
    eventType = "on" + eventType;

    if (typeof target[eventType] == "function")
    {
      var oldListener = target[eventType];

      target[eventType] = function()
      {
        oldListener();

        return functionRef();
      }
    }
    else
    {
      target[eventType] = functionRef;
    }
  }

  return true;
}

function getEventTarget(event)
{
  var targetElement = null;

  if (typeof event.target != "undefined")
  {
    targetElement = event.target;
  }
  else
  {
    targetElement = event.srcElement;
  }

  while (targetElement.nodeType == 3 && targetElement.parentNode != null)
  {
    targetElement = targetElement.parentNode;
  }

  return targetElement;
}

// the relevant fields in the form always start with BillingAddress. or ShippingAddress.
function getAddressType(target) {
	var addressType 	= target.id.split(".");
//	alert(addressType);
	return addressType[0];
}

function getEventID(target) {
	var eventID 	= target.id;

	return eventID;
}

function stopDefaultAction(event)
{
  event.returnValue = false;

  if (typeof event.preventDefault != "undefined")
  {
    event.preventDefault();
  }

  return true;
}

function getPosition(theElement)
{
  var positionX = 0;
  var positionY = 0;

  while (theElement != null)
  {
    positionX += theElement.offsetLeft;
    positionY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }

  return [positionX, positionY];
}

function identifyBrowser()
{
  var agent = navigator.userAgent.toLowerCase();

  if (typeof navigator.vendor != "undefined" && navigator.vendor == "KDE" && typeof window.sidebar != "undefined")
  {
    return "kde";
  }
  else if (typeof window.opera != "undefined")
  {
    var version = parseFloat(agent.replace(/.*opera[\/ ]([^ $]+).*/, "$1"));

    if (version >= 7)
    {
      return "opera7";
    }
    else if (version >= 5)
    {
      return "opera5";
    }

    return false;
  }
  else if (typeof document.all != "undefined")
  {
    if (typeof document.getElementById != "undefined")
    {
      var browser = agent.replace(/.*ms(ie[\/ ][^ $]+).*/, "$1").replace(/ /, "");

      if (typeof document.uniqueID != "undefined")
      {
        if (browser.indexOf("5.5") != -1)
        {
          return browser.replace(/(.*5\.5).*/, "$1");
        }
        else
        {
          return browser.replace(/(.*)\..*/, "$1");
        }
      }
      else
      {
        return "ie5mac";
      }
    }

    return false;
  }
  else if (typeof document.getElementById != "undefined")
  {
    if (navigator.vendor.indexOf("Apple Computer, Inc.") != -1)
    {
      if (typeof window.XMLHttpRequest != "undefined")
      {
        return "safari1.2";
      }

      return "safari1";
    }
    else if (agent.indexOf("gecko") != -1)
    {
      return "mozilla";
    }
  }

  return false;
}

function autoFillPostcodeAndState(addressType) {
	if (!addressType) {
		addressType = lastAddressType;
	}
	
	
	if (addressType && document.getElementById(addressType + ".State") ) {
		var state = document.getElementById(addressType + ".State");
		
		if (! (state.value.indexOf(" - ")== -1) ) {
			var aStatePostcode	= state.value.split(" - ");
			// auto-fill postcode + state 
			if (aStatePostcode.length >= 1) {
				document.getElementById(addressType + ".ZipCode").value =  aStatePostcode[1];
				document.getElementById(addressType + ".State").value = aStatePostcode[0];
			}
		}
	
	}
	
	if (addressType && document.getElementById(addressType + ".City") ) {
		var suburb = document.getElementById(addressType + ".City");
		// suburb should be suburb, state postcode
		if (! (suburb.value.indexOf(", ")== -1) ) {
			var aStatePostcode	= suburb.value.split(", ");
			// only auto-fill postcode + state if suburb contains all three fields
			if (aStatePostcode.length >= 2) {
				var aState			= aStatePostcode[1].split(" ");
				var state = '';
				// we need to loop as state could have spaces in the name
				for (var i = 0; i < aState.length-1; i++) {
					state	+= aState[i] + " ";
				}
				//  kill any trailing whitespace
          		state 	= state.replace(/\s*$/g, "");
				// if state has spaces, postcode will be the last element in the array
				var postcode			= aState[aState.length-1];
				document.getElementById(addressType + ".ZipCode").value = postcode;
				document.getElementById(addressType + ".State").value = state;
				document.getElementById(addressType + ".City").value = aStatePostcode[0];
			}
		}
	}
		
  return true;
}

// when drop-down is changed, auto-fill with "RD " for rural addresses
// and clear state and postcode fields
function toggleUrbanRural(addressType) {
	var type = document.getElementById(addressType + ".type");
	var suburb = document.getElementById(addressType + ".City");
	
	if(type.value == "rural") {
			document.getElementById(addressType + ".City").value = "RD ";
			document.getElementById(addressType + ".City").focus();
			document.getElementById(addressType + ".State").value = "";
			document.getElementById(addressType + ".ZipCode").value = "";
			// for IE: move to the end of the field (FF does it automatically)
			if (typeof  document.getElementById(addressType + ".City").createTextRange != "undefined" ) {
				var range = document.getElementById(addressType + ".City").createTextRange();
      			range.moveStart("character", 4);
      	    }
		}
		
	if(type.value == "urban") {
			document.getElementById(addressType + ".City").value = "";
			document.getElementById(addressType + ".City").focus();
			document.getElementById(addressType + ".State").value = "";
			document.getElementById(addressType + ".ZipCode").value = "";
	}
	
	return true;
}


// when the page loads, if there is a value in suburb and it starts with "RD ", select
// "rural address" in drop-down list
function checkUrbanRural(addressType) {
	if (document.getElementById(addressType + ".typeLbl") ) {
		// if suburb field starts with RD, select "rural"
		var addressFormat = document.getElementById(addressType + ".City").value.toUpperCase();
		if (!( addressFormat.indexOf("RD", 0)) ) {
			document.getElementById(addressType + ".typeLbl").innerHTML = "Rural address";
			document.getElementById(addressType + ".type").value = "rural";
			// if no space between RD and delivery number, insert space
			if(addressFormat.indexOf(" ", 2) != 2) {
				addressFormat = "RD " + addressFormat.substring(2, addressFormat.length);
			}
			document.getElementById(addressType + ".City").value = addressFormat;
		}
		// else select "urban"
		else {
			document.getElementById(addressType + ".typeLbl").innerHTML = "Suburb";
			document.getElementById(addressType + ".type").value = "urban";
		}
	}
	return true;
}

// make the request to get back suburb,state,postcode if suburb has been entered
function suggestSuburbStatePostcode(doAutoComplete, addressType, eventID) {
	// only do if something has been entered in suburb
	 if (document.getElementById(addressType + ".City").value.length) {
		removeDialogError(addressType + ".City");
		document.getElementById(addressType + ".City_status").innerHTML = "<img src='/WebRoot/AddressLookup_images/wait.gif' alt='Looking up suburb...' />&nbsp;<span class=\"status\">Looking up suburb</span>";
	   	document.getElementById(addressType + ".State_status").innerHTML ="";

		document.getElementById(addressType + ".ZipCode").value = "";
		document.getElementById(addressType + ".State").value = "";

		var input 	=  encodeURIComponent(document.getElementById(addressType + ".City").value);
		if (document.getElementById("ObjectID")) {
			var objectid	=  encodeURIComponent(document.getElementById("ObjectID").value);
			var country	= encodeURIComponent(document.getElementById(addressType + ".CountryID").value);
			  
			makeHttpRequest("GET",WebServerScriptUrlSSL+
		'?ViewAction=GetSuburb&ObjectID='+ objectid + '&suburb=' + input + '&country=' + country,'',false, 'handleSuburbCompletionRequest', doAutoComplete, addressType );
		}
	}
	return true;
 
 }
  
// make the request to get back state,postcode
function suggestStatePostcode(doAutoComplete, addressType, type, eventID) {
	var ChangeAction = 'GetRDState';
	document.getElementById(addressType + ".State_status").innerHTML = "<img src='/WebRoot/AddressLookup_images/wait.gif' alt='Looking up state...' />&nbsp;<span class=\"status\">Looking up " + stateLbl + "</span>";
	
	// clear the postcode field
	document.getElementById(addressType + ".ZipCode").value = "";

	// only clear the suburb field is the address is urban
	if (type.value == "urban") {
		document.getElementById(addressType + ".City").value = "";
		ChangeAction = 'GetState';
	}
	
	var suburb	= encodeURIComponent(document.getElementById(addressType + ".City").value);
	var input 	=  encodeURIComponent(document.getElementById(addressType + ".State").value);
	
	if (document.getElementById("ObjectID")) {
		var objectid	=  encodeURIComponent(document.getElementById("ObjectID").value);
		var country	= encodeURIComponent(document.getElementById(addressType + ".CountryID").value);
		  
		makeHttpRequest("GET",WebServerScriptUrlSSL+
	'?ViewAction=' + ChangeAction + '&ObjectID='+ objectid + '&suburb=' + suburb + '&state=' + input + '&country=' + country,'',false, 'handleStateCompletionRequest', doAutoComplete, addressType );
	}
	return true;
}

function changeDialogError(inputid) {
	var inputBlock = document.getElementById(inputid).parentNode.parentNode;
  	inputBlock.setAttribute("class", "InputBlock DialogError"); 
	// for IE
	inputBlock.setAttribute("className", "InputBlock DialogError"); 
	document.getElementById(inputid).focus();
	return true;
}

function removeDialogError(inputid) {
	var inputBlock = document.getElementById(inputid).parentNode.parentNode;
  	inputBlock.setAttribute("class", "InputBlock"); 
	// for IE
	inputBlock.setAttribute("className", "InputBlock"); 
	return true;
}

// add id="..." attribute to input fields
function addIdAttribute(name, id) {
	if (! document.getElementById(id) ) {
		var aFields	= document.getElementsByName(name);
		if (aFields.length) {
			// there should only be one element in the array
			// if there is more we will only set the id attribute to the first element
			var field	= aFields[0];
			field.setAttribute('id', id);
		}
	}
 	return true;
 }
 
// adds <span id="..."></span> to suburb and state fields
function addFieldStatus(id) {
	if (document.getElementById(id)) {
		var container = document.getElementById(id).parentNode.parentNode;
		if (typeof container != undefined ) {
			var spanStatus	= document.createElement("span");
			spanStatus.setAttribute('id', id + "_status");
			if (container.nodeName == "TR") {
				container = document.getElementById(id).parentNode;
			}
			container.appendChild(spanStatus);
		}
	}
	return true;
}

// adds method when form is submitted so the fields are automatically filled
function addOnSubmit(id) {
	if (document.getElementById(id)) {
		var form = document.getElementById(id).form;
		form.setAttribute('onsubmit', "autoFillPostcodeAndState();");
	}
	return true;
}