var geocoder;
var map;
var directionsPanel;
var directions;
var address;	
var startIconFile;
var wayptIconFile;
var endIconFile;
var startIcon;
var endIcon;
var startPoint;
var endPoint;
var startMarker;
var endMarker;
var LatLongCoords;
var logoURL = '/PublishingImages/home/headerlogo.gif';

function refreshMap() {
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(39.81,-98.56), 2);        
	map.addControl(new GLargeMapControl());

	// zoom scale   
	map.addControl(new GScaleControl());

	// toggles between road, satelite and hybrid maps   
	// map.addControl(new GMapTypeControl());

	// collapsable overview map    
	// map.addControl(new GOverviewMapControl());                   
}    

function grabAddr()
{
    address="9500 Euclid Ave.  Cleveland, OH";
	var a = document.getElementById('AddrDiv').innerText;
	if (a == undefined)
	{
	    a = document.getElementById('AddrDiv').textContent;
	}
	a = a.replace(/&nbsp;/gi,"");
	a = a.replace(/\n/gi,"");
	a = a.replace(/\t/gi,"");
	a = a.replace(/^\s+|\s+$/g,""); // trim spaces before and after string
	
	var hiddnFld = (document.getElementById)?document.getElementById('LatLongCoords'):document.all['LatLongCoords'];
	var coord = ""; 
	if (hiddnFld != null)
	{
	    coord = hiddnFld.value;
		coord = coord.replace(/&nbsp;/gi,"");
		coord = coord.replace(/\n/gi,"");
		coord = coord.replace(/\t/gi,"");
		coord = coord.replace(/^\s+|\s+$/g,"");// trim spaces before and after string
		coord = coord.replace(String.fromCharCode(160),"");
	}
	
	
	if (coord!=null && coord.length > 9) 
	{
		LatLongCoords = coord;
	}
		
	if (a!=null && a.length > 9) 
	{
		address = a;
	}
	return false;
}    

function mapLoad() {           
    // The <Body> onUnload event handler to a method defined by Google.
    document.body.onunload = GUnload;
    var lookupAddress;
		
	grabAddr();
	
	if (LatLongCoords != null)
	{ lookupAddress = LatLongCoords;}
	else
	{ lookupAddress = address;}
	
	if (GBrowserIsCompatible()) {
	
	refreshMap();
	geocoder = new GClientGeocoder();
	geocoder.getLatLng(
		lookupAddress,
		function(point) 
		{
			if (!point) 
			{
				alert("Target location not found - That can't be good.\n\"" + lookupAddress + "\" (" + address.length() + ") bad character @ " 
				+ indexOf(String.fromCharCode(160)) );
			} 
			else 
			{
				try 
				{
					endPoint = point;
					startIconFile = "/PublishingImages/home/bstart.gif";
					wayptIconFile = "/PublishingImages/home/bend.gif";
					endIconFile = "/PublishingImages/home/bend1.gif";
					startIcon=new GIcon(G_DEFAULT_ICON, startIconFile);
					endIcon=new GIcon(G_DEFAULT_ICON, endIconFile);
					var marker = new GMarker(endPoint, endIcon);
					map.setCenter(point, 11);                    
					var address1 = address;
					var address2 = "";
					var addressBreak = address.indexOf("  ");
					if (addressBreak > -1) 
					{
						address1 = address.substring(0, addressBreak);
						address2 = address.substring(addressBreak+2);
					}
					map.addOverlay(marker);
					marker.openInfoWindowHtml('<img src="' + logoURL + '" alt="Cleveland Clinic"/><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + address1 + '<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + address2);
				}
				catch (e) 
				{
					alert("in mapLoad(): " + e);
				}
			}
		});
	}
}        

// display a given address as a marker and pop-up window   
function showAddress(address1) {
	refreshMap();
	geocoder.getLatLng(
		address1,
		function(point) 
		{
			if (!point) 
			{
				alert("Starting address '" + address1 + "' not found");
				mapLoad();
			} 
			else 
			{
				startPoint = point;
			}
		});
	
	G_START_ICON.image = startIconFile;
	G_END_ICON.image = endIconFile;
	
	directionsPanel = document.getElementById("directionsArea");
	directionsPanel.innerHTML = '';
	directions = new GDirections(map);
	directions.load("from: " + address1 + " to: " + address, {getSteps:true});

	GEvent.addListener(
		directions ,
		"load", 
		function() 
		{
			setTimeout('customPanel(map,"map",directions,document.getElementById("directionsArea"))', 1);
		});
		
	return false;
}

