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

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"));
	
	// set where the map starts 
	var centerLatitude = 40.7335;
	var centerLongitude = -73.9955;
	var startZoom = 17;
  map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
	
	// initialize features on the map
  map.setMapType(G_NORMAL_MAP);
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
  map.enableScrollWheelZoom();
	
	getMarkers();
	
	// add a click listener
	function onClickCallback(marker, latlng) {
    if (marker) {
      // do nothing - this is necessary because sometimes gmaps fires extra events
    } else {
			// create the input form
      map.openInfoWindowHtml(latlng,
        "<form onsubmit='storeNewPoint(); return false;'>" +
          "<input type=hidden name=lat id=lat value='" + latlng.lat() + "'/>" +
          "<input type=hidden name=lng id=lng value='" + latlng.lng() + "'/>" +
          "Steward Code: <input type=text size=8 name=steward_code id=steward_code /><br>" +
					"Choose Tree Type: <select id='species' name='species'>" +
							"<option value='TICO'>choose...</option>" +
							"<option value='TICO'>Little Leaf Linden</option>" +
 							"<option value='TIAM'>American Linden</option>" + 
							"<option value='TITO'>Silver Linden</option>" +
							"<option value='CR'>Hawthorn </option>" +
							"<option value='PYCA'>Callery Pear</option>" +
							"<option value='MAZ'>Crabapple</option>" +
							"<option value='PR'>Cherry</option>" +
							"<option value='QUPH'>Willow Oak</option>" +
							"<option value='QUAC'>Sawtooth Oak</option>" +
							"<option value='QUPA'>Pin Oak</option>" +
							"<option value='QURU'>Northern Red Oak</option>" +
							"<option value='QUBI'>Swamp White Oak</option>" +
							"<option value='QURO'>English Oak</option>" +
							"<option value='MEGL'>Dawn Redwood</option>" +
							"<option value='PIST'>Eastern White Pine</option>" +
							"<option value='TADI'>Bald Cypress</option>" +
							"<option value='FRPE'>Green Ash</option>" +
							"<option value='ACPL'>Norway Maple</option>" +
							"<option value='ACPLCK'>Crimson King Norway Maple</option>" +
							"<option value='ACRU'>Red Maple</option>" +
							"<option value='ACSA1'>Silver Maple</option>" +
							"<option value='ACSA2'>Sugar Maple</option>" +
							"<option value='ACCA'>Hedge Maple</option>" +
							"<option value='ACG1'>Amur Maple</option>" +
							"<option value='ACPS'>Sycamore Maple</option>" +
							"<option value='STJA2'>Japanese Pagoda Tree</option>" +
							"<option value='GLTR'>Honey Locust</option>" +
							"<option value='ROPS'>Black Locust</option>" +
							"<option value='GIBI'>Ginko</option>" +
							"<option value='ULAM'>American Elm</option>" +
							"<option value='ULPA'>Chinese Elm</option>" +
							"<option value='ZESE'>Japanese Zelkova</option>" +
							"<option value='PLAC'>London Plane Tree</option>" +
							"<option value='BE'>Birch</option>" +
							"<option value='CEJA'>Katsura Tree</option>" +
							"<option value='HADI'>Silverbell</option>" +
							"<option value='PRCE'>Purpleleaf Plum</option>" +
							"<option value='SYRE'>Japanese Lilac Tree</option>" +
							"<option value='UNK'>unknown</option>" +
						"</select><br>" +						
					"DBH in whole inches: <input type=text size=8 name=DBH id=DBH /><br>" +
					"Link to Photo: <input type=text size=37 name=image id=image /><br>" +
		      "<input type=submit />" +
        "</form>"
      );
    }
	}
  GEvent.addListener(map, "click", onClickCallback);
	
}

