

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

//bounds
var zoomlevel = 8;
var bounds;
var nelat, nelng, latspan, lngspan;

var imagePath = "http://www.rpa.org/js/maps/";

var loadingMessage = "<p>Loading...<img src=" +  imagePath +  "ajax-loader.gif></p>";

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"));
	
	
	//create the geocoder for address lookup
	geocoder = new GClientGeocoder();
  
  // set where the map starts 
	map.setCenter(new GLatLng(40.7196,-73.9924), 16);
	
	// set min/max map scale 
  var minmapscale = 14;
  var maxmapscale = 17;
  // get array of map types
  var mapTypes = map.getMapTypes();
  // overwrite the getMinimumResolution() and getMaximumResolution() methods for each map type
  for (var i=0; i<mapTypes.length; i++) {
  mapTypes[i].getMinimumResolution = function() {return minmapscale;}
  mapTypes[i].getMaximumResolution = function() {return maxmapscale;} 
  }

  // initialize features on the map
  map.setMapType(G_NORMAL_MAP);
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
  map.enableScrollWheelZoom();
	
	//Frank's code for listening to the map move, to reload markers
	getMarkers();
	
	//listen for map moving
	GEvent.addListener(map, "moveend", function() {
	//if moved, we need to reload
	getMarkers();
	});
}

// generate markers for each random point 
function makeCustomMarker(point) {
	
	
  var icon = new GIcon();
	// set defaults used for most cases (5 bus types)
	icon.iconSize = new GSize(10, 10);
  icon.iconAnchor = new GPoint(5, 5);
	icon.shadow = "http://lizbarry.com/transitcuts/icons/bus_shadow.png"
	icon.shadowsize =  new GSize(6,6);
  icon.infoWindowAnchor = new GPoint(5, 5);
	
	switch( point.cut_type ) {
		case '1':
		icon.image = imagePath + "icons/b_elim.png";
		break;
		case '2':
		icon.image = imagePath + "icons/b_elim_wkdy.png";
		break;
		case '3':
		icon.image = imagePath + "icons/b_elim_wknd.png";
		break;
		case '4':
		icon.image = imagePath + "icons/b_elim_ltnt.png";
		break;
		case '5':
		icon.image = imagePath + "icons/b_reduced_srvc.png";
		break;
		case '6':
		icon.image = imagePath + "icons/s_elim.png";
		// make the subway icons bigger
		icon.iconSize = new GSize(16, 16);
 		icon.iconAnchor = new GPoint(8, 8);
		icon.shadow = "icons/shadow.png"
		icon.shadowsize =  new GSize(24,24);
  	icon.infoWindowAnchor = new GPoint(8, 8);
		break;
		case '7':
		icon.image = imagePath + "icons/s_reduced.png";
		icon.iconSize = new GSize(20, 20);
 		icon.iconAnchor = new GPoint(10, 10);
		icon.shadow = imagePath + "icons/shadow.png"
		icon.shadowsize =  new GSize(8,8);
  	icon.infoWindowAnchor = new GPoint(8, 8);
		break;
		default:
		icon.image = imagePath + "cut_stop.png";
		break;
	}

 // var marker = new GMarker(new GLatLng(point.y, point.x), { icon : icon; title : "foo"});
	var marker = new GMarker(new GLatLng(point.y, point.x), {icon : icon});
	
	var tooltip = new Tooltip(marker,point.d,4); 
	marker.tooltip = tooltip; 
		
	GEvent.addListener(marker,'mouseover',function(){ this.tooltip.show(); }); 	
	GEvent.addListener(marker,'mouseout',function(){ this.tooltip.hide(); });

	map.addOverlay(marker);
	map.addOverlay(tooltip);
		
	return marker;
}

function getMarkers(){	

	//startup the loading symbol
	document.getElementById("cuts").innerHTML = loadingMessage;
		
	//get the zoom and bounds
	zoomlevel = map.getZoom();
	bounds = map.getBounds();
	
	//digested lat/lng values
	nelat = bounds.getNorthEast().lat();
	nelng = bounds.getNorthEast().lng();
	latspan = nelat - bounds.getSouthWest().lat();
	lngspan = nelng - bounds.getSouthWest().lng();
	
	//get the json
	var boundsStr = "nelat=" + nelat + "&nelng=" + nelng + "&latspan=" + latspan + "&lngspan=" + lngspan;
	var urlStr="http://www.rpa.org/js/maps/retrievePointsFromSQL.php5?" + boundsStr ;
	var cutsStr="http://www.rpa.org/js/maps/retrieveCutsFromSQL.php5?" + boundsStr ;
	
	var request = GXmlHttp.create();
	var cutsRequest = GXmlHttp.create();
	
	request.open('GET', urlStr , true); 
	cutsRequest.open('GET', cutsStr , true); 
	
	request.onreadystatechange = function () {
		if (request.readyState == 4) {
			response = eval('(' + request.responseText + ')');
			
			//get rid of old markers
			map.clearOverlays();

			var markers = makePointArrayFromJson(response);
		}
	}

	cutsRequest.onreadystatechange = function () {
		if (cutsRequest.readyState == 4) {
			cutsResponse = eval('(' + cutsRequest.responseText + ')');
			var cutInfo = makeCutsText(cutsResponse);
		}	
	}
	
	request.send(null);
	cutsRequest.send(null);	
}

function makePointArrayFromJson(pointArray) {
  var result = [];
  // 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];
	var marker = makeCustomMarker(point);
    result.push(marker);
  }
  return result;
}


//make text from the returned cuts and put it into the side bar
function makeCutsText(cutArray) {
	var cutsText = "<p>";
	for (var i = 0; i < cutArray.length; i++ ) {
		cutsText += "<img src=";
		switch( cutArray[i].t ) {
			case '1':
			cutsText += imagePath + "icons/b_elim.png";
			break;
			case '2':
			cutsText += imagePath +  "icons/b_elim_wkdy.png";
			break;
			case '3':
			cutsText += imagePath +  "icons/b_elim_wknd.png";
			break;
			case '4':
			cutsText += imagePath +  "icons/b_elim_ltnt.png";
			break;
			case '5':
			cutsText += imagePath +  "icons/b_reduced_srvc.png";
			break;
			case '6':
			cutsText += imagePath +  "icons/s_elim.png";
			break;
			case '7':
			cutsText += imagePath +  "icons/s_reduced.png";
			break;
			default:
			cutsText += imagePath +  "cut_stop.png";
			break;
		}
		cutsText += "> ";
		cutsText += cutArray[i].r;
		cutsText += " - ";
		cutsText += cutArray[i].d;
		cutsText += "<br>";
	}
	
	cutsText += "</p>";
	
	//this shouldn't be innerHTML, deprecated and despised... 
	//TODO use proper DOM methods like appendChild and createTextNode instead
	
	document.getElementById("cuts").innerHTML = cutsText;
	
	return cutsText;
}

// showLocation() is called when you click on the Search button
// in the form. 
function showLocation(address) {
  //var address = document.forms[0].q.value; //this might need to be tweaked, depending on other page items
  geocoder.getLocations(address, findLocation);
  return false;
}

// allow people to look up their zip codes
// this code comes from the google maps documentation
function findLocation(response) {
	// map.clearOverlays(); 
		if (!response || response.Status.code != 200) {
			alert("Sorry, we were unable to geocode that address");
		} else {
			gcplace = response.Placemark[0];
			gcpoint = new GLatLng(gcplace.Point.coordinates[1], gcplace.Point.coordinates[0]);
			marker = new GMarker(gcpoint);
			map.setCenter(gcpoint, 15);
	//		map.getMarkers;
		}
}

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