// ============ custom direction panel ===============
var evenodd = true;
function customPanel(map,mapname,dirn,div) {

	dirn.getMarker(0).getIcon().image = startIconFile;
	dirn.getMarker(1).getIcon().image = endIconFile;
	var html = '<div class="InteractiveMapHdr1">Step-by-step Directions to Cleveland Clinic</div>';
	
	
	// === read through the GRoutes and GSteps ===
	
	for (var i=0; i<dirn.getNumRoutes(); i++) {
		if (i==0) 
		{
			var type="play";
		} 
		else 
		{
			var type="pause";
		}
		var route = dirn.getRoute(i);
		var geocode = route.getStartGeocode();
		var point = route.getStep(0).getLatLng();
		// === Waypoint at the start of each GRoute
		html += waypoint(point, type, geocode.address, mapname);
		html += routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");
		for (var j=0; j<route.getNumSteps(); j++) {
			var step = route.getStep(j);
			// === detail lines for each step ===
			html += detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html, mapname);
		}
	}
	html += routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");
	
	// === the final destination waypoint ===   
	var geocode = route.getEndGeocode();
	var point = route.getEndLatLng();
	html += waypoint(point, "stop", geocode.address);
	
	// === the copyright text ===
	html += copyright(dirn.getCopyrightsHtml());
	
	// === drop the whole thing into the target div
	div.innerHTML = html;
}

// === waypoint banner ===
function waypoint(point, type, address, mapname) {
	var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
	var html = '<table class="InteractiveMapHdr2">';
	html += '  <tr style="cursor: pointer;" onclick='+target+'>';        
	html += '    <td class="InteractiveMapHdr2" style="vertical-align: middle;">';
	var imgSrc = startIconFile;
	if (type == "stop")
	{
		imgSrc = endIconFile;
	}
	else if (type == "pause")
	{
		imgSrc = wayptIconFile;
	}
	html += '      <img src="' + imgSrc + '">'
	html += '    </td>';
	html += '    <td style="vertical-align: middle; width: 100%;">';
	html +=        address;
	html += '    </td>';
	html += '  </tr>';
	html += '</table>';
	evenodd = true;
	return html;
}

// === total route distance ===
// Pays attention to the evenodd variable but doesn't change it.
function routeDistance(dist) {
	var html = '<div class="' + (evenodd?'InteractiveMapOdd':'InteractiveMapEven') + '" style="text-align:right;padding-bottom:8px;padding-top:8px">Total: ' + dist + '</div>';
	return html;
}      

// === step detail ===
// Step number, description, distance.
function detail(point, num, description, dist, mapname) {
	var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
	var style = (evenodd?'InteractiveMapOdd':'InteractiveMapEven');
	var html = '<table style="margin: 0px; border-collapse: collapse;">';
	html += '  <tr class="' + style + '" onclick='+target+'>';
	html += '    <td class="' + style + '" style="margin: 0px; vertical-align: top; text-align: left;padding-right:2px;padding-left:18px;">';
	html += '      '+num+'.';
	html += '    </td>';
	html += '    <td class="' + style + '" style="margin: 0px; vertical-align: top; width: 100%;padding-left=2px;">';
	html +=        description;
	html += '    </td>';
	html += '    <td class="' + style + '" style="margin: 0px; vertical-align: top; text-align: right;">';
	html +=        dist;
	html += '    </td>';
	html += '  </tr>';
	html += '</table>';
	evenodd = !evenodd
	return html;
}

// === Copyright tag ===
function copyright(text) {
	return '<div class="InteractiveMapNotes" align="right"><font size="-1"><i>' + text + "</i></font></div>";
}


function HitEnter(e)
{
    var keynum;

    if(window.event) // IE
      {
      keynum = e.keyCode;
      }
    else if(e.which) // Netscape/Firefox/Opera
      {
      keynum = e.which;
      }
    return (keynum == 13);
}

//I'm not exactly sure why mapLoad() has to be run before AND after the rest
//of the <Body> onLoad code.
if (_spBodyOnLoadFunctionNames != null) 
{
    _spBodyOnLoadFunctionNames.push("mapLoad");
    _spBodyOnLoadFunctionNames.unshift("mapLoad");
}