function makeCustomMarker(point) {
	
  var icon = new GIcon();
	// set defaults used for most cases 
	icon.iconSize = new GSize(10, 10);
  icon.iconAnchor = new GPoint(5, 5);
  icon.infoWindowAnchor = new GPoint(5, 5);
	
	switch( point.family ) {
		case 'TILIACEAE':
		icon.image = "icons/090407.tiliaceae.png";
		break;
		case 'ROSACEAE':
		icon.image = "icons/090407.rosaceae.png";
		break;
		case 'FAGACEAE':
		icon.image = "icons/090407.Fagaceae.png";
		break;
		case 'CONIFERAE':
		icon.image = "icons/090407.conifer.png";
		break;
		case 'OLEACEAE':
		icon.image = "icons/090407.oleacea.png";
		break;
		case 'SAPINDACEAE':
		icon.image = "icons/090407.Sapindaceae.png";
		break;
		case 'FABACEAE':
		icon.image = "icons/090407.Fabaceae.png";
		break;
		case 'GINKGOPHYTA':
		icon.image = "icons/090407.ginkgophyta.png";
		break;
		case 'ULMACEAE':
		icon.image = "icons/090407.ulmaceae.png";
		break;
		case 'PLATANACEAE':
		icon.image = "icons/090407.platancea.png";
		break;
		case 'OTHER':
		icon.image = "icons/090407.OTHER.png";
		break;

		default:
		icon.image = "icons/090407.other.png";
		break;
	}
	var marker = new GMarker(new GLatLng(point.lat, point.lng), {icon : icon, title : "Street Tree"});		
	
	map.addOverlay(marker);
	
	//info window
	function showInfo() {
		
		var static = "";
		if (point.id) {
				static += "<b>Unique ID</b>: " + point.id + "<br>";
			}
		if (point.com_name_1) {
				static += "<b>Species</b>: " + point.com_name_1 + "<br>";
			}
		if (point.DBH) {
				static += "<b>DBH</b>: " + point.DBH + "<br>";
			}
		if (point.image1) {
				static += '<div style="height: 5px;"></div><img src="' + htmlEscape(point.image1) + '" style="max-width: 450px; width: expression(this.width>450?450px:this.width); max-height: 350px; height: expression(this.height>350?350px:this.height);"/>';
					static = '<div style="width: 450px; height: 350px;">' + static + '</div>';
		}
					
		var dynamic = (
				"<DIV STYLE=width:450px;height:300px><DIV STYLE=overflow:auto;width:450px;height:300px>" +
					"<form name='maintenance'>" +
							"<input type=hidden name=id id=id value='" + point.id + "'/>" +
						  "<input type=hidden name=lat id=lat value='" + point.lat + "'/>" +
          		"<input type=hidden name=lng id=lng value='" + point.lng + "'/>" +
							"Steward Code: <input type=text size=8 name=steward_code id=steward_code /><br>" +
							"<br>" +
							"Date: <select id='year' name='year'>" +
							"<option value='0000'>choose...</option>" +
							"<option value='2009'>2009</option>" +
							"</select>" +
							" Month: <select id='month' name='month'>" +
							"<option value='00'>choose...</option>" +
							"<option value='01'>January</option>" +
							"<option value='02'>February</option>" +
							"<option value='03'>March</option>" +
							"<option value='04'>April</option>" +
							"<option value='05'>May</option>" +
							"<option value='06'>June</option>" +
							"<option value='07'>July</option>" +
							"<option value='08'>August</option>" +
							"<option value='09'>September</option>" +
							"<option value='10'>October</option>" +
							"<option value='11'>November</option>" +
							"<option value='12'>December</option>" +
							"</select>" +
							" Day: <select id='day' name='day'>" +
							"<option value='00'>choose...</option>" +
							"<option value='01'>01</option>" +
							"<option value='02'>02</option>" +
							"<option value='03'>03</option>" +
							"<option value='04'>04</option>" +
							"<option value='05'>05</option>" +
							"<option value='06'>06</option>" +
							"<option value='07'>07</option>" +
							"<option value='08'>08</option>" +
							"<option value='09'>09</option>" +
							"<option value='10'>10</option>" +
							"<option value='11'>11</option>" +
							"<option value='12'>12</option>" +
							"<option value='13'>13</option>" +
							"<option value='14'>14</option>" +
							"<option value='15'>15</option>" +
							"<option value='16'>16</option>" +
							"<option value='17'>17</option>" +
							"<option value='18'>18</option>" +
							"<option value='19'>19</option>" +
							"<option value='20'>20</option>" +
							"<option value='21'>21</option>" +
							"<option value='22'>22</option>" +
							"<option value='23'>23</option>" +
							"<option value='24'>24</option>" +
							"<option value='25'>25</option>" +
							"<option value='26'>26</option>" +
							"<option value='27'>27</option>" +
							"<option value='28'>28</option>" +
							"<option value='29'>29</option>" +
							"<option value='30'>30</option>" +
							"<option value='31'>31</option>" +
							"</select><br>" +
							"<br>" +
							<!-- "Time - to the nearest hour: <select id='time' name='time'>" +
								<!-- "<option value='00:00:00'>choose...</option>" +
								<!-- "<option value='05:00:00'>5:00am</option>" +
								<!-- "<option value='06:00:00'>6:00am</option>" +
								<!-- "<option value='07:00:00'>7:00am</option>" +
								<!-- "<option value='08:00:00'>8:00am</option>" +
								<!-- "<option value='09:00:00'>9:00am</option>" +
								<!-- "<option value='10:00:00'>10:00am</option>" +
								<!-- "<option value='11:00:00'>11:00am</option>" +
								<!-- "<option value='12:00:00'>12:00pm</option>" +
								<!-- "<option value='13:00:00'>1:00pm</option>" +
								<!-- "<option value='14:00:00'>2:00pm</option>" +
								<!-- "<option value='15:00:00'>3:00pm</option>" +
								<!-- "<option value='16:00:00'>4:00pm</option>" +
								<!-- "<option value='17:00:00'>5:00pm</option>" +
								<!-- "<option value='18:00:00'>6:00pm</option>" +
								<!-- "<option value='19:00:00'>7:00pm</option>" +
								<!-- "<option value='20:00:00'>8:00pm</option>" +
								<!-- "<option value='21:00:00'>9:00pm</option>" +
								<!-- "<option value='22:00:00'>10:00pm</option>" +
								<!-- "</select><br>" + 
							<!-- "<br>" + -->
							"<b>Watering:</b><br>" +
							"Street trees need 15 to 20 gallons of water per week <br>" +
							"during the late spring, summer, and early fall.<br>" +
							"How many gallons of water did you give this tree?<br>" +
							"<input type=text size=4 name=water id=water /><br><br>" +
							"<b>Cultivating:</b><br>" +
							"The soil around street trees can get too compacted for <br>" +
							"roots to absorb water and oxygen. <br>" +
							"Cultivating the soil with a trowel can help. <br>" +
							"Did you cultivate the soil around this tree?<br>" +
							"<input type='radio' id='soil' name='soil' value='yes'>Yes<input type='radio' id='soil' name='soil' value='no'>No<br><br>" +
							"<b>Compost and Soil:</b><br>" +
							"Sometimes the soil in street tree pits runs out of the<br>" +
							"nutrients that a tree relies on to grow. <br>" +
							"Adding new soil or compost to the tree pit can help,<br>" +
							"especially if added after cultivation.<br>" +
							"Did you add compost or soil to the tree pit? <br>" +
							"<input type='radio' id='fertilizer' name='fertilizer' value='yes'>Yes<input type='radio' id='fertilizer' name='fertilizer' value='no'>No<br><br>" +
							"<b>Flowers and Plants:</b><br>" +
							"Growing flowers and plants in a street tree pit can help <br>" +
							"keep soil cultivated. A beautiful tree pit can also encourage <br>" +
							"dog owners to curb their dogs away from tree pits. <br>" +
							"Did you add plants or flowers to the tree pit?<br>" +							
							"<input type='radio' 'id='planting' name='planting' value='yes'>Yes<input type='radio' id='planting' name='planting' value='no'>No<br><br>" +
							"<b>Tree Pitguard:</b><br>" +
							"Did you add a pitguard to protect the tree?<br>" +
							"<input type=radio id='pitguard' name='pitguard' 'value='yes'>Yes<input type='radio' id='pitguard' name='pitguard' value='no'>No<br><br>" +
							"Additional comments: <input type=text size=34 name=comments id=comments /><br>" +
							"</DIV></DIV><br>"  +
						"<input type=button value='Submit Info' onclick='storeMaintenance(); return false;'>" +
        "</form>"
				);
		
		// select a data range
		
		var statistics = (
				"Please choose a time period for viewing watering history: <br>" +
				"<br>" +
					(
						"<form name='daterange'>" +
									"<input type=hidden name=id id=id value='" + point.id + "'/>" +
							"Start Date: <select id='syear' name='syear'>" +
							"<option value='0000'>choose...</option>" +
							"<option value='2009'>2009</option>" +
							"</select>" +
							" Month: <select id='smonth' name='smonth'>" +
							"<option value='00'>choose...</option>" +
							"<option value='01'>January</option>" +
							"<option value='02'>February</option>" +
							"<option value='03'>March</option>" +
							"<option value='04'>April</option>" +
							"<option value='05'>May</option>" +
							"<option value='06'>June</option>" +
							"<option value='07'>July</option>" +
							"<option value='08'>August</option>" +
							"<option value='09'>September</option>" +
							"<option value='10'>October</option>" +
							"<option value='11'>November</option>" +
							"<option value='12'>December</option>" +
							"</select>" +
							" Day: <select id='sday' name='sday'>" +
							"<option value='00'>choose...</option>" +
							"<option value='01'>01</option>" +
							"<option value='02'>02</option>" +
							"<option value='03'>03</option>" +
							"<option value='04'>04</option>" +
							"<option value='05'>05</option>" +
							"<option value='06'>06</option>" +
							"<option value='07'>07</option>" +
							"<option value='08'>08</option>" +
							"<option value='09'>09</option>" +
							"<option value='10'>10</option>" +
							"<option value='11'>11</option>" +
							"<option value='12'>12</option>" +
							"<option value='13'>13</option>" +
							"<option value='14'>14</option>" +
							"<option value='15'>15</option>" +
							"<option value='16'>16</option>" +
							"<option value='17'>17</option>" +
							"<option value='18'>18</option>" +
							"<option value='19'>19</option>" +
							"<option value='20'>20</option>" +
							"<option value='21'>21</option>" +
							"<option value='22'>22</option>" +
							"<option value='23'>23</option>" +
							"<option value='24'>24</option>" +
							"<option value='25'>25</option>" +
							"<option value='26'>26</option>" +
							"<option value='27'>27</option>" +
							"<option value='28'>28</option>" +
							"<option value='29'>29</option>" +
							"<option value='30'>30</option>" +
							"<option value='31'>31</option>" +
							"</select><br>" +
							"<br>" +
								"<br>" +
							"End Date: <select id='eyear' name='eyear'>" +
							"<option value='0000'>choose...</option>" +
							"<option value='2009'>2009</option>" +
							"</select>" +
							" Month: <select id='emonth' name='emonth'>" +
							"<option value='00'>choose...</option>" +
							"<option value='01'>January</option>" +
							"<option value='02'>February</option>" +
							"<option value='03'>March</option>" +
							"<option value='04'>April</option>" +
							"<option value='05'>May</option>" +
							"<option value='06'>June</option>" +
							"<option value='07'>July</option>" +
							"<option value='08'>August</option>" +
							"<option value='09'>September</option>" +
							"<option value='10'>October</option>" +
							"<option value='11'>November</option>" +
							"<option value='12'>December</option>" +
							"</select>" +
							" Day: <select id='eday' name='eday'>" +
							"<option value='00'>choose...</option>" +
							"<option value='01'>01</option>" +
							"<option value='02'>02</option>" +
							"<option value='03'>03</option>" +
							"<option value='04'>04</option>" +
							"<option value='05'>05</option>" +
							"<option value='06'>06</option>" +
							"<option value='07'>07</option>" +
							"<option value='08'>08</option>" +
							"<option value='09'>09</option>" +
							"<option value='10'>10</option>" +
							"<option value='11'>11</option>" +
							"<option value='12'>12</option>" +
							"<option value='13'>13</option>" +
							"<option value='14'>14</option>" +
							"<option value='15'>15</option>" +
							"<option value='16'>16</option>" +
							"<option value='17'>17</option>" +
							"<option value='18'>18</option>" +
							"<option value='19'>19</option>" +
							"<option value='20'>20</option>" +
							"<option value='21'>21</option>" +
							"<option value='22'>22</option>" +
							"<option value='23'>23</option>" +
							"<option value='24'>24</option>" +
							"<option value='25'>25</option>" +
							"<option value='26'>26</option>" +
							"<option value='27'>27</option>" +
							"<option value='28'>28</option>" +
							"<option value='29'>29</option>" +
							"<option value='30'>30</option>" +
							"<option value='31'>31</option>" +
							"</select><br>" +
							"<br>" +
								"<br>" +
						"<input type=button value='Submit Query' onclick='retrieveMaintenance(); return false;'>" +
					"</form>"
					) +
				"<br>" +
				"Total Water: <span id=myDiv>" +
				"</div>"
				); 
				
		var infoTabs = [
				new GInfoWindowTab("Tree Info", static),
				new GInfoWindowTab("Maintenance", dynamic),
				new GInfoWindowTab("Statistics", statistics)
		];
    marker.openInfoWindowTabsHtml(infoTabs);
	}
	
	GEvent.addListener(marker, 'click', showInfo);
	
}

