/*
Created:  ©2009 - The City of Davenport Iowa
Author:   Matthew Thompson
Comments: This code generates a Google based map of reported and cleared Police incidents in the City of
          Davenport Iowa. If you have any questions or comments, or would like to utilize any portion of 
		  this code please contact the author at mthompson@ci.davenport.ia.us for more information. Any
		  reuse without author permission prohibited.
*/

var map = null;
var geocoder;
var gOverlays = null;
var gNewOverlays = null;
var controlLoc = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10, 10));
var numResults;
var outdistance;
var address;
var bounds = new GLatLngBounds();
var baseaddress;
var radius;
var mapExtension;
var wardslayer = null;
var clearedStatus;
var clearType;
var cleardate;

//Create our custom icons
var iconBlue = new GIcon(); 
iconBlue.image = 'Assets/blue.png';
iconBlue.iconSize = new GSize(15, 15);
iconBlue.iconAnchor = new GPoint(6, 20);
iconBlue.infoWindowAnchor = new GPoint(5, 4);

var iconRed = new GIcon(); 
iconRed.image = 'Assets/red.png';
iconRed.iconSize = new GSize(15, 15);
iconRed.iconAnchor = new GPoint(6, 20);
iconRed.infoWindowAnchor = new GPoint(5, 4);

var iconGreen = new GIcon(); 
iconGreen.image = 'Assets/green.png';
iconGreen.iconSize = new GSize(15, 15);
iconGreen.iconAnchor = new GPoint(6, 20);
iconGreen.infoWindowAnchor = new GPoint(5, 4);

var iconPurple = new GIcon(); 
iconPurple.image = 'Assets/purple_test.png';
iconPurple.iconSize = new GSize(15, 15);
iconPurple.iconAnchor = new GPoint(6, 20);
iconPurple.infoWindowAnchor = new GPoint(5, 4);

var iconSearch = new GIcon(); 
iconSearch.image = 'Assets/search.png';
iconSearch.iconSize = new GSize(15, 15);
iconSearch.iconAnchor = new GPoint(11, 8);
iconSearch.infoWindowAnchor = new GPoint(5, 4);

var iconOrange = new GIcon(); 
iconOrange.image = 'Assets/orange.png';
iconOrange.iconSize = new GSize(15, 15);
iconOrange.iconAnchor = new GPoint(11, 8);
iconOrange.infoWindowAnchor = new GPoint(5, 4);

//Create our solved icons
var iconCleared = new GIcon(); 
//iconCleared.image = 'Assets/siren.gif';
iconCleared.image = 'Assets/cleared.png';
iconCleared.iconSize = new GSize(25, 25);
iconCleared.iconAnchor = new GPoint(6, 20);
iconCleared.infoWindowAnchor = new GPoint(5, 4);

var customIcons = [];
customIcons["Burglary - Residential"] = iconBlue;
customIcons["Burglary - Commercial"] = iconOrange;
customIcons["ROBBERY"] = iconRed;
customIcons["STOLEN VEHICLE"] = iconGreen;
customIcons["SEX CRIME"] = iconPurple;
customIcons["search"] = iconSearch;
customIcons["cleared"] = iconCleared;

/*	function showFacts() {
	document.getElementById('overlay').style.display = 'block';
	document.getElementById('over_quote').style.display = 'block';
}

function hideOverlay() {
	document.getElementById('overlay').style.display = 'none';
	document.getElementById('over_quote').style.display = 'none';
}*/

function load() { 
  if (GBrowserIsCompatible()) {
	//showFacts();
	geocoder = new GClientGeocoder();
	map = new GMap2(document.getElementById('map'));
	map.addControl(new GLargeMapControl(), controlLoc);
	document.getElementById('hitlist').innerHTML = '<p>Enter search criteria above</p>';
	map.enableScrollWheelZoom();
	map.setCenter(new GLatLng(41.523808649571734, -90.57652473449707), 12);
	
	showLimit();
	
	G_NORMAL_MAP.getMinimumResolution = function () { return 12 }; 
	G_NORMAL_MAP.getMaximumResolution = function () { return 19 };
	
  }
}

