var map;
//var gdir;
var mapType;
var xmlFile;
var markerTag;
var markerURL;
var markers;
var markerId;

var parkmarkers = new Array();
var sitemarkers = new Array();
var golfmarkers = new Array();
var naturemarkers = new Array();
var othermarkers = new Array();

var parkico = new GIcon();
var siteico = new GIcon();
var golfico = new GIcon();
var natureico = new GIcon();
var otherico = new GIcon();

var pathPrefix = "/";

var zIndexStateParks = 9;
var zIndexHistoricSites = 8;
var zIndexGolfCourses = 7;
var zIndexNatureCenters = 6;
var zIndexOther = 5;

var i = 0;
var to_htmls = [];
var from_htmls = [];
var allowedBounds;
  
//-- On Page Load 
function onLoad() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(42.20, -76.5020), 7);
		map.setUIToDefault();
		//map.addControl(new GLargeMapControl());  //Add zoom map control
		//map.addControl(new GScaleControl());  //Add zoom map control
		//map.addControl(new GMapTypeControl());  //Add zoom map control
		map.addMapType(G_PHYSICAL_MAP); 
		map.enableDoubleClickZoom()
		//map.enableScrollWheelZoom()

       /* gdir = new GDirections(map, document.getElementById("directions"));

        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);
        });*/
      
		//set outermost zoom level for each map type
		var gmapType = map.getMapTypes();
		for (var i=0; i < gmapType.length; i++) {
			gmapType[i].getMinimumResolution = function() {return 6;}
		}

		//set outermost bounds of map   
		allowedBounds = new GLatLngBounds(new GLatLng(40.5,-81), new GLatLng(45.5,-70.5));
	
		map.clearOverlays();
		
		// initialize Markers
		initIcons();
		
		enabled();
		
		GEvent.addListener(map, "zoomed", function() {
			checkBounds();
		});
		
		//Check the outermost bounds of the map
		GEvent.addListener(map, "move", function() {
			checkBounds();
		});

		fnStateParks();
		fnHistoricSites();
		fnGolfCourses();
		fnNautreCenters();
		fnOther();
  }
  else {
      alert("Sorry, the Google Maps API is not compatible with this browser");}
}

//-- Show Makers
function showMarkers(mtype) {	
	mapType = mtype;

	if (mtype == "parks") {
		xmlFile = pathPrefix + "gmaps/StateParks.xml?" + new Date().getTime();
		mapType = 'parks';
		markerTag = "ROW";
		markerURL = "/parks/";}
	else if (mtype == "sites") {
		xmlFile = pathPrefix + "gmaps/HistoricSites.xml?" + new Date().getTime();
		mapType = 'sites';
		markerTag = "ROW";
		markerURL = "/historic-sites/";}
	else if (mtype == "courses") {
		xmlFile = pathPrefix + "gmaps/GolfCourses.xml?" + new Date().getTime();
		mapType = 'courses';
		markerTag = "ROW";
		markerURL = "/golf-courses/";}
	else if (mtype == "centers") {
		xmlFile = pathPrefix + "gmaps/NatureCenters.xml?" + new Date().getTime();
		mapType = 'centers';
		markerTag = "ROW";
		markerURL = "/environment/nature-centers/";}
	else if (mtype == "other") {
		xmlFile = pathPrefix + "gmaps/Other.xml?" + new Date().getTime();
		mapType = 'other';
		markerTag = "ROW";
		markerURL = "";}
		
	GDownloadUrl(xmlFile, function(data) {
		var xml = GXml.parse(data);
		markers = xml.documentElement.getElementsByTagName(markerTag);

	    window.setTimeout(mapMarkers, 10);
		i = 0;
	}); //end GDownloadUrl
} // end function

//-- Verify Boundaries of map
function checkBounds() {
	if (allowedBounds.contains(map.getCenter())) {
		return;}

	//reset bounding coordinates to keep map in range
	var C = map.getCenter();
	var X = C.lng();
	var Y = C.lat();

	var AmaxX = allowedBounds.getNorthEast().lng();
	var AmaxY = allowedBounds.getNorthEast().lat();
	var AminX = allowedBounds.getSouthWest().lng();
	var AminY = allowedBounds.getSouthWest().lat();

	if (X < AminX) {X = AminX;}
	if (X > AmaxX) {X = AmaxX;}
	if (Y < AminY) {Y = AminY;}
	if (Y > AmaxY) {Y = AmaxY;}

	map.setCenter(new GLatLng(Y,X));
}