function htmlEscape(str) {
  return str.replace('"', '&quot;');
  return str.replace("'", "&apos;");
}

function getMarkers(){	
	
	//get the json
	var request = GXmlHttp.create();
	request.open('GET', 'retrievePoints.php5' , true); 
		request.onreadystatechange = function () {
		if (request.readyState == 4) {
		response = eval('(' + request.responseText + ')');
	
		//get rid of old markers
		map.clearOverlays();
		
		makePointArrayFromJson(response);
	}
}
request.send(null);
}

function makePointArrayFromJson(pointArray) {
  // 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];
		makeCustomMarker(point);
  }
}

function getRadioValue(name) {
	var myRadioArray = document.getElementsByName(name);
	for (var i=0; i < myRadioArray.length; i++) {
	if (myRadioArray[i].checked) {
		return myRadioArray[i].value;
			}
		}
	}

function storeMaintenance() { 
		
  var id = document.getElementById('id').value;
  var lat = document.getElementById('lat').value;
	var lng = document.getElementById('lng').value;
	var steward_code = document.getElementById('steward_code').value;
	var year = (getSelectedValue('year'));
	var month = (getSelectedValue('month'));
	var day = (getSelectedValue('day'));
	//var time = (getSelectedValue('time'));
	var water = document.getElementById('water').value;
	
	var soil = (getRadioValue('soil'));
	var fertilizer = (getRadioValue('fertilizer'));
	var planting = (getRadioValue('planting'));
	var pitguard = (getRadioValue('pitguard'));
	
	var comments = document.getElementById('comments').value;
	
	// URL parameters to storeMarker.php must be in the form "?name=foo&param=value"
	//concatenates all the parameters into something that the server can read
  var serverParams = "?"
    + "&id=" + id
    + "&lat=" + lat
    + "&lng=" + lng
		+ "&steward_code=" + steward_code
		+ "&dateof=" + year + '-' + month + '-' + day
		+ "&add_water=" + water
		+ "&cultivate_soil=" + soil
		+ "&add_fertility=" + fertilizer
		+ "&add_underplanting=" + planting
		+ "&add_pitguard=" + pitguard
		+ "&comments=" + comments;
  
  // request to storeMarker.php on your server
  var request = GXmlHttp.create();
  request.open('GET', 'storeMaintenance.php5' + serverParams, true);
		request.onreadystatechange = function () {
		if (request.readyState == 4) {
		alert (request.responseText); 
		}
	}
	// this is sending the form inputs to the server
  request.send(null);
	
	// draw the new marker on the map (this assumes that storeMarker.php will always succeed)
	// we are not adding this point to the map, just adding it to the database as "pending"
	// addPoint(p);
	map.closeInfoWindow();
	
}