function makeRadius(center, distance, V, lcolor, lwidth, lopacity, fill, fillopacity) {
	
	//Convert from degrees to km
	var newlat = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	var newlng = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;
	
	var circlepoints = [];
	var V = parseInt(360/V);
	
	for(var i=0; i<=360; i+=V)
	{
	var p = new GLatLng(center.lat() + (distance/newlat * Math.cos(i * Math.PI/180)), center.lng() + (distance/newlng * Math.sin(i * Math.PI/180)));
	circlepoints.push(p);
	bounds.extend(p);
	}
	
	var circle = new GPolygon(circlepoints,lcolor,lwidth,lopacity,fill,fillopacity);
	map.addOverlay(circle);
	showLimit();
	
}

function searchLocations() {
   
 address = document.getElementById('addressInput').value + ' Davenport, Iowa';
 geocoder.getLatLng(address, function(latlng) {
   if (!latlng) {
	 alert(address + ' could not be found, please try again\nIf you continue to experience problems please try \nsearching locations near your desired location');
   } else if(verifyDate(document.getElementById('StartDate').value)) {
	   
	   var d = new Date();
	   var curr_day = d.getDate() - 7;
	   var curr_month = d.getMonth();
	   curr_month++;
	   var curr_year = d.getFullYear();
	   var dataend = curr_month + "/" + curr_day + "/" + curr_year;

	   alert('Map data is available from 01/01/2008 through ' + dataend + '\n\nPlease select an ending date within that time period and try again');
   } else {
	 baseaddress = latlng;
	 searchLocationsNear(latlng);
   }
 });
}

function searchLocationsNear(center) {
 document.getElementById('numres').innerHTML = 'Searching...';
 radius = document.getElementById('radiusSelect').value;
 var startdate = document.getElementById('StartDate').value;
 var duration = document.getElementById('duration').value;
 
 if(document.getElementById('t1').checked) {
	var t1 = "t"; 
 } else {
	var t1 = "f";
 }
 
  if(document.getElementById('t2').checked) {
	var t2 = "t"; 
 } else {
	var t2 = "f";
 }
 
  if(document.getElementById('t3').checked) {
	var t3 = "t"; 
 } else {
	var t3 = "f";
 }
 
  if(document.getElementById('t4').checked) {
	var t4 = "t"; 
 } else {
	var t4 = "f";
 }
 
  if(document.getElementById('t5').checked) {
	  var t5 = "t";
  } else {
	  var t5 = "f";
  }
 
 outdistance = radius; // Used to display the searched distance back to the user
 var searchUrl = 'genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&StartDate=' + startdate + '&duration=' + duration + '&t1=' + t1 + '&t2=' + t2 + '&t3=' + t3 + '&t4=' + t4 + '&t5=' + t5 + '&searchloc=' + address;
 
 GDownloadUrl(searchUrl, function(data) {
   var xml = GXml.parse(data);
   var markers = xml.documentElement.getElementsByTagName('marker');
   map.clearOverlays();
   var sidebar = document.getElementById('hitlist');
   sidebar.innerHTML = '';
   
   if (markers.length == 1) {
	 sidebar.innerHTML = 'No results found.';
	 alert("No results found for selected search criteria");
	 showLimit();
	 document.getElementById('numres').innerHTML = 'Search Results';
	 map.setCenter(new GLatLng(41.523808649571734, -90.57652473449707), 11);
	 return;
   }
   
   numResults = markers.length - 1;
   
   for (var i = 0; i < markers.length; i++) {
	 var name = markers[i].getAttribute('name');
	 var address = markers[i].getAttribute('address');
	 var outdate = markers[i].getAttribute('time');
	 var type = markers[i].getAttribute('type');
	 var distance = parseFloat(markers[i].getAttribute('distance'));
	 var desc = markers[i].getAttribute('desc');
	 clearedStatus = markers[i].getAttribute('clearedStatus');
	 cleardate = markers[i].getAttribute('cleardate');
	 var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
							 parseFloat(markers[i].getAttribute('lng')));
	 
	 var marker = createMarker(point, name, address, desc, outdate, type, clearedStatus);
	 map.addOverlay(marker);
	 
	 if(markers[i].getAttribute('name') != "Search Location") {
		var sidebarEntry = createSidebarEntry(marker, name, address, distance);
		sidebar.appendChild(sidebarEntry);
		bounds.extend(point);
	 }
	 
	 showLimit();
	 
   }
   
   if(radius != 15) {
	makeRadius(baseaddress, radius * 1.8, 60, '#1177ff', 2, .4, '#0055ff', .05);
   }
	
   map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
   
   if(document.getElementById('shwchk').checked) {
	
		showwards();
	
   }	   
   
 });
}

