

// ===== convert words to standard versions =====
function standardize(a) {
  for (var i=0; i<standards.length; i++) {
	if (a == standards[i][0])  {a = standards[i][1];}
  }
  return a;
}

// ===== check if two addresses are sufficiently different =====
function different(a,b) {
  // only interested in the bit before the first comma in the reply
  var c = b.split(",");
  b = c[0];
  // convert to lower case
  a = a.toLowerCase();
  b = b.toLowerCase();
  // remove apostrophies
  a = a.replace(/'/g ,"");
  b = b.replace(/'/g ,"");
  // replace all other punctuation with spaces
  a = a.replace(/\W/g," ");
  b = b.replace(/\W/g," ");
  // replace all multiple spaces with a single space
  a = a.replace(/\s+/g," ");
  b = b.replace(/\s+/g," ");
  // split into words
  awords = a.split(" ");
  bwords = b.split(" ");
  // perform the comparison
  var reply = false;
  for (var i=0; i<bwords.length; i++) {
	//GLog.write (standardize(awords[i])+"  "+standardize(bwords[i]))
	if (standardize(awords[i]) != standardize(bwords[i])) {reply = true}
  }
  //GLog.write(reply);
  return (reply);
}

/* Show a map for the user mymaps (favourites) page */
function mymap_load (lat, lng) {

	var m = eid("mymap");
	if (m != undefined && google.maps.BrowserIsCompatible()) {
		
		var point = new GLatLng(lat, lng);
		map = new GMap2(m);
		map.setCenter(point, 9);
		map.setUIToDefault();
		map.enableGoogleBar();
		bounds = new GLatLngBounds();
		bounds.extend( point );
		
		var latlang = map.getCenter(); 
		
		 gdir = new GDirections(map, document.getElementById("directions"));
		 GEvent.addListener(gdir, "load", onGDirectionsLoad);
       	 GEvent.addListener(gdir, "error", handleErrors);
	}
}
function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
}
function openWindow(marker)
{
  myPano = new GStreetviewPanorama(document.getElementById("stview"));
  var latlang = marker.getLatLng();
  myPano.setLocationAndPOV(latlang);
}
//following function used to handle the error for google map street view
function handleNoFlash(errorCode) {
  if (errorCode == 603) {
	alert("Error: Flash doesn't appear to be supported by your browser");
	return;
  }
} 
function printGoogleMapDirection(container, name)
{
	var str= Sortable.serialize( container,{ name:name} );
	if(eid("directions").innerHTML == ""){
		alert("No directions yet");
	} else {
		//generate the string below for address and than all done
		new Ajax.Request('/inc/ajax/ajax.php', {
					method: 'get',
					parameters: {
						action: 'getSerializeStr',
						str: str
					},
					onSuccess: function (r) {
						var fromAddress =  eid("fromAddress").value + "," + eid("fromSuburb").value;
						var printUrl = "http://maps.google.com/maps?f=d&source=s_d&saddr="+fromAddress+"&daddr="+r.responseText.substring(5)+"&hl=en&geocode=&mra=ls&sll=-27.563816,153.075139&sspn=0.019174,0.090895&ie=UTF8&ll=-27.466436,153.01235&spn=0.001333,0.00284&z=19&layer=c&pw=2";
						window.open(printUrl,'','width=750,height=600,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=yes,resizable=yes');
						//setDirections(r.responseText, "English");
					}
				});
	}
	
}
function addressSerialize(container, name)
{
	if(eid("fromAddress").value != "" && eid("fromSuburb").value != ""){
		var str= Sortable.serialize( container,{ name:name} );
		//generate the string below for address and than all done
		new Ajax.Request('/inc/ajax/ajax.php', {
					method: 'get',
					parameters: {
						action: 'getSerializeStr',
						str: str
					},
					onSuccess: function (r) {
						//alert(r.responseText);
						setDirections(r.responseText, "English");
					}
				});
	}
	else
	{
		alert("You must input your address and suburb!");
	}	
}
function setDirections(toAddress, locale) {
	 var fromAddress =  eid("fromAddress").value + "," + eid("fromSuburb").value;
	gdir.load("from: "+fromAddress+toAddress,
                { "locale": locale });
	 
	 eid("errorGetDirections").innerHTML = "";
	 eid("mymap").style.display = "block";
	 eid("directions").style.display = "block";
	 
}
function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
   {
	   eid("errorGetDirections").innerHTML = "Some Addresses Can Not Be Found!";
	 	//alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
   } 
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
   {
	    eid("errorGetDirections").innerHTML = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code;
   }
	
   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
   {
	   eid("errorGetDirections").innerHTML ="The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code;	
   }
	
   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
   {
	 eid("errorGetDirections").innerHTML ="The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code;
   } 
   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
   {
	   eid("errorGetDirections").innerHTML ="A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code;
   }
   else
   {
	   eid("errorGetDirections").innerHTML ="An unknown error occurred.";
   }
	   
}
/* add a garagesale to the mymap (g is a garagesale object) */
function mymap_add_garagesale (g) {
	if (map == false)
	{
		return false;
	}// map not loaded

	var html = '<div style="text-align:center"><strong>'+g.title+'</strong><br /><emphasis>'+g.address+'</emphasis><br /><br />'+g.description+'</div>';
	
	var point = new google.maps.LatLng(g.lat, g.lng);
	var marker = new google.maps.Marker(point, {title: g.title});
	markers.push({id: g.id, marker:marker});
	map.addOverlay(marker);
	GEvent.addListener(marker, "click", function () {
		marker.openInfoWindowHtml(html);
	});
	
	bounds.extend(point);
	//alert(point);
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
	//map.setCenter(new google.maps.LatLng(-25.562265014427492, 133.857421875), 3);
}

