// these variables determine where the map is centered, and how far it's zoomed in

var centerLatitude = 45.085;
var centerLongitude = -69.04111;
var startZoom = 7;

var map;

// these variables place the "logo.png" icon on the site of the Augusta Civic Center

var augustalatlng = new GLatLng(43.8854, -69.9797);
var augustalogo = new GIcon();
	  augustalogo.image = "61.png";
      augustalogo.iconSize = new GSize(25, 25);
      augustalogo.iconAnchor = new GPoint(5, 5);

// this function places markers on the map as a function of location (latlng) and type of carpool (logo)

function addMarker(latlng, logo) {
	var marker = new GMarker(latlng, logo);
	map.addOverlay(marker);
}

// 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);

	addMarker(augustalatlng, augustalogo);

	//Note: this call to retrieve markers is required for Listing 3-8
	retrieveMarkers();
	
	GEvent.addListener(map, "click", function(overlay, latlng) {
		//only perform the click if the window is closed and the click was directly on the map.
		if(!overlay) {
			//create an HTML DOM form element
			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;};

			//retrieve the longitude and lattitude of the click point
			var lng = latlng.lng();
			var lat = latlng.lat();
			
			// edit the inner HTML below to change the style of the input form (remember to include apostrophe quotes around every line)
			inputForm.innerHTML = '<fieldset style="font-size:.8125em;width:225px;z-index:1000;">'
			+ '<legend>New Carpool</legend>'
			+ '<label for="ride">Will you ride or drive from this location?</label><br>'
			+ '<select id="ride">'
			+ '<option value="ride">Ride</option>'
			+ '<option value="drive">Drive</option>'
			+ '<option value="either">Either</option>'
			+ '</select><hr>'
			+ '<label for="pass">If you can drive, how many additional passengers could you take?</label><br>'
            + '<select id="pass">'
			+ '<option value="1">1</option>'
			+ '<option value="2">2</option>'
			+ '<option value="3">3</option>'
			+ '</select><hr>'
			+ '<label for="contact">Contact information (phone number or e-mail):</label>'
			+ '<input type="text" id="contact" style="width:100%;" />'
			+ '<input type="submit" value="Save"/>'
			+ '<input type="hidden" id="longitude" value="' + lng + '"/>'
			+ '<input type="hidden" id="latitude" value="' + lat + '"/>'
			+ '</fieldset>';

			map.openInfoWindow (latlng,inputForm);
		}
	});

}

window.onload = init;

// this function gets called when the "submit" button in the form above is pressed (by way of the inputForm.onsubmit definition above):

function storeMarker(){
	// define the relevant variables from elements in the HTML form:
	var lng = document.getElementById("longitude").value;
	var lat = document.getElementById("latitude").value;
			
    // and these translate the same into PHP variables, for the storeMarker.php file
	var getVars =  "?ride=" + document.getElementById("ride").value
	+ "&pass=" + document.getElementById("pass").value
	+ "&contact=" + document.getElementById("contact").value
	+ "&lng=" + lng
	+ "&lat=" + lat ;
	
	

	var request = GXmlHttp.create();

	//open the request to storeMarker.php on your server
	request.open('GET', '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;
}

// 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("marker");
			for (var i = 0; i < markers.length; i++) {
				var lng = markers[i].getAttribute("lng");
				var lat = markers[i].getAttribute("lat");
				var iconImage = markers[i].getAttribute("icon");
				
				//check for lng and lat so MSIE does not error
				//on parseFloat of a null value
				
				if(lng && lat) {
					
					var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));

					// define the HTML for an info window of an existing marker:
					var html = '<div><b>Driver or rider:</b> '
					+ markers[i].getAttribute("ride")
					+ '</div><div><b>Passengers:</b> '
					+ markers[i].getAttribute("pass") 
					+ '</div><div><b>Contact:</b> '
					+ markers[i].getAttribute("contact");

					var marker = createMarker(latlng, html, iconImage);
					map.addOverlay(marker);
				}
			} //for
		} //if
	} //function

	request.send(null);
}

// 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;
}

