var map;
var $gmapSidebarLinks;
var tooltip;
var gdir;
var isOverGMTT=false; //is over google map tooltip

var fpoints = [];


var $docslist;

$(document).ready(function(){
	
	$gmapSidebarLinks = $("#gmap-sidebar-list li");
	$docslist = $("#docs_list > div");
 
  if (GBrowserIsCompatible()) {
		var centerLatitude = 45.5118;
		var centerLongitude = -122.67565;
		var startZoom = 10;
			
		map = new GMap2(document.getElementById("gmap-canvas"), {suppressCopyright: false, logoPassive: true});
		map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
		
		map.addControl(new GSmallMapControl());
		map.addControl(new GScaleControl());
		map.addControl(new GMapTypeControl());
		      
	  // ====== set up marker mouseover tooltip div ======
	    tooltip = document.createElement("div");
	    map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
	    tooltip.style.visibility="hidden";
    
		// === create a GDirections Object ===
		gdir=new GDirections(map, document.getElementById("directions"));

		
		for(id in objMarkers) { createMarker(objMarkers[id], id); }
	}
	else {
    	alert("Sorry, the Google Maps API is not compatible with this browser");
  }
	
	
	var myFile = document.location.toString();
	if (myFile.match('#')) { // the URL contains an anchor
	  // click the navigation item corresponding to the anchor
	  var myAnchor = myFile.split("#")[1];
	  $("#gmap-sidebar-" + myAnchor).click();
	}
	
});




//objMarkers[id].latitude, objMarkers[id].longitude, objMarkers[id].name, objMarkers[id].desc, objMarkers[id].icon
function createMarker(objMarker, markerID) 
{
		var point = new GLatLng(objMarker.latitude, objMarker.longitude);
		var marker = new GMarker(point);
		marker.name = objMarker.name;
		marker.alias = objMarker.alias;
		marker.desc = objMarker.desc;


       var htmlDocList = '';
	   jQuery.each(objMarker.docs, function() {
			if($docslist.eq(this)) {  htmlDocList += '<p>' + $docslist.eq(this).html() + '</p>';  }
		});

		// === store the name so that the tooltip function can use it ===
		marker.tooltip = '<div class="gmap-tooltip"><img onclick="$(this).parent().hide();" class="closegmtt" style="border:0px none ; margin:0; padding:0; position:absolute; right:8px; top:8px; width:12px; height:12px; -moz-user-select:none; cursor:pointer; z-index:10000;" src="http://maps.google.com/intl/en_ALL/mapfiles/iw_close.gif"/><nobr><h2>'+objMarker.name+'</h2><p>'+objMarker.desc+'</p>Ph:'+objMarker.phone+'</nobr><br /><a class="showgmtt" href="javascript:void(0)" onClick="fPoint(\''+id+'\');" >click here to learn more</a></div>';

		var $listItem = $('#gmap-sidebar-' + objMarker.alias);
		var $listItems = $('.gmap-sidebar-' + objMarker.alias);

		var focusPoint = function() {

			// The info window version with the "to here" form open
			var to_html = '<h3><strong>'+marker.name+'</strong><br /><br /><p>'+marker.desc+' <br />'+objMarker.phone+'</h3><a href="http://www.eyehealthlasik.com/pdfs/'+objMarker.alias+'.pdf" target="_blank"><img src="http://www.eyehealthlasik.com/images/pdficon.gif" width="15" height="18" /> Click for pdf</a></p>' +
						'<p>Directions: 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">' +
					    '<p>Walk <input type="checkbox" name="walk" id="walk" /> &nbsp; Avoid Highways <input type="checkbox" name="highways" id="highways" /></p>' +
						'<input type="hidden" id="daddr" value="'+marker.name+"@"+ point.lat() + ',' + point.lng() + '"/>';

			//tooltip.style.visibility="hidden";
			$gmapSidebarLinks.removeClass("current");
			$listItem.parent().addClass("current");
			$("#gmap-sidebar h2").text(objMarker.name + " Location");


			var infoTabs = [
				new GInfoWindowTab("Info", '<div class="gmap-tab gmap-tab-info">'+to_html+'</div>'),
				new GInfoWindowTab("Hours", '<div class="gmap-tab gmap-tab-hours">'+objMarker.hours+'</div>'),
				new GInfoWindowTab("Physicians", '<div class="gmap-tab gmap-tab-physicians">'+htmlDocList+'</div>')
			];

			marker.openInfoWindowTabsHtml(infoTabs, {maxWidth:300});


		  /*
			//new GInfoWindowTab("Location", '<div id="gmap-tab-detailmap" class="gmap-tab"></div>')	
			//map.openInfoWindowTabsHtml(point, infoTabs);
			var dMapDiv = document.getElementById("gmap-tab-detailmap");
			var detailMap = new GMap2(dMapDiv);
			detailMap.setCenter(point , 8);
			detailMap.addControl(new GSmallMapControl());
			GEvent.addListener(detailMap, "zoomend", miniMapZoomEnd);
			GEvent.addListener(detailMap, "moveend", miniMapMoveEnd);
			var CopyrightDiv = dMapDiv.firstChild.nextSibling;
			var CopyrightImg = dMapDiv.firstChild.nextSibling.nextSibling;
			CopyrightDiv.style.display = "none"; 
			CopyrightImg.style.display = "none";
			showMinimapRect(detailMap);
			//marker.openInfoWindowHtml(objMarker.name+'<br />');   //+"<p>"+objMarker.addr_desc+"</p>"
		  */	

			//map.panTo(point);
			
			return false;
		}


		$listItem.click(function () { focusPoint(); });
		$listItems.click(function () { focusPoint(); });
		$(tooltip).click(function () {tooltip.style.visibility="hidden"; });

		GEvent.addListener(marker, 'click', focusPoint);

		$listItem.hover(function () { 
			focusPoint(); //showTooltip(marker); 
		}, function () {
		});
			
		$listItems.hover(function () { 
			focusPoint(); //showTooltip(marker); 
		}, function () {
		});
		

		GEvent.addListener(marker, 'mouseover', function() {
			//marker.showMapBlowup(17, G_HYBRID_MAP);
			//marker.setIcon(G_DEFAULT_ICON);
			focusPoint(); //showTooltip(marker);
		});
		
		fpoints[id] = focusPoint;
			
		map.addOverlay(marker);
}



// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a side_bar mouseover
function showTooltip(marker) {
	tooltip.innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
}



function fPoint(id) {
	fpoints[id]();
}



// ===== request the directions =====
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
  gdir.load("from: "+saddr+" to: "+daddr, opts);
}




// === Array for decoding the failure codes ===
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.";


/*
// === catch Directions errors ===
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);
});
*/



window.onunload = GUnload;