function mymap_remove_garagesale (garagesale_id) {
	for (var i=0; i<markers.length; i++) {
		if (markers[i].id == garagesale_id) {
			map.removeOverlay(markers[i].marker);
			break;
		}
	}
}

function validate_street()
{
	if(v("addr_street") == "")
	{
		alert("Street Can Not Be Blank! ");
		eid("addr_street").focus();
	}
	
}

function validate_postcode()
{
	if( v("addr_postcode") == "" || v("addr_postcode") == "" )
	{
		alert("Postcode Can Not Be Blank! Or Less Than 4 Digits ");
		eid("addr_postcode").focus();
	}
}

function isDigit(fData) 
{ 
    var reg = new RegExp("^[0-9]$"); 
    return (reg.test(fData)); 
}
function getDirections()
{
	//2, resize the map and info window
	eid("mymap").style.width = "400px";
	eid("directions").style.display = "block";
}
/*
	extract the suburb and state out of an address
	@param prefix the prefix of the form fields (street, postcode) => (suburb, state)
*/
function validate_address (prefix) 
{	
	validateAddress(prefix);
	prefixG = prefix;

}
function jShowMap(field)
{
	var address = eid(field).value;
	eid("mapTr").style.display = '';
		eid("mapExplainId").innerHTML = "We need you to confirm your address on the map. Click on the marker and then click \"This is it\" to confirm. You can drag the marker if you like.";
		initializeMapAdvertise(address+', Australia');
}

function showAddress(response)
{
		if (!response || response.Status.code != 200)
		{
			//eid('verify_message_td').style.display = "";
			//eid('verify_message').innerHTML = addressNotFoundMsg;
			eid('validedAddress').value = false;
		}
		else
		{
			var extraText = '';

			place = response.Placemark[0];
			var addressArray 	  = place.address.split(",");
			// check address to see if user input the right street name but wrong street number such as 11111111111
			var streetAddressPart = addressArray[0];
			
			var realStreetAddress = streetAddressPart.split(" ");
			
			//alert(realStreetAddress);return false;
			var realStreetNumber  = realStreetAddress[0];
			var realStreetName    = realStreetAddress[1];
			
			var tempNumber = parseInt(realStreetNumber);

			if(isNaN(tempNumber))
			{
				eid('validedAddress').value = false;
				return ;
			}
			
			var tempStreetAddressArray = eid("addr_street").value.toLowerCase().split(" ");
			if(tempStreetAddressArray.length >= 2)
			{
				//console.log(tempStreetAddressArray.join(" "));
				if(tempStreetAddressArray[1] != realStreetAddress[1].toLowerCase())
				{
					tempStreetAddressArray[1] = firstToUpper(realStreetAddress[1]);
					eid("addr_street").value = tempStreetAddressArray.join(" ");
					
				}
			}
			
			var postCodePart 	  = addressArray[1];
			var realPostCode 	  = postCodePart.split(" ");
			if(eid(prefixG+"postcode").value != realPostCode[realPostCode.length -1])
			{
				eid(prefixG+"postcode").value = realPostCode[realPostCode.length -1];
				
				//eid('verify_message_td').style.display = "";
				extraText = 'We changed the postcode to match google mapping.';

			}
			eid('addr_lat').value = place.Point.coordinates[1];
			eid('addr_lng').value = place.Point.coordinates[0];
			var stateFullname = trim(place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName);
			var stateName = "";
			switch(stateFullname)
			{
				case "Queensland":
					stateName = "QLD";
					break;
				case "New South Wales":
					stateName = "NSW";
					break;
				case "Victoria":
					stateName = "VIC";
					break;
			}
			eid('validedAddress').value = true;
		}
}

function firstToUpper(mystring) 
{
	var sp = mystring.split(' ');
	var wl=0;
	var f ,r;
	var word = new Array();
	for (i = 0 ; i < sp.length ; i ++ ) {
	f = sp[i].substring(0,1).toUpperCase();
	r = sp[i].substring(1);
	word[i] = f+r;
	}
	newstring = word.join(' ');
	return newstring;   
}
/*
	load the map and center it on a location
*/
function show_address (title, display_address, lat, lng) 
{
  	var text = "<strong>"+title+"</strong><br />";
  
	var m = eid("map");
	if (m != undefined && google.maps.BrowserIsCompatible()) {
		map = new google.maps.Map2(m);
	
		map.setUIToDefault();
	    map.enableGoogleBar();

		point = new google.maps.LatLng(lat, lng);
		map.setCenter(point, 15);
		//map.setCenter(point, 12, G_SATELLITE_MAP);
		var marker = new google.maps.Marker(point);
		map.addOverlay(marker);
		marker.openInfoWindowHtml(text);
		google.maps.Event.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(text);
		});
	}
}

function clearField(senderId)
{
	eid(senderId).value="";
}

function myMapDescToggleBtn(sender)
{
	eid("mymapDescDiv").style.display = eid("mymapDescDiv").style.display == "none" ? eid("mymapDescDiv").style.display = "" : eid("mymapDescDiv").style.display = "none";
	eid(sender).innerHTML = eid("mymapDescDiv").style.display == "none" ? "<b>Open map user guide</b>" : "<b>Close map user guide</b>";
	
}
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

// Printing
function Printing(id){ 
	if(window.print()){
	var d=eval(id)==null||eval(id+".closed");
	if(!d){eval(id+".print()");}}
}
