var map, neighborhood_mgr, tree_mgr;

var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = '/tree_icons/tree_shadow.png';
baseIcon.iconSize = new GSize(12, 20);
baseIcon.shadowSize = new GSize(22, 20);
baseIcon.iconAnchor = new GPoint(6, 20);
baseIcon.infoWindowAnchor = new GPoint(5, 1);

function createMap() {
	if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("google_map"));
        map.addControl(new GLargeMapControl());
		map.addControl(new GHierarchicalMapTypeControl());
		map.disableDoubleClickZoom()
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
		map.setCenter(new GLatLng(42.95814995692838, -85.64688205718994), 15);

		GEvent.addListener(map, "dblclick", function(overlay, latlng) {
		  alert(map.getCenter());
		});

		neighborhood_mgr = new MarkerManager(map);
		tree_mgr = new MarkerManager(map);
		
		loadNeighborhoods();

	} else {
		alert('Browser not compatible');
	}
}

function loadNeighborhoods(){
	document.body.style.cursor='wait';
	var request = GXmlHttp.create();
	request.open("GET", 'tree-get_neighborhoods.php', true);
	request.onreadystatechange=function() {
		if (request.readyState==4) {
			var neighborhoods = eval('(' + request.responseText + ')');
			hoods = new Array();
			for(i in neighborhoods){
				//alert(neighborhoods[i]);
				//create the neighborhood icon with the tree count
				hoods.push(createNeighborhoodMarker(neighborhoods[i]));
				//add the polygon overlay
				map.addOverlay(drawPolygon(neighborhoods[i]['color'], neighborhoods[i]['coordinates'], neighborhoods[i]['neighborhood_id']));
				
			}
			//add the neighborhood markers to the manager and map
			neighborhood_mgr.addMarkers(hoods, 14, 15);
			neighborhood_mgr.refresh();

			document.body.style.cursor='auto';
		}
	}
	request.send(null);
}
//gets the neighborhood info and create a LabeledMarker out of the info
function createNeighborhoodMarker(n){
	var latlng = new GLatLng(n['center_point'][0], n['center_point'][1]);
	var icon = new GIcon();
	icon.image = 'http://easthillscouncil.org/tree_icons/'+n['icon'];
	icon.iconSize = new GSize(54, 54);
	icon.iconAnchor = new GPoint(27, 27);
	icon.infoWindowAnchor = new GPoint(49, 5);

	opts = {
		"icon": icon,
		"clickable": true,
		"labelText": n['tree_count']+'<span class="marker_note">trees</span>',
		"labelOffset": new GSize(-27, -27),
		"title": 'Click to view trees in the '+n['name']+' neighborhood'
	};
	var marker = new LabeledMarker(latlng, opts);
	//var handler = createMarkerClickHandler(marker, pointData.name, pointData.wp);	
	GEvent.addListener(marker, "click", function(latlng){
		triggerHood(latlng.lat(), latlng.lng(), neighborhood_id);
	});

	return marker;
}
//draws the polygon of the neighborhood
function drawPolygon(color, coordinates, neighborhood_id){
	//setup an array of the coordinates in GLatLng objects
	var latlngs = new Array();
	for(i in coordinates){
		latlngs.push(new GLatLng(coordinates[i][0], coordinates[i][1]));
	}
	//close it with the first point
	latlngs.push(new GLatLng(coordinates[0][0], coordinates[0][1]));
	var hood = new GPolygon(latlngs, "#"+color, 1, .8, "#"+color, .5);
	GEvent.addListener(hood, "click", function(latlng){
		triggerHood(latlng.lat(), latlng.lng(), neighborhood_id);
	});
	return hood;
}

//handle actions to show hood trees
function triggerHood(cLat, cLon, neighborhood_id){
	//zoom and pan to the center point
	map.setCenter(new GLatLng(cLat, cLon), 17);
	//clear current trees
	tree_mgr.clearMarkers();
	//load new ones
	loadTrees(neighborhood_id);
}



function loadTrees(sector){
	document.body.style.cursor='wait';
	var request = GXmlHttp.create();
	request.open("GET", 'tree-get_trees.php?sector='+sector, true);
	request.onreadystatechange=function() {
		if (request.readyState==4) {
			//alert(request.responseText);
			var trees = eval('(' + request.responseText + ')');
			var markers = new Array();
			for(i in trees){
				var point = new GLatLng(trees[i]['lat'], trees[i]['lon']);
				var opts = {
					title: trees[i]['common_name']+' - '+trees[i]['address']+' '+trees[i]['street']+' - '+trees[i]['tag'],
					icon: new GIcon(baseIcon, '/tree_icons/'+trees[i]['icon'])
				}
				var tree = new GMarker(point, opts);

				//add infowindow with max content from http://gmaps-samples.googlecode.com/svn/trunk/megawindow/maxcontent_ajax.html
				GEvent.addListener(tree, 'click', function() {
					var maxContentDiv = document.createElement('div');
					maxContentDiv.innerHTML = 'Loading...'
					info = this.getTitle().split(' - ');
					this.openInfoWindowHtml('<p><strong>'+info[0]+'</strong><br />'+info[1]+'</p><p class="note">Click the maximize button (<img src="/images/maximize_btn_bw.png" alt="button" />) above to get more information</p>',
					{	maxWidth: 200,
						maxHeight: 100,
						maxContent: maxContentDiv, 
						maxTitle: this.getTitle()
					});

					var iw = map.getInfoWindow();
					GEvent.addListener(iw, "maximizeclick", function() {
						GDownloadUrl("tree-info.php?tag="+info[2], function(data) {
							maxContentDiv.maxWidth = 300;
							maxContentDiv.innerHTML = data;
						});
					});
				});

				//add to the array
				markers.push(tree);
			}
			tree_mgr.addMarkers(markers, 16);
			tree_mgr.refresh();
			document.body.style.cursor='auto';
		}
	}
	request.send(null);
}