//-- Add Mapping Markers
function mapMarkers() {

	if ( i < markers.length ) {
		var max = Math.min(i + 20, markers.length);
		
		while (i < max) {
			var lat = parseFloat(markers[i].getAttribute("Latitude"));
			var lng = parseFloat(markers[i].getAttribute("Longitude"));
			var point = new GLatLng(lat, lng);
			var marker = new GMarker(point);
			
			var id = markers[i].getAttribute("ID");
			var name = markers[i].getAttribute("Name");
			var region = markers[i].getAttribute("Region");
			var address = markers[i].getAttribute("Street");
			var city = markers[i].getAttribute("City");
			var zip = markers[i].getAttribute("Zip");
			var desc = markers[i].getAttribute("Description");
						
			var tooltip = name;
			var infoHTML = '<div class="g-box">';
			
			if (markerURL.length > 0) {
			    infoHTML = infoHTML + "<p><a href='" + markerURL + id + "/details.aspx'>" + name + "</a><br />";}
			else {
			    var url = markers[i].getAttribute("URL");
			    infoHTML = infoHTML + "<p><a href='" + url + "'>" + name + "</a><br />";}
			    
			infoHTML = infoHTML + address + "<br />";
			infoHTML = infoHTML + city + ", NY " + zip + "</p>";
			
			if (desc.length > 180) {
				infoHTML = infoHTML + "<p style='margin:5px 0px;'>"+ desc.substring(0, 180) +"...</p>";}
			else {
				infoHTML = infoHTML + "<p style='margin:5px 0px;'>"+ desc +"</p>";}		

            // The info window version with the "to here" form open
            to_htmls[i] = infoHTML + '<br />Directions: <b>To here</b> - <a href="javascript:fromhere('+ i + ",'" + mapType + "'" + ')">From here</a><br />' +
               '<span style="display:block; margin:3px 0px 3px 87px;">e.g., "street city, state"</span>' +
               '<form action="http://maps.google.com/maps" method="get" target="_blank">' +
               '<label for="saddr" style="margin-right:5px;">Start Address</label>' +
               '<input type="text" size="35" maxlength="40" name="saddr" id="saddr" value="" /><br />' +
               '<input value="Get Directions" type="submit" style="margin-top:3px;">' +
               '<input type="hidden" name="daddr" value="'+ name +"@"+ point.lat() + ',' + point.lng() + '"/></form>';
            
            // The info window version with the "to here" form open
            from_htmls[i] = infoHTML + '<br />Directions: <a href="javascript:tohere('+ i + ",'" + mapType + "'" + ')">To here</a> - <b>From here</b><br />' +
               '<span style="display:block; margin:3px 0px 3px 87px;">e.g., "street city, state"</span>' +
               '<form action="http://maps.google.com/maps" method="get" target="_blank">' +
               '<label for="daddr" style="margin-right:5px;">End Address</label>' +
               '<input type="text" size="35" maxlength="40" name="daddr" id="daddr" value="" /><br />' +
               '<input value="Get Directions" type="submit" style="margin-top:3px;">' +
               '<input type="hidden" name="saddr" value="'+ name + "@" + point.lat() + ',' + point.lng() + '"/></form>';
           
            // The inactive version of the direction info
            infoHTML = infoHTML + '<br />Directions: <a href="javascript:tohere('+ i + ",'" + mapType + "'" + ');">To here</a> - <a href="javascript:fromhere('+ i +",'" + mapType + "'" + ')">From here</a>';

            infoHTML = infoHTML + "</div>";	
            
			if (mapType == "parks") {
				var marker = createMarker(point, tooltip, infoHTML, parkico, "parks");
				parkmarkers.push(marker);
				marker.type = mapType;}
				//map.addOverlay(marker);}
			else if (mapType == "sites") {
				var marker = createMarker(point, tooltip, infoHTML, siteico, "sites");
				sitemarkers.push(marker);
				marker.type = mapType;}
				//map.addOverlay(marker);}
			else if (mapType == "courses") {
				var marker = createMarker(point, tooltip, infoHTML, golfico, "courses");
				golfmarkers.push(marker);
				marker.type = mapType;}
			else if (mapType == "centers") {
				var marker = createMarker(point, tooltip, infoHTML, natureico, "centers");
				naturemarkers.push(marker);
				marker.type = mapType;}
			else if (mapType == "other") {
				var marker = createMarker(point, tooltip, infoHTML, otherico, "other");
				othermarkers.push(marker);
				marker.type = mapType;}
				
			if (markerId == id) {
			    map.addOverlay(marker);
				map.setCenter(new GLatLng(lat, lng), 12);
				marker.openInfoWindowHtml(infoHTML);}
			else if (markerId == 0) {
			    map.addOverlay(marker);}
			    
			i++;
		}
	
		window.setTimeout(mapMarkers, 10);
	}
	
	if (i >= markers.length ) {enabled();}
}

