// GLOBALS
var map = undefined;									// main Google Maps object
var allPlacemarksArray = new Array();		// tracking for all active placemarks

$(document).ready(function() {
	// GMAP INITIALIZATION
	initialize_map();
});
//window.onload = initialize;
window.onunload = GUnload;


/* =============================================================================================== */

// placemark "class" definition
// placemarks according to DNP can be a single point, a polyline, or a filled polygon
// see http://www.phpied.com/3-ways-to-define-a-javascript-class/ for how to define
function Placemark(title, body, markersString) {
	this.title = title;
	this.body = body;
	this.markersString = markersString;
	this.markers = new Array();
}

function displayPoint(marker, index){
	$("#placemarkMessage").hide();

	contentString = "<h2>" + allPlacemarksArray[index].title +"</h2><p>" + allPlacemarksArray[index].body +"</p>";
	$("#placemarkMessage").html(contentString);
	
	
	var moveEnd = GEvent.addListener(map, "moveend", function(){
		var markerOffset = map.fromLatLngToDivPixel(marker.getLatLng());
		$("#placemarkMessage").fadeIn().css({ top:markerOffset.y, left:markerOffset.x });
	
		GEvent.removeListener(moveEnd);
	});
	map.panTo(marker.getLatLng());
}



/* =============================================================================================== */


function loadMarkersFromPlacemarkArray(myArray) {
	waitToLoad = function() {
		if ( map ) {

			$("#placemarkMessage").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));

/*
			for (var i=0; i < myArray.length; i++) {
				currPlacemark = myArray[i];
				for (var j=0; j < currPlacemark.markers.length; j++) {
					currMarker = currPlacemark.markers[j];
					// ADD THE MARKER TO THE MAP
					map.addOverlay(currMarker);
					
					// CREATE ITS ENTRY IN THE LIST
					$("<li />").html('<a href="#">' + currPlacemark.title + '</a>').click(function() {
						displayPoint(currMarker, i);
					}).appendTo("#placemarkList");
	
					// AND ADD ITS CLICK LISTENER
					GEvent.addListener(currMarker, "click", function(){
						displayPoint(currMarker, i);
					});
				
				}
			}
*/

	
			$(myArray).each(function(i,placemark) {
				$(placemark.markers).each(function(j,marker) {
					// ADD THE MARKER TO THE MAP
					map.addOverlay(marker);
					
					// CREATE ITS ENTRY IN THE LIST
					$("<li />").html('<a href="#">' + placemark.title + '</a>').click(function() {
						displayPoint(marker, i);
					}).appendTo("#placemarkList");
	
					// AND ADD ITS CLICK LISTENER
					GEvent.addListener(marker, "click", function(){
						displayPoint(marker, i);
					});
				
				
				});
			});
	
			// attach the info window to the map
	
	
		} else { 
			setTimeout(waitToLoad, 500);
		} //if
	} // waitToLoad
	waitToLoad();
}





/* =============================================================================================== */


