// these variables determine where the map is centered, and how far it's zoomed in

var centerLatitude = 45.305803;
var centerLongitude = -69.104004;
var startZoom = 7;

var map;

// this function shows the map (centered and zoomed by the variables above), its controls (GSmallMapControl and GMapTypeControl), and adds a "listener" that specifies what to do when someone clicks on it

function init() {
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);

	//Note: this call to retrieve markers is required for Listing 3-8
	retrieveMarkers();
	}

window.onload = init;

// this function retrieves previously-saved markers from the XML file and adds them to the map with the addOverlay method

function retrieveMarkers() {
	var request = GXmlHttp.create();

	//tell the request where to retrieve data from.
	request.open('GET', 'retrieveMarkers.php', true);

	//tell the request what to do when the state changes.
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;

			// retrieve individual markers and their data from the KML file
			var markers = xmlDoc.documentElement.getElementsByTagName("property");
			
			for (var i = 0; i < markers.length; i++) {
				var lng = markers[i].getAttribute("longitude");
				var lat = markers[i].getAttribute("latitude");
				var iconImage = markers[i].getAttribute("icon");
				var image = markers[i].getAttribute("image");
					
				
				//check for lng and lat so MSIE does not error
				//on parseFloat of a null value
				
				if(lng && lat) {
					if(image) {
											
						var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));
	
						// define the HTML for an info window of an existing marker:
						var html = '<div style="font-size:14px;"><b> '
						+ markers[i].getAttribute("name")
						+ '</b><br>'
						+ markers[i].getAttribute("address")
						+ ', '
						+ markers[i].getAttribute("town")
						+ '</b></div><div>Year of renovation: '
						+ markers[i].getAttribute("year")
						+ '</div><div>Est. Cost:'
						+ markers[i].getAttribute("cost") 
						+ '</div><br><div style="padding:4px; width=300px;"><img src="'
						+ markers[i].getAttribute("image")
						+ '"></div>';
	
						var marker = createMarker(latlng, html, iconImage);
						map.addOverlay(marker);
					}
					else {
						var inputForm = document.createElement("form");
						inputForm.setAttribute("action","");
						// on clicking the 'submit' button in the form below, 
						// this calls the 'storeMarker' function, below:
						inputForm.onsubmit = function() {storeMarker(); return false;};
						
						inputForm.innerHTML = 
						'<div style="font-size:14px;"><b> '
						+ markers[i].getAttribute("name")
						+ '</b><br>'
						+ markers[i].getAttribute("address")
						+ ', '
						+ markers[i].getAttribute("town")
						+ '</b></div><div>Year of renovation: '
						+ markers[i].getAttribute("year") 
						+ '</div><div>Est. Cost: '
						+ markers[i].getAttribute("cost")
						+ '<br>'
						+ '<fieldset style="width:200px; font-size:10px;">'
						+ '<label for="image">Add an image by URL:</label><br>'
						+ '<input type="text" id="image" style="width:100%;" />'
						+ '<input type="submit" value="Submit"/>'
						+ '<input type="hidden" id="lat" value="' + lat + '"/>'
						+ '<input type="hidden" id="lng" value="' + lng + '"/>'
						+ '<input type="hidden" id="name" value="' + markers[i].getAttribute("name") + '"/>'
						+ '<input type="hidden" id="address" value="' + markers[i].getAttribute("address") 
						+ '"/>'
						+ '<input type="hidden" id="town" value="' + markers[i].getAttribute("town") + '"/>'
						+ '<input type="hidden" id="lat" value="' + markers[i].getAttribute("latitude") + '"/>'
						+ '<input type="hidden" id="lng" value="' + markers[i].getAttribute("longitude") + '"/>'
						+ '</fieldset>';
					
						var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));

	
						var marker = createMarker(latlng, inputForm, iconImage);
						map.addOverlay(marker);
					}
				}
			} //for
		} //if
	} //function

	request.send(null);
}



function storeMarker(){
	
	var name = document.getElementById("name").value;
	var imgsrc = document.getElementById("image").value;
	var lng = document.getElementById("lng").value;
	var lat = document.getElementById("lat").value;
	
	// define the relevant variables from elements in the HTML form:
    // and these translate the same into PHP variables, for the storeMarker.php file
	var getVars =  "?name=" + name	+ "&image=" + imgsrc;
	
	var request = GXmlHttp.create();

	//open the request to storeMarker.php on your server
	request.open('GET', 'http://www.growsmartmaine.org/maps/historic/storeMarker.php' + getVars, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			//the request in complete

			var xmlDoc = request.responseXML;

			//retrieve the root document element (response)
			var responseNode = xmlDoc.documentElement;

			//retrieve the type attribute of the node
			var type = responseNode.getAttribute("type");

			//retrieve the content of the responseNode
			var content = responseNode.firstChild.nodeValue;

			//check to see if it was an error or success
			if(type!='success') {
				alert(content);
			} else {
				//Create a new marker and add its info window.
				var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));
				
				// the iconImage below is yellow to differentiate the newly-added marker from others
				var iconImage = "http://maps.google.com/mapfiles/kml/paddle/ylw-circle.png"

				var marker = createMarker(latlng, content, iconImage);

				map.addOverlay(marker);
				map.closeInfoWindow();
			}
		}
	}
	request.send(null);
	return false;

	
	map.closeInfoWindow();
}

// this function collects data from the retrieved markers and newly-created markers and creates a 
// "marker" argument, which then gets used in the map.addOverlay event.
function createMarker(latlng, html, iconImage) {
		var icon = new GIcon();
		icon.image = iconImage;
		icon.iconAnchor = new GPoint(16,32);
		icon.iconSize = new GSize(32,32);
		icon.infoWindowAnchor = new GPoint(14,14);
		var marker = new GMarker(latlng, icon);
	GEvent.addListener(marker, 'click', function() {
		var markerHTML = html;
		marker.openInfoWindowHtml(markerHTML);
	});
	return marker;
}