//-- Initalize Markers Onload
function initIcons() {
	parkico.image = pathPrefix + "gmaps/green_pin.png";
	parkico.iconSize = new GSize(28, 34);
	parkico.iconAnchor = new GPoint(7, 26);
	parkico.infoWindowAnchor = new GPoint(9, 9);

	siteico.image = pathPrefix + "gmaps/red_pin.png";
	siteico.iconSize = new GSize(28, 34);
	siteico.iconAnchor = new GPoint(7, 26);
	siteico.infoWindowAnchor = new GPoint(9, 9);
	
	golfico.image = pathPrefix + "gmaps/yellow_pin.png";
	golfico.iconSize = new GSize(28, 34);
	golfico.iconAnchor = new GPoint(7, 26);
	golfico.infoWindowAnchor = new GPoint(9, 9);
	
	natureico.image = pathPrefix + "gmaps/blue_pin.png";
	natureico.iconSize = new GSize(28, 34);
	natureico.iconAnchor = new GPoint(7, 26);
	natureico.infoWindowAnchor = new GPoint(9, 9);
	
	otherico.image = pathPrefix + "gmaps/green_pin.png";
	otherico.iconSize = new GSize(28, 34);
	otherico.iconAnchor = new GPoint(7, 26);
	otherico.infoWindowAnchor = new GPoint(9, 9);
}

//-- Create New Google Markers
function createMarker(point, title, html, icon, type) {
	var marker = new GMarker(point, {icon:icon, title:title, zIndexProcess:setZindexOrder});

		if (type == "parks") {
			marker.importance = zIndexStateParks;}
		else if (type == "sites") {
			marker.importance = zIndexHistoricSites;}
		else if (type == "courses") {
			marker.importance = zIndexGolfCourses;}
		else if (type == "centers") {
			marker.importance = zIndexNatureCenters;}
		else if (type == "other") {
			marker.importance = zIndexOther;}
			
		GEvent.addListener(marker, "click", function() {  
		marker.openInfoWindowHtml(html);
	});   
	
	return marker;
}

//-- Show/Hide State Park Markers	
function fnStateParks()  {
	disabled();
	
	window.setTimeout(function() {hideMarkers("parks");}, 10);
	
	if(document.getElementById("hdnParks").value > 0) {
		markerId = document.getElementById("hdnParks").value; showMarkers("parks");}

	/*if (document.getElementById('chkParks').checked) {
		markerId = 0; window.setTimeout(function() {showMarkers("parks");}, 20);} 	*/
}
	
//-- Show/Hide Historic Site Markers	
function fnHistoricSites()  {	
	disabled();

    window.setTimeout(function() {hideMarkers("sites");}, 10);
    
	if(document.getElementById("hdnHistoricSites").value > 0) {
		markerId = document.getElementById("hdnHistoricSites").value; showMarkers("sites");}

	/*if (document.getElementById('chkHistoricSites').checked) {
		markerId = 0; window.setTimeout(function() {showMarkers("sites");}, 20);} */
}	

//-- Show/Hide Golf Courses Markers	
function fnGolfCourses()  {
	disabled();
	
	window.setTimeout(function() {hideMarkers("courses");}, 10);
	
	if(document.getElementById("hdnGolfCourses").value > 0) {
		markerId = document.getElementById("hdnGolfCourses").value; showMarkers("courses");}

	/*if (document.getElementById('chkGolfCourses').checked) {
		markerId = 0; window.setTimeout(function() {showMarkers("courses");}, 20);} */
}

