
// define a global variable for the map (so any function can access it)
var map;

function init() {
  // don't even try to work if this is crazy old browser
  if (!GBrowserIsCompatible()) {
	  return;
  }
	
	// create the map
  map = new GMap2(document.getElementById("map"));
	
	// set where the map starts 
	var centerLatitude = 40.738933;
	var centerLongitude = -73.207397;
	var startZoom = 9;
  map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
	
	// initialize features on the map
  map.setMapType(G_SATELLITE_MAP);
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
  map.enableScrollWheelZoom();
	
	getMarkers();
	
	function getMarkers(){	
	
	//get the json
	var request = GXmlHttp.create();
	request.open('GET', 'retrieveSites.php5' , true); 
		request.onreadystatechange = function () {
		if (request.readyState == 4) {
		response = eval('(' + request.responseText + ')');
	
		//get rid of old markers
		map.clearOverlays();
		
		makePointArrayFromJson(response);
	}
}
request.send(null);
}
}

function makeCustomMarker(point) {
	
  var icon = new GIcon();
	// set defaults used for most cases 
	icon.iconSize = new GSize(10, 10);
  icon.iconAnchor = new GPoint(5, 5);
  icon.infoWindowAnchor = new GPoint(5, 5);
	
	switch( point.site ) {
		case 'overall':
		icon.image = "http://lizbarry.com/ligis/yellowbig.png";
		break;
		
		default:
		icon.image = "http://lizbarry.com/ligis/yellowbig.png";
		break;
	}
	var marker = new GMarker(new GLatLng(point.lat, point.lng), {icon : icon, title : ""});		
	
	map.addOverlay(marker);
	
	function showInfo() {
		
		var info = "";
		if (point.name) {
				info += " " + point.name + "<br>";
			}

		if (point.caption) {
				info += " " + point.caption + "<br>";
		}
	
			var infoTabs = [
				new GInfoWindowTab("Site Info", info),
		];
    marker.openInfoWindowTabsHtml(infoTabs);
	}
  GEvent.addListener(marker, 'click', showInfo);
}

function htmlEscape(str) {
  return str.replace('"', '&quot;');
  return str.replace("'", "&apos;");
}

function makePointArrayFromJson(pointArray) {
  // this is a for-loop: for (start condition; end condition; step function) { looped stuff }
  for (var index = 0; index < pointArray.length; index++ ) {
    // this takes the object in the index position of the response array and assigns it to be point
    var point = pointArray[index];
		makeCustomMarker(point);
  }
}




window.onload = init;
window.onunload = GUnload;