function initialize_map() {

	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.enableScrollWheelZoom();

		// init map types
		var vectorMap = DnpMapClean();
		map.addMapType(vectorMap);

		function DnpMapTypeControl() { }
		
			DnpMapTypeControl.prototype = new GControl();
			
			DnpMapTypeControl.prototype.initialize = function(map) {
				var container = document.createElement("div");
		
				// add custom DNP map button
				var typeVectorDiv = document.createElement("div");
					this.setButtonStyle_(typeVectorDiv);
					typeVectorDiv.style.left = "0px";
					typeVectorDiv.style.width = "60px";
					typeVectorDiv.style.background = "url(/_assets/img/gmap/gmap-typecontrol-vector.png) no-repeat 0 0";
					container.appendChild(typeVectorDiv)
					typeVectorDiv.appendChild(document.createTextNode("vector"));
					GEvent.addDomListener(typeVectorDiv, "click", function() {
						map.setMapType(vectorMap);
					});

				// add satellite map button
				var typeSatelliteDiv = document.createElement("div");
					this.setButtonStyle_(typeSatelliteDiv);
					typeSatelliteDiv.style.left = "60px";
					typeSatelliteDiv.style.width = "70px";
					typeSatelliteDiv.style.background = "url(/_assets/img/gmap/gmap-typecontrol-satellite.png) no-repeat 0 0";
					container.appendChild(typeSatelliteDiv)
					typeSatelliteDiv.appendChild(document.createTextNode("Satellite"));
					GEvent.addDomListener(typeSatelliteDiv, "click", function() {
						map.setMapType(G_SATELLITE_MAP);
					});

				// add satellite/hybrid map button
				var typeHybridDiv = document.createElement("div");
					this.setButtonStyle_(typeHybridDiv);
					typeHybridDiv.style.left = "140px";
					typeHybridDiv.style.width = "50px";
					typeHybridDiv.style.background = "url(/_assets/img/gmap/gmap-typecontrol-map.png) no-repeat 0 0";
					container.appendChild(typeHybridDiv)
					typeHybridDiv.appendChild(document.createTextNode("Map"));
					GEvent.addDomListener(typeHybridDiv, "click", function() {
						map.setMapType(G_HYBRID_MAP);
					});
				/*
				// add normal map button
				var typeMapDiv = document.createElement("div");
					this.setButtonStyle_(typeMapDiv);
					//this.setTypeMapStyle_(typeMapDiv);
					typeMapDiv.style.left = "0px";
					typeMapDiv.style.width = "50px";
					typeMapDiv.style.background = "url(/sites/all/themes/dnp/_assets/img/gmap-typecontrol-map.png) no-repeat 0 0";
					container.appendChild(typeMapDiv)
					typeMapDiv.appendChild(document.createTextNode("map"));
					GEvent.addDomListener(typeMapDiv, "click", function() {
						map.setMapType(G_NORMAL_MAP);
					});

				// add terrain map button
				var typeTerrainDiv = document.createElement("div");
					this.setButtonStyle_(typeTerrainDiv);
					typeTerrainDiv.style.left = "120px";
					typeTerrainDiv.style.width = "60px";
					typeTerrainDiv.style.background = "url(/sites/all/themes/dnp/_assets/img/gmap-typecontrol-terrain.png) no-repeat 0 0";
					container.appendChild(typeTerrainDiv)
					typeTerrainDiv.appendChild(document.createTextNode("terrain"));
					GEvent.addDomListener(typeTerrainDiv, "click", function() {
						map.setMapType(G_PHYSICAL_MAP);
					});
				*/
				
				map.getContainer().appendChild(container);
				return container;
			} // END DnpMapTypeControl
			
			DnpMapTypeControl.prototype.getDefaultPosition = function() {
				return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(120, 18));
			}
		
			// Sets the proper CSS for the given button element.
			DnpMapTypeControl.prototype.setButtonStyle_ = function(button) {
				button.style.textDecoration = "none";
				button.style.color = "#FFFFFF";
				button.style.backgroundColor = "#333333";
				button.style.font = "small Arial";
				button.style.border = "0px solid black";
				button.style.padding = "0px";
				button.style.margin = "0px";
				button.style.textAlign = "center";
			
				button.style.position = "absolute";
				button.style.top = "0px";
				button.style.height = "18px";
				button.style.cursor = "pointer";
				button.style.overflow = "hidden";
				button.style.textIndent = "9000px";
			}
		
		//END DnpMapTypeControl definitions (closing "}" at top)
		
		
		map.addControl(new DnpMapTypeControl()); // add custom map type buttons as above
		map.addControl(new DnpZoomControl()); // init zoom/pan controls
		map.addControl(new DnpLayersControl()); // init zoom/pan controls
		map.setCenter(new GLatLng(38.0632299145, -121.5575408936), 10, vectorMap);
		//map.enableContinuousZoom(); //enable continuous zooming (great but causes weird black areas)
				
