var map;
var gmarkers = [];
var htmls = [];
var to_htmls = [];
var from_htmls = [];
var i=0;

var localSearch = new GlocalSearch();
// === Create an associative array of GIcons() ===
function changeClass(Elem, myClass) {
	var elem;
	if(document.getElementById) {
		var elem = parent.document.getElementById(Elem);
	} else if (document.all){
		var elem = parent.document.all[Elem];
	}
	elem.className = myClass;
}

function handleErrors(){
	   if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     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 (directions.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("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 (directions.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("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 (directions.getStatus().code == G_GEO_BAD_KEY)
	     alert("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 (directions.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	   else alert("Not a valid postcode.");
	   
	}


/*function createMarker(point,html,icontype) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
  marker.openInfoWindowHtml(html);
});
return marker;
}
*/


function createMarker(point,name,html) {
	var marker = new GMarker(point);
	// The info window version with the "to here" form open
	to_htmls[i] = html + '<p style="margin:10px 0px;">Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
	   '<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
	   '<input type="text" SIZE=40 MAXLENGTH=40 style="width:50px;" name="saddr" id="saddr" value="" /><\/p>' +
	   '<INPUT value="Get Directions" TYPE="SUBMIT">' +
	   '<input type="hidden" name="daddr" value="' + 'OX28 4LH ' + "(" + name + ")" + 
	   '"/>';
	// The info window version with the "to here" form open
	from_htmls[i] = html + '<p style="margin:10px 0px;">Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <b>From here<\/b>' +
	   '<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
	   '<input type="text" SIZE=40 MAXLENGTH=40 style="width:50px;" name="daddr" id="daddr" value="" /><\/p>' +
	   '<INPUT value="Get Directions" TYPE="SUBMIT">' +
	   '<input type="hidden" name="saddr" value="' + 'OX28 4LH ' + "(" + name + ")" + 
	   '"/>';
	// The inactive version of the direction info
	html = html + '<p style="margin:10px 0px;">Directions: <a href="javascript:tohere('+i+')">To here<\/a> - <a href="javascript:fromhere('+i+')">From here<\/a><\/p>';
	
	GEvent.addListener(marker, "click", function() {
	  marker.openInfoWindowHtml(html);
	});
	gmarkers[i] = marker;
	htmls[i] = html;
	i++;
	return marker;
}

// functions that open the directions forms
function tohere(i) {
	gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
function fromhere(i) {
	gmarkers[i].openInfoWindowHtml(from_htmls[i]);
}


function wheelevent(e)
{
if (!e){
e = window.event
}
if (e.preventDefault){
e.preventDefault()
}
e.returnValue = false;
}
function addoverlays() {
		var point = new GLatLng(51.77871413350769, -1.4833903312683105);
		var marker = createMarker(point,'STL Communications Limited','<div style="width:150px"><p style="margin:0px;">STL Communications Limited<br>Park House<br>Station Lane<br>Witney<br>Oxfordshire<br>OX28 4LH</p></div>')
		map.addOverlay(marker);
}
function mapLoad() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
		map.enableDoubleClickZoom
		/*map.setCenter(new GLatLng(51.77871413350769, -1.4833903312683105), 15);*/
		GEvent.addDomListener(map.getContainer(), "DOMMouseScroll", wheelevent);
		map.getContainer().onmousewheel = wheelevent; 
		/*addoverlays();*/
		resetmap();
		
	}
}
function resetmap(){
	/*directions.clear()
	changeClass('directionsPanel','hidden');*/
	map.setCenter(new GLatLng(51.77871413350769, -1.4833903312683105), 15);
	addoverlays();
}
function usePointFromPostcode(postcode, callbackFunction) {
	localSearch.setSearchCompleteCallback(null, 
		function() {
			//alert(localSearch.results[0]);
			if (localSearch.results[0])
			{		
				var resultLat = localSearch.results[0].lat;
				var resultLng = localSearch.results[0].lng;
				var point = new GLatLng(resultLat,resultLng);
				callbackFunction(point);
			}else{
				alert("Postcode not found!");
			}
		});	
	localSearch.execute(postcode + ", UK");
}

function getdirs(point){
	if(document.getElementById('start').value!='') {
	usePointFromPostcode(document.getElementById('start').value, getdirs2);
	}
}
function onGDirectionsLoad(){ 
	m=directions.getDistance().meters;
	//alert(directions.getSummaryHtml());
	miles=Math.round(m/1609.344);
	changeClass('directionsPanel','shown');
	map.clearOverlays();
}
function getdirs2(point){
	lat2=point.lat() 
	lng2=point.lng()
	directionsPanel = document.getElementById("directionsPanel");
	directions = new GDirections(map, directionsPanel);
	GEvent.addListener(directions, "load", onGDirectionsLoad);
	 GEvent.addListener(directions, "error", handleErrors);
	directions.load(lat2 + "," + lng2 + " to 51.77871413350769, -1.4833903312683105")
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}