function createMarker(point, name, address, desc, outdate, type, clearedStatus) {
  if(clearedStatus == "cleared") {
	  type = "cleared";
  }
  var marker = new GMarker(point, customIcons[type]);
  if(name == "Search Location") {
	var html = '<p class="infowin"><b><span class="infname">' + name + '</span></b><br /><span class="infaddress">' + address + '</span></p>';
  } else {
	if(clearedStatus == "cleared") {
		if(clearType == "U") {
			clearOut = "Cleared";
		} else {
			clearOut = "Cleared";
		}
		var html = '<p class="infowin"><b><span class="infname">' + name + '</span></b><span class="infdate">Offense Date: ' + outdate + '</span><br /><span class="infaddress">Location: ' + address + '</span><br /><span class="infaddress">Status: ' + clearOut + '</span><br /><span class="infcleardate">Clear Date: ' + cleardate + '</span><span class="infaddress"><br /><br />If you have any information or would like to know more<br /> about this incident, please call (563) 888-3702<br /></span></p>';
	} else {
		var html = '<p class="infowin"><b><span class="infname">' + name + '</span></b><span class="infdate">Offense Date: ' + outdate + '</span><br /><span class="infaddress">Location: ' + address + '</span><span class="infaddress"><br /><br />If you have any information or would like to know more<br /> about this incident, please call (563) 888-3702<br /></span></p>';
	}
  }
  GEvent.addListener(marker, 'click', function() {
	marker.openInfoWindowHtml(html);
  });
  return marker;
}

function createSidebarEntry(marker, name, address, distance) {
  var div = document.createElement('div');
  var numholder = document.getElementById('numres');
  if(clearedStatus != "cleared") {
	var html = '<b><span class="resHeading">' + name + '</span></b> <span class="resDistance">(' + distance.toFixed(1) + ') miles</span><br/><span class="resAddress">' + address + '</span>';
  } else {
	var html = '<b><span class="resClearHeading">' + name + '</span></b> <span class="resClearDistance">(' + distance.toFixed(1) + ') miles</span><br/><span class="resClearAddress">' + address + '</span>';
  }
  div.innerHTML = html;
  if(outdistance == 15) {
	numholder.innerHTML = numResults + ' Results found within the city limits';
  } else {
	numholder.innerHTML = numResults + ' Results found within ' + outdistance + ' mile(s)';
  }
  div.style.cursor = 'pointer';
  div.style.marginBottom = '5px'; 
  GEvent.addDomListener(div, 'click', function() {
	GEvent.trigger(marker, 'click');
  });
  GEvent.addDomListener(div, 'mouseover', function() {
	div.style.backgroundColor = '#AFC8CF';
  });
  GEvent.addDomListener(div, 'mouseout', function() {
	div.style.backgroundColor = '#DDDDDD';
  });
  return div;
}

function showwards() {
	
	//create mapextension class to be used to add/remove results from the map.
	mapExtension = new esri.arcgis.gmaps.MapExtension(map);
	
	//create mapOptions to specify opacity, minResolution, maxResolution when adding to the map.
	var mapOptions = {opacity: 0.44, minResolution: 0, maxResolution: 19};
	if(document.getElementById('shwchk').checked) {
	//create custom tile layer
	var tiledmap = new esri.arcgis.gmaps.TiledMapServiceLayer("http://gis.ci.davenport.ia.us/ArcGIS/rest/services/Ward_Map/MapServer/", mapOptions, addTiledMap);
	  
	} else {
		
		mapExtension.removeFromMap(gOverlays);

	}
}

function addTiledMap(gTileLayer) {
	//Add tile layer as a GTileLayerOverlay using mapExtension
	wardslayer = gTileLayer;
	gOverlays = mapExtension.addToMap(wardslayer);
}



function showLimit() {
	
	//create mapextension class to be used to add/remove results from the map.
	mapExtension = new esri.arcgis.gmaps.MapExtension(map);
	
	//create mapOptions to specify opacity, minResolution, maxResolution when adding to the map.
	var mapOptions = {opacity: 1, minResolution: 0, maxResolution: 19};
	//create custom tile layer
	var tiledmap = new esri.arcgis.gmaps.TiledMapServiceLayer("http://gis.ci.davenport.ia.us/ArcGIS/rest/services/City_Limit/MapServer/", mapOptions, addTiledMap);

}

function addTiledMap(gTileLayer) {
	//Add tile layer as a GTileLayerOverlay using mapExtension
	limitlayer = gTileLayer;
	gOverlays = mapExtension.addToMap(limitlayer);
}