//		gmap_load_kml('http://www.deltanationalpark.org/sites/all/themes/dnp/_assets/php/get_kml_orientation.php');
		
		
		/* POLYLINE EDITOR ITEMS =========================================================================== */
	 	featureTable_ = document.getElementById("featuretbody");
	 	featureDetails_ = document.getElementById("featuredetails-textarea");
	 	latField_ = document.getElementById("edit-field-lat-0-value");
	 	lngField_ = document.getElementById("edit-field-lon-0-value");
	 	polylineField_ = document.getElementById("edit-field-polyline-0-value");
	 	polylineEncodedField_ = document.getElementById("edit-field-polyline-encoded-0-value");
	 	polylineOptionsField_ = document.getElementById("edit-field-polyline-options-0-value");
	 	
		//select("hand_b");
		
	} else {
		alert('Sorry, but your browser is not compatible with the Google Maps API!');
	}
} // end initialize









// INITIALIZATION ===================================================================
// init constants
//var PATH_URL = 'http://dnp.zeibin.com/';
//var PATH_PHP_REL = '_assets/php/';
//var PATH_PHP_ABS = PATH_URL + PATH_PHP_REL;

// POLYLINE/MARKER EDITOR
var COLORS = [["red", "#ff0000"], ["orange", "#ff8800"], ["green","#008000"],
              ["blue", "#000080"], ["purple", "#800080"]];
var options = {};
var lineCounter_ = 0;
var shapeCounter_ = 0;
var markerCounter_ = 0;
var colorIndex_ = 0;
var featureTable_;
var featureDetails_;

var latField_;
var lngField_;
var polylineField_;
var polylineEncodedField_;
var polylineOptionsField_;


//NEEDED????

//var gmarkers = [];		// array of active markers
//var gpolylines =[];		// array of active pollines
//var idmarkers = [];		// array of markers by ID
//var marker = null;		// needed to check for existing, current marker
// init arrays
//var placemarkTypes = [];	// placemark types array
//var giconsURL = [];			// marker icons
//var giconsURLover = [];		// hover icons
//var giconsURLshadow = [];	// icon shadows
//var gicons = [];			// actual icons
//var glayers = [];



