var geocoder;
var map;
var errtxt = "";
var gdir;

var side_bar_html = "";
var gmarkers = [];
var htmls = [];
var to_htmls = [];
var from_htmls = [];


function loadAddresses(zoom)
{
	if (GBrowserIsCompatible()) 
	{
		var reasons=[];
		reasons[G_GEO_SUCCESS]            = "Success";
		reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
		reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
		reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
		reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
		reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
		reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
		reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
		reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
		reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";


		showElem('ph_contact_gmap');
		map = new GMap2(document.getElementById("ph_contact_gmap"));
 		map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());

	    if (getElem('ph_contact_directions')!=null) 
	    {
	    	gdir = new GDirections(map, document.getElementById("ph_contact_directions"));
	    	
	    	GEvent.addListener(gdir, "error", function() {
				var code = gdir.getStatus().code;
				var reason="Code "+code;
				if (reasons[code]) {
					reason = reasons[code]
				} 
				
				alert("Failed to obtain directions, "+reason);
			});
	    }

		for (i=0;i<addresses.length;i++)
		{
			if (latitudes[i]!='0' && longitudes[i]!='0')
			{
//				alert('display GPS '+names[i]+ ' '+i);
				displayGPS(i, addresses[i], names[i], latitudes[i], longitudes[i], zoom);
			}
			else
			{
//				alert('display SAD '+names[i]+ ' '+i);
				searchAndDisplay(i, addresses[i], names[i], i==(addresses.length-1), zoom);
			}
		}
	}
	else
	{
		alert ('Your browser version does not support Google Maps. If the problem persists, please report this to Site Administrators. !');
	}
}

function displayGPS(index, address, name, latitude, longitude, zoom)
{
	if (zoom==null) zoomLevel = 10;
	else zoomLevel = zoom;
	
	point = new GLatLng(latitude, longitude);
	map.setCenter(point, zoomLevel);
	
	var infoHtml = '<div align="left" style="width:180px;"> <b>'+name+'</b> <br>' +   address;
	infoHtml = infoHtml +  '</div>';

	var marker = createMarker(index, point, name, infoHtml);
	map.addOverlay(marker);

}
function searchAndDisplay(index, address, name, islast, zoom)
{
	if (zoom==null) zoomLevel = 10;
	else zoomLevel = zoom;
	geocoder = new GClientGeocoder();
	
	geocoder.getLocations(address, function (response) 
	{
		if (!response)
		{
			if (errtxt!='') errtxt+='\n\n';
			errtxt += 'ADDRESS "'+address+'" not found!';
			errtxt += '\nREASON: Internal error. Try again. If the problem persists, please report this to Site Administrators.';
		}
		else if (response.Status.code!=200)
		{
			if (errtxt!='') errtxt+='\n\n';
			errtxt += 'ADDRESS "'+address+'" not found!';

			switch (response.Status.code)
			{
//				case 400: errtxt = '\nREASON: A directions request could not be successfully parsed. For example, the request may have been rejected if it contained more than the maximum number of waypoints allowed. ';break;
//				case 500: errtxt = '\nREASON: A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known. ';break;
//				case 601: errtxt = '\nREASON: The HTTP q parameter was either missing or had no value. For geocoding requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input ';break;
				case 400: 
				case 500:
				case 601: 
				case 602: errtxt += '\nREASON: The address is relatively new, or it may be incorrect.';break;
				case 603: errtxt += '\nREASON: The address details cannot be returned due to legal or contractual reasons.';break;
				case 604: errtxt += '\nREASON: Google error . We do not have enough data regarding that region.';break;
				case 610: errtxt += '\nREASON: The given key is either invalid or does not match the domain for which it was given.';break;
				case 620: errtxt += '\nREASON: Too many queries in too short a period. Try again. If the problem persists, please report this to Site Administrators.';break;
			}
		}
		else
		try {
			place = response.Placemark[0];
			point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
			map.setCenter(point, zoomLevel);
			
			var infoHtml = '<div align="left" style="width:180px;"> <b>'+name+'</b> <br>' +   place.address;
			infoHtml = infoHtml +  '</div>';

			// Add the marker to map
//			map.addOverlay(createInfoMarker(point, infoHtml));
			
			var marker = createMarker(index, point, name, infoHtml);
			map.addOverlay(marker);

			
		}
		catch (err)
		{
			if (errtxt!='') errtxt+='\n\n';
			errtxt += 'ADDRESS "'+address+'" not found!';
			errtxt += '\nREASON: Internal error. Try again. If the problem persists, please report this to Site Administrators.';
		}
		
		if (errtxt!="" && islast) 
		{
			errtxt+="\n\nClick OK to continue.";
			alert(errtxt);
		}
	});
}

function createInfoMarker(point, content) 
{
	var marker = new GMarker(point);
	GEvent.addListener(marker, "click",	function() {
		marker.openInfoWindowHtml(content);
	});
	
	return marker;
}

function createMarker(index, point,name,html) 
{
	var marker = new GMarker(point);
	
	var i = index;
//	alert(name+' '+i);
	
	// The info window version with the "to here" form open
	to_htmls[i] = html + '<br>Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
		'<br>Start address:<form action="javascript:getDirections()">' +
		'<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
		'<INPUT value="Get Directions" TYPE="SUBMIT"><br>' +
		'Walk <input type="checkbox" name="walk" id="walk" /> &nbsp; Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
		'<input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + 
		'"/>';
	// The info window version with the "from here" form open
	from_htmls[i] = html + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <b>From here<\/b>' +
		'<br>End address:<form action="javascript:getDirections()">' +
		'<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
		'<INPUT value="Get Directions" TYPE="SUBMIT"><br>' +
		'Walk <input type="checkbox" name="walk" id="walk" /> &nbsp; Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
		'<input type="hidden" id="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +
		'"/>';
	// The inactive version of the direction info
	html = html + '<br>Directions: <a href="javascript:tohere('+i+')">To here<\/a> - <a href="javascript:fromhere('+i+')">From here<\/a>';
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	// save the info we need to use later for the side_bar
//	gmarkers.push(marker);
	gmarkers[i] = marker;
	htmls[i] = html;
	// add a line to the side_bar html
//	side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '<\/a><br>';
	return marker;
}

function getDirections() 
{
	// ==== Set up the walk and avoid highways options ====
	var opts = {};
	if (document.getElementById("walk").checked) {
		opts.travelMode = G_TRAVEL_MODE_WALKING;
	}
	if (document.getElementById("highways").checked) {
	   opts.avoidHighways = true;
	}
	// ==== set the start and end locations ====
	var saddr = document.getElementById("saddr").value;
	var daddr = document.getElementById("daddr").value;
	if (gdir!=null) gdir.load("from: "+saddr+" to: "+daddr, opts);
}


// This function picks up the click and opens the corresponding info window
function myclick(i) {
	gmarkers[i].openInfoWindowHtml(htmls[i]);
}

// functions that open the directions forms
function tohere(i) {
	gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
function fromhere(i) {
	gmarkers[i].openInfoWindowHtml(from_htmls[i]);
}
