var xmlHttp;

function showLocations(str)
{ 
	if (str.length != 4 && str.length != 0) {
		return;
	}
	
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
 	{
 		alert ("Browser does not support HTTP Request");
 		return;
 	}
	var url="/locations/fetch_by_postcode";
	url=url+"?postcode="+str;
	url=url+"&sid="+Math.random();
	xmlHttp.onreadystatechange=stateChanged ;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function stateChanged_new() 
{ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 	{ 
 		document.getElementById("PropertyCityId").innerHTML=xmlHttp.responseText;
		alert('New location added');
 	}
}

function stateChanged() 
{ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 	{ 
//		alert("setting to:" + xmlHttp.responseText)
		var location = document.getElementById("PropertyCityId");
		location.options.length = 0;		
		var arr_locations = xmlHttp.responseText.split("\n");		
		for(i=0; i < arr_locations.length - 1; i++) {			
			arr_location = arr_locations[i].split("|");
			location.options[location.options.length] = new Option(arr_location[1],arr_location[0]);
		}
 	}
}

function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
 	{
 		// Firefox, Opera 8.0+, Safari
 		xmlHttp=new XMLHttpRequest();
 	}
	catch (e)
 	{
 		//Internet Explorer
 		try
  		{
  			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  		}
 		catch (e)
  		{
  			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
 	}
	return xmlHttp;
}

function showHide_NewLocation()
{
	if (document.getElementById('PropertyLocationAdd').style.display == 'none') {
		document.getElementById('PropertyLocationAdd').style.display = 'block';
		document.getElementById('PropertyLocationAddLink').style.display = 'none';		
	}
	else {
		document.getElementById('PropertyLocationAdd').style.display = 'none';		
		document.getElementById('PropertyLocationAddLink').style.display = 'block';		
	}
}

function save_NewLocation() {

	var postcode = document.getElementById('PropertyPostcode').value;
	var location = document.getElementById('PropertyLocation').value;
	if (postcode == "" || location == "") {
		alert('You must enter a postcode and location.');
		return;
	}
	else {
		if (!confirm('Are you sure you want to add this location ?')) {
			return;
		}
	}	
	
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
 	{
 		alert ("Browser does not support HTTP Request");
 		return;
 	}
	var url="/locations/add_by_postcode";
	url=url+"?postcode="+postcode+"&location="+location;
	url=url+"&sid="+Math.random();
	xmlHttp.onreadystatechange=stateChanged_new;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