function getSelectedValue(id)
{

	var myOptionArray = document.getElementById(id);
	var mySelectedIndex =  myOptionArray.selectedIndex;
	return myOptionArray.options[mySelectedIndex].value;
}

function storeNewPoint() { 

  var lat = document.getElementById('lat').value;
	var lng = document.getElementById('lng').value;
	var steward_code = document.getElementById('steward_code').value;
	
	var species = (getSelectedValue('species'));
		
	var DBH = document.getElementById('DBH').value;
	var image = document.getElementById('image').value;	
	
	 var serverParams = "?"
		+ "&lat=" + lat
		+ "&lng=" + lng
		+ "&added_by=" + steward_code
		+ "&species_code=" + species
		+ "&DBH=" + DBH
		+ "&image1=" + image;
		
  // request to storeMarker.php on server
  var request = GXmlHttp.create();
  request.open('GET', 'storePendingPoints.php5' + serverParams, true);
	request.onreadystatechange = function () {
		if (request.readyState == 4) {
		alert (request.responseText); 
		}
	}
	// this is sending the form inputs to the server
  request.send(null);
	
	// draw the new marker on the map (this assumes that storeMarker.php will always succeed)
	// we are not adding this point to the map, just adding it to the database as "pending"
	// addPoint(p);
	map.closeInfoWindow();
}

function retrieveMaintenance() {
	
  var id = document.getElementById('id').value;
  var lat = document.getElementById('lat').value;
	var lng = document.getElementById('lng').value;

	var syear = (getSelectedValue('syear'));
	var smonth = (getSelectedValue('smonth'));
	var sday = (getSelectedValue('sday'));

	var eyear = (getSelectedValue('eyear'));
	var emonth = (getSelectedValue('emonth'));
	var eday = (getSelectedValue('eday'));
	
	var myDiv = document.getElementById('myDiv');

  var serverParams = "?"
	  + "&id=" + id
    + "&lat=" + lat
    + "&lng=" + lng
		+ "&startdate=" + syear + '-' + smonth + '-' + sday
		+ "&enddate=" + eyear + '-' + emonth + '-' + eday;
	
	//request to retrieveMaintenance.php5
	var request = GXmlHttp.create();
	request.open('GET', 'retrieveMaintenance.php5' + serverParams, true); 
		request.onreadystatechange = function () {
		if (request.readyState == 4) {
		var response = eval('(' + request.responseText + ')');
		myDiv.innerHTML = response.TotalWater + " gallons";
		}
	}
	request.send(null);
}	

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