var map;
var gdir;
//var geocoder = null;
//var addressMarker;

function initialize() {
  if (GBrowserIsCompatible()) {      

    map = new GMap2(document.getElementById("map_canvas"));
	map.setCenter(new GLatLng(40.185886, -75.097617), 15);
	
    var marker = new GMarker(new GLatLng(40.185886, -75.097617));

	map.openInfoWindowHtml(map.getCenter(), "L&M Engines<br/>246 E. County Line Rd.<br/>Hatboro, PA 19040");
	
	map.addOverlay(marker);
	
    gdir = new GDirections(map, document.getElementById("directions"));
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);

  }
}

function setDirections(fromAddress) {
	var smsg = check_directions()
	
	if (smsg != '') {
		alert(smsg);
	}
	else {	
		map.clearOverlays();
			
		var surl = '/directionsset?from[address]=' + encodeURIComponent(document.getElementById("from_address").value);
		surl = surl + '&from[city]=' + encodeURIComponent(document.getElementById("from_city").value);
		surl = surl + '&from[state]=' + encodeURIComponent(document.getElementById("from_state").value);
		surl = surl + '&from[zip]=' + encodeURIComponent(document.getElementById("from_zip").value);
		new Ajax.Request(surl, {method: 'get', asynchronous:true, evalScripts:true})
		
		var toAddress = '246 E. County Line Rd. Hatboro, PA 19040'
		var fromAddress = document.getElementById("from_address").value;
		fromAddress = fromAddress + ' ' + document.getElementById("from_city").value;
		fromAddress = fromAddress + ', ' + document.getElementById("from_state").value;
		fromAddress = fromAddress + ' ' + document.getElementById("from_zip").value;
		
		gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": 'en' });
	}
}

function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("The address entered could not be found, please check the address and try again.");
	     
   else alert("An unknown error occurred.");
   
}

function onGDirectionsLoad() {
	
}

window.onunload = function() {
	GUnload();
}

window.onload = function() {
	initialize();
}