/* EDITOR FUNCTIONS ==================================================================================== */
// hand => stopEditing()
// marker => placeMarker()
// polyline => startLine()
// shape => startShape()
/*

function select(buttonId) {
	document.getElementById("hand_b").className="unselected";
	document.getElementById("shape_b").className="unselected";
	document.getElementById("line_b").className="unselected";
	document.getElementById("placemark_b").className="unselected";
	document.getElementById(buttonId).className="selected";
}
function stopEditing() {
	select("hand_b");
}
function getColor(named) {
	return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];
}

function getIcon(color) {
  var icon = new GIcon();
  icon.image = "http://google.com/mapfiles/ms/micons/" + color + ".png";
  icon.iconSize = new GSize(32, 32);
  icon.iconAnchor = new GPoint(15, 32);
  return icon;
}

function startShape() {
  select("shape_b");
  var color = getColor(false);
  var polygon = new GPolygon([], color, 2, 0.7, color, 0.2);
  startDrawing(polygon, "Shape " + (++shapeCounter_), function() {
    var cell = this;
    var area = polygon.getArea();
    cell.innerHTML = (Math.round(area / 10000) / 100) + "km<sup>2</sup>";
  }, color);
}

function startLine() {
	select("line_b");
	var color = getColor(false);
	var line = new GPolyline([], color);
		startDrawing(line, "Line " + (++lineCounter_), function() {
			var cell = this;
			var len = line.getLength();
			cell.innerHTML = (Math.round(len / 10) / 100) + "km";
		}, color);
}

function addFeatureEntry(name, color) {
  currentRow_ = document.createElement("tr");
  var colorCell = document.createElement("td");
  currentRow_.appendChild(colorCell);
  colorCell.style.backgroundColor = color;
  colorCell.style.width = "1em";
  var nameCell = document.createElement("td");
  currentRow_.appendChild(nameCell);
  nameCell.innerHTML = name;
  var descriptionCell = document.createElement("td");
  currentRow_.appendChild(descriptionCell);
  featureTable_.appendChild(currentRow_);
  return {desc: descriptionCell, color: colorCell};
}


function updatePolylineFields() {
	// update the polyline field
	var coords = '';
	var polylineCoords = '';
	var i=0;
	for (i=0; i < this.getVertexCount(); i++) {
		var vertex = this.getVertex(i);
		polylineCoords += (Math.round(vertex.lng() * 1000000)/1000000) + "," + (Math.round(vertex.lat() * 1000000)/1000000) + "\n";
	}
	//alert(polylineCoords);
	polylineField_.value = polylineCoords;

	latField_.value = '';
	lngField_.value = '';

}


function startDrawing(poly, name, onUpdate, color) {
	map.clearOverlays();
	map.addOverlay(poly);
	poly.enableDrawing(options);
	poly.enableEditing({onEvent: "mouseover"});
	poly.disableEditing({onEvent: "mouseout"});

	GEvent.addListener(poly, "endline", function() {
		select("hand_b");
		var cells = addFeatureEntry(name, color);
	
		GEvent.bind(poly, "lineupdated", cells.desc, onUpdate);

		GEvent.addListener(poly, "lineupdated", updatePolylineFields);
	
		//listens for clicks: if a vertex, deletes it, else changes color
		GEvent.addListener(poly, "click", function(latlng, index) {
			if (typeof index == "number") {
				poly.deleteVertex(index);
			} else {
				var newColor = getColor(false);
				cells.color.style.backgroundColor = newColor
				poly.setStrokeStyle({color: newColor, weight: 4});
			}
		});
	});
}

function placeMarker() {
  select("placemark_b");
  var listener = GEvent.addListener(map, "click", function(overlay, latlng) {
    if (latlng) {
      select("hand_b");
      GEvent.removeListener(listener);
      var color = getColor(true);
      var marker = new GMarker(latlng, {icon: getIcon(color), draggable: true});

	map.clearOverlays(); // clear any existing overlays

      map.addOverlay(marker);
      var cells = addFeatureEntry("Placemark " + (++markerCounter_), color);
      updateMarker(marker, cells);
      GEvent.addListener(marker, "dragend", function() {
        updateMarker(marker, cells);
      });
      GEvent.addListener(marker, "click", function() {
        updateMarker(marker, cells, true);
      });
    }
  });
}

function updateMarker(marker, cells, opt_changeColor) {
  if (opt_changeColor) {
    var color = getColor(true);
    marker.setImage(getIcon(color).image);
    cells.color.style.backgroundColor = color;
  }
  var latlng = marker.getPoint();
  cells.desc.innerHTML = "(" + Math.round(latlng.y * 100) / 100 + ", " +
  Math.round(latlng.x * 100) / 100 + ")";
  
	latField_.value = Math.round(latlng.y * 1000000) / 1000000;
	lngField_.value = Math.round(latlng.x * 1000000) / 1000000;
	polylineField_.value = '';
	polylineEncodedField_.value = '';	
	polylineOptionsField_.value = '';	
}




*/





// =======================================================================================




// loads a single placemark for a placemark node
function loadMapPlacemark(pid) {
	waitToLoad = function() {
		if (map) {
			gmap_load_kml('http://www.deltanationalpark.org/_assets/php/get_kml.php?action=kml_by_pid&pid=' + pid);
		} else {
			setTimeout(waitToLoad, 500);
		}
	}
	waitToLoad();
/*
	myPoint = new GLatLng(myLatitude, myLongitude);
	myMarker = new GMarker(myPoint);
	GEvent.addListener(myMarker, "click", function() {
		myMarker.openInfoWindowHtml("<p>my infobox!</p>");
	});
	map.addOverlay(myMarker);
	map.setCenter(myPoint, 13);

*/	
}