//-- Show/Hide Nature Centers Markers	
function fnNautreCenters()  {
	disabled();

	window.setTimeout(function() {hideMarkers("centers");}, 10);
	
	if(document.getElementById("hdnNatureCenters").value > 0) {
		markerId = document.getElementById("hdnNatureCenters").value; showMarkers("centers");}

	/*if (document.getElementById('chkNatureCenters').checked) {
		markerId = 0; window.setTimeout(function() {showMarkers("centers");}, 20);} 	*/
}

//-- Show/Hide Other Markers	
function fnOther()  {
	disabled();

	window.setTimeout(function() {hideMarkers("other");}, 10);
	
	if(document.getElementById("hdnOther").value > 0) {
		markerId = document.getElementById("hdnOther").value; showMarkers("other");}

	/*if (document.getElementById('chkNatureCenters').checked) {
		markerId = 0; window.setTimeout(function() {showMarkers("centers");}, 20);} 	*/
}

//-- Set Index Layer
function setZindexOrder (marker, b) {
	return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;}

//-- Hide Markers
function hideMarkers(mtype) {
	if (mtype == "parks") {
				
		for (var i = 0; i < parkmarkers.length; i++) {
		   map.removeOverlay(parkmarkers[i]);}
		
		//parkmarkers = new Array();
	} else if (mtype == "sites") {
		
		for (var i = 0; i < sitemarkers.length; i++) {
			map.removeOverlay(sitemarkers[i]);}
		
		sitemarkers = new Array();
	} else if (mtype == "courses") {
		
		for (var i = 0; i < golfmarkers.length; i++) {
			map.removeOverlay(golfmarkers[i]);}
		
		golfmarkers = new Array();
	} else if (mtype == "centers") {
		
		for (var i = 0; i < naturemarkers.length; i++) {
			map.removeOverlay(naturemarkers[i]);}
		
		naturemarkers = new Array();
	} else if (mtype == "other") {
		
		for (var i = 0; i < othermarkers.length; i++) {
			map.removeOverlay(othermarkers[i]);}
		
		othermarkers = new Array();
	}
	
	enabled();
}

//-- Enable Mapping Features
function disabled() {
	map.disableDragging();
	
	var loading = document.getElementById("lyrLoading");
	loading.style.visibility = "visible";
}

//-- Enable Mapping Features
function enabled() {
	map.enableDragging();
	
	var loading = document.getElementById("lyrLoading");
	loading.style.visibility = "hidden";
}

// functions that open the directions forms (to here)
function tohere(i, mtype) {
    if (mtype == "parks") {
         parkmarkers[i].openInfoWindowHtml(to_htmls[i]);} 
    else if (mtype == "sites") {
        sitemarkers[i].openInfoWindowHtml(to_htmls[i]);}
    else if (mtype == "courses") {
        golfmarkers[i].openInfoWindowHtml(to_htmls[i]);}
	else if (mtype == "centers") {
        naturemarkers[i].openInfoWindowHtml(to_htmls[i]);}
    else if (mtype == "other") {
        othermarkers[i].openInfoWindowHtml(to_htmls[i]);}
}

// functions that open the directions forms (from here)
function fromhere(i, mtype) {
    if (mtype == "parks") {
        parkmarkers[i].openInfoWindowHtml(from_htmls[i]);}
    else if (mtype == "sites") {
        sitemarkers[i].openInfoWindowHtml(from_htmls[i]);}
    else if (mtype == "courses") {
        golfmarkers[i].openInfoWindowHtml(from_htmls[i]);}
	else if (mtype == "centers") {
        naturemarkers[i].openInfoWindowHtml(from_htmls[i]);}
    else if (mtype == "other") {
        othermarkers[i].openInfoWindowHtml(from_htmls[i]);}
}

 // ===== request the directions =====
/*function getDirections(mtype) {
    var saddr = document.getElementById("saddr").value
    var daddr = document.getElementById("daddr").value
    gdir.load("from: "+saddr+" to: "+daddr);
    
   hideMarkers(mtype);
   
    var printHTML = '<a href="http://maps.google.com/maps?f=d&hl=en&geocode=&saddr='+saddr+'&daddr='+daddr+'%5C&sll=37.0625,-95.677068&sspn=40.460237,70.488281&ie=UTF8&z=12&pw=2">hey now</a>';
    //var printHTML = 'hey now';
    document.getElementById("print").innerHTML = printHTML;
}
*/