﻿var map;
var bmap;
var bmapElement;
var bmapCenter;
var bmapZoom = false;
var projects;
var teamMembers;
var geocoder;
var myLocation = null;
	
G_PHYSICAL_MAP.getMinimumResolution = function()
{
	return 2;
}
		
G_PHYSICAL_MAP.getMaximumResolution = function()
{
	return 9;
}

G_HYBRID_MAP.getMinimumResolution = function()
{
	return 2;
}

G_SATELLITE_MAP.getMinimumResolution = function()
{
	return 2;
}

	
		var smallPinIconLeft = new GIcon();
		smallPinIconLeft.image = "images/map/small-pin-left.png";
		smallPinIconLeft.shadow = "images/map/small-pin-shadow.png";
		smallPinIconLeft.transparent = "images/map/small-pin-left-transparent.png";
		smallPinIconLeft.iconSize = new GSize(32, 27);
		smallPinIconLeft.shadowSize = new GSize(32, 27);
		smallPinIconLeft.iconAnchor = new GPoint(11, 25);
		smallPinIconLeft.infoWindowAnchor = new GPoint(5, 1);
		smallPinIconLeft.imageMap = [0,0, 14,0, 14,27, 0,27];
		
		
		var smallPinIconRight = new GIcon(smallPinIconLeft);
		smallPinIconRight.image = "images/map/small-pin-right.png";
		smallPinIconRight.transparent = "images/map/small-pin-right-transparent.png";
		smallPinIconRight.infoWindowAnchor = new GPoint(15, 1);
		smallPinIconRight.imageMap = [6,0, 21,0, 21,27, 6,27];
		
		// Image icon - square
		var labelIcon = new GIcon();
		labelIcon.shadow = "images/map/shadow-icon.png";
		labelIcon.transparent = "images/map/transparent-icon.png";
		labelIcon.iconSize = new GSize(62, 62);
		labelIcon.shadowSize = new GSize(126, 64);
		labelIcon.iconAnchor = new GPoint(31, 62);
		labelIcon.dragCrossAnchor = new GPoint(0, 31);
		
		var largePinIcon = new GIcon();
		largePinIcon.image = "images/map/large-pin.png";
		largePinIcon.shadow = "images/map/large-pin-shadow.png";
		largePinIcon.transparent = "images/map/large-pin-transparent.png";
		largePinIcon.iconSize = new GSize(36, 40);
		largePinIcon.shadowSize = new GSize(36, 40);
		largePinIcon.iconAnchor = new GPoint(5, 34);
		largePinIcon.infoWindowAnchor = new GPoint(12, 1);
		largePinIcon.imageMap = [0,0, 20,0, 20,38, 0,38];
		
		var dotIcons = []
		for (var i = 1; i < 6; i++)
		{
			var x = i + 6;
			var m = Math.ceil(i / 2) + 3
			var dotIcon = new GIcon();
			dotIcon.image = "images/map/dot" + i + ".png";
			dotIcon.shadow = "images/map/dot" + i + "-transparent.png";
			dotIcon.transparent = "images/map/dot" + i + "-transparent.png";
			dotIcon.iconSize = new GSize(x, x);
			dotIcon.shadowSize = new GSize(x, x);
			dotIcon.iconAnchor = new GPoint(m, m);
			dotIcon.infoWindowAnchor = new GPoint(m, 1);
			dotIcons.push(dotIcon);
		}
		
function miniZoom()
{
	if (bmapZoom)
	{
		bmap.setCenter(bmapCenter, 8, G_PHYSICAL_MAP);
	}
	else
	{
		bmap.setCenter(bmapCenter, 18, G_SATELLITE_MAP);
	}
	bmapZoom = !bmapZoom;
}

function showOnMainMap()
{
	if (!bmapZoom)
	{
		map.setCenter(bmapCenter, 8);
	}
	else
	{
		// Force a map change - can't zoom that far on G_PHYSICAL_MAP.
		map.setCenter(bmapCenter, 17, G_HYBRID_MAP);
	}
	map.closeInfoWindow();
}

function load()
{
	if (GBrowserIsCompatible())
	{
	
		bmap = null;
		bmapElement = document.getElementById("bmap");
		bmapCenter = new GLatLng(10.00, 0.0);
		
		var copyCollection = new GCopyrightCollection('Overlay');
		var copyright = new GCopyright(42, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, "©2007 UserFriendly.Org");
		copyCollection.addCopyright(copyright);
		
		var hivOverlay = new GTileLayerOverlay(
			new UfTileLayer("hiv", [ "fff", "6effffff7f21", "0c001c78383efffffffffdffb9feddfc1eef0ee70c030c" ], copyCollection)
		);

		var yfOverlay = new GTileLayerOverlay(
			new UfTileLayer("yf", [ "066", "0000003c38", "00000000000000000000000001c00de00ec004" ], copyCollection)
		);
		
		var malariaOverlay = new GTileLayerOverlay(
			new UfTileLayer("malaria", [ "0ff", "00000e7e7f2", "00000000000000000000007c31fc1dfc1eef0ee00c" ], copyCollection)
		);
		
		

		map = new GMap2(document.getElementById("map"), { mapTypes:[G_PHYSICAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP] });
		geocoder = new GClientGeocoder();
		
		map.setCenter(new GLatLng(10.00, 0.0), 2);
		
		var mapControl = new GHierarchicalMapTypeControl();
    mapControl.clearRelationships();
    mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", true);

		var legendControl = new OverlayLegendControl();
		legendControl.addRelationship(hivOverlay, "HIV", document.getElementById("hiv-legend"));
		legendControl.addRelationship(yfOverlay, "Yellow Fever", document.getElementById("yf-legend"));
		legendControl.addRelationship(malariaOverlay, "Malaria", document.getElementById("malaria-legend"));
				
		map.addControl(new GSmallZoomControl());
		map.addControl(new ResetZoomControl());
		map.addControl(mapControl);
		map.addControl(legendControl);
		
		//map.addControl(new GOverviewMapControl());
				
		//map.disableDragging();
		//map.enableScrollWheelZoom();
		//map.enableContinuousZoom();
		new GKeyboardHandler(map);
		
		mgr = new MarkerManager(map);
		
		projects = [
			new Project("hpf1", "Human Proteome Folding", 47.64777419812832, -122.33923584222794,
				39.1, -156.1, 0, false),
			new Project("hcc", "Help Conquer Cancer", 43.659695, -79.38747,
				65.2, -110.7, 1, true),
			new Project("hpf2", "Human Proteome Folding - Phase 2", 40.73025887998484,-73.99544924497604,
				38.8, -30.6, 1, true),
			new Project("ach", "AfricanClimate@Home", -33.957172, 18.459842,
				-40.2, 68.2, 0, true),
			new Project("gc", "Genome Comparison", -22.87488025419358, -43.24543833732605,
				-45.3, -17.2, 1, false),
			new Project("hcmd", "Help Cure Muscular Dystrophy", 48.837927, 2.360891,
				60.2, 61.9, 0, false),
			new Project("hdc", "Help Defeat Cancer", 40.49640908441156, -74.44904834032059,
				15.3, -38.3, 0, false),
			new Project("faah", "FightAIDS@Home", 32.89515546480429, -117.2427088022232,
				3.5, -135.7, 1, true),
			new Project("dddt", "Discovering Dengue Drugs – Together", 29.310491701759307, -94.77969646453857,
				-32.2, -108.6, 0, true),
			new Project("nrw", "Nutritious Rice for the World", 47.62346121128495,-122.33751654624939,
				35.1, -152.1, 1, true)
		];
		
		teamMembers = new Array();
		
		var infoWindowResetMap = false;	
		GEvent.addListener(map, "infowindowbeforeclose", function()
			{
				if (map.getZoom() == 2)
				{
					infoWindowResetMap = true;
					setTimeout(function()
						{
							if (infoWindowResetMap)
							{
								map.panTo(new GLatLng(10.00, 0.0));
							}
						}, 400
					);
				}
			}
		);
	
		GEvent.addListener(map, "infowindowopen",
			function() { infoWindowResetMap = false; }
		);

		GEvent.addListener(map, "zoomend", function(oldLevel, newLevel)
			{
				if (newLevel == 2)
				{
					map.panTo(new GLatLng(10.00, 0.0));
				}
				
				for (var i = 0; i < projects.length; i++)
				{
					projects[i].update(newLevel);
				}
			}
		);

		GEvent.addListener(map, "moveend", function()
			{
				for (var i = 0; i < projects.length; i++)
				{
					projects[i].update(map.getZoom());
				}
			}
		);

		var info = map.getInfoWindow();
		
		GEvent.addListener(info, "maximizeend", function()
			{
				bmapElement.style.display = "block";
				var mapChild = bmapElement.getElementsByTagName("div")[0];
				setTimeout(function()
					{
						bmapZoom = false;
						bmap = new GMap2(mapChild, { mapTypes:[G_PHYSICAL_MAP, G_HYBRID_MAP] });
						
						bmap.setCenter(bmapCenter, 8);
						bmap.disableDragging();
					}
				);	
			}
		);

		GEvent.addListener(info, "restoreend",
			function() { bmap = null; }
		);
		
		resize();
		window.onresize = resize;
		
		var disabledDefSWZoom = false;
		var mapDiv = map.getContainer();

	// Remove handling of default scrolling action
	if ( mapDiv.addEventListener ){
		// W3C
		mapDiv.addEventListener( 'DOMMouseScroll', doNotPropagate,
	false );
		disabledDefSWZoom = true ;
	} else {
		// IE
		mapDiv.onmousewheel = doNotPropagate ;
		disabledDefSWZoom = true ;
	}

	// Add zooming
	map.enableDoubleClickZoom() ;
	map.enableContinuousZoom() ;
	if ( disabledDefSWZoom ){
		map.enableScrollWheelZoom() ;
	} 
	
	// Add logged in member marker:
		if (document.getElementById("edit-location"))
		{
			var lat = document.getElementById("lat").value;
			var lng = document.getElementById("lng").value;
			if ((lat != "") && (lng != ""))
			{
				var location = new GLatLng(lat, lng);
				myLocation = new GMarker(location, {icon:largePinIcon, title:"My Location"});
				map.addOverlay(myLocation);
			}
		}

	}
	else
	{
		// show alt content
	}
}

function resize()
{
	var width = document.getElementsByTagName("body")[0].clientWidth;
	//var width = window.innerWidth;
	var offset = (width - 1026) / 2;
	var mapElement = map.getContainer();
	if (offset < 0)
	{
		mapElement.style.left = "0";
		mapElement.style.width = (width - 2) + "px";
	}
	else
	{
		mapElement.style.left = offset + "px";
		mapElement.style.width = "1024px";
	}
}

function doNotPropagate(e)
{
	if (!e)
	{
		e = window.event ;
	}
	e.returnValue = false;
	e.cancelBubble = true;
	if (e.preventDefault && e.stopPropagation)
	{
		// W3C (Firefox, Safari, etc)
		e.preventDefault() ;
		e.stopPropagation() ;
	}
}

function suppressEnter(e)
{
	if (!e)
	{
		e = window.event;
	}
	return (e.keyCode != 13);
}

function searchEnter(e)
{
	var useDefault = suppressEnter(e);
	if (!useDefault)
	{
		showLocation();
	}
	return useDefault;	
}

function showActiveProjects()
{
	var show = document.getElementById("inactive").checked;
	for (var i = 0; i < projects.length; i++)
	{
		if (show)
		{
			projects[i].setVisible(true);
		}
		else
		{
			projects[i].setVisible(projects[i].active);
		}
	}
}

function showProjectImages()
{
	var show = document.getElementById("images").checked;
	for (var i = 0; i < projects.length; i++)
	{
		projects[i].setShowLabel(show);
	}
}

function showTeamMembers()
{
	var show = document.getElementById("show").checked;
	if (show)
	{
		GDownloadUrl("ajax/members.jspx", function(data, responseCode)
		{
		  var xml = GXml.parse(data);
		  var markers = xml.documentElement.getElementsByTagName("member");

		  for (var i = 0; i < markers.length; i++)
			{
		    var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
		                            parseFloat(markers[i].getAttribute("lng")));
		    var title = markers[i].getAttribute("name");
		    var size = parseInt(markers[i].getAttribute("size"));
		    var minZoom = parseInt(markers[i].getAttribute("minZoom"));
		    var maxZoom = parseInt(markers[i].getAttribute("maxZoom"));
		    
		    var member = makeMarker(point, size, title, minZoom, maxZoom);
		    
		    if (maxZoom < 100)
		    {
		     	mgr.addMarker(member, minZoom, maxZoom);
		    }
		    else
		    {
      		mgr.addMarker(member, minZoom);
      	}

		    teamMembers.push(member);
		  }
		});
	}
	else
	{
		mgr.clearMarkers()
		teamMembers = new Array();
	}
}

function makeMarker(point, size, title, minZoom, maxZoom)
{
	if (size > 1)
	{
		title = size + " members (click to zoom)";
	}
	
	var iconIndex = Math.min(size - 1, 4);
	var member = new GMarker(point, { title:title, icon:dotIcons[iconIndex] });
	
	if (size > 1)
	{
		GEvent.addListener(member, "click", function() {
	  		map.setCenter(point, maxZoom + 1);
			});
	}
	return member;
}

function showLocation()
{
	var address = document.getElementById("address").value;
	geocoder.getLocations(address, addAddressToMap);
}
    
// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response)
{

	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to find that address");
	}
	else
	{
		if (myLocation != null)
		{
			map.removeOverlay(myLocation);
		}
		place = response.Placemark[0];
		point = new GLatLng(
			place.Point.coordinates[1],
			place.Point.coordinates[0]);

		// Massage address accuracy into a (completely fake) positional error in km.
		// 4 = max error, 8 = min error.
		var error = Math.min(8 - place.AddressDetails.Accuracy, 4);
		error = Math.pow(error, error) / 256.0;
		
		// Source of gaussian random generator:
		// http://www.taygeta.com/random/gaussian.html
		var x1 = Math.random();
		var x2 = Math.random();
	
		var y1 = Math.sqrt(-2 * Math.log(x1)) * Math.cos(2 * Math.PI * x2);
		var y2 = Math.sqrt(-2 * Math.log(x1)) * Math.sin(2 * Math.PI * x2);
		
		//Base distance will be 0.01 degrees (about 1 km at the equator)
		y1 = y1 * 0.01 * error;
		y2 = y2 * 0.01 * error;
		
		var location = new GLatLng(point.lat() + y1, point.lng() + y2);
		
		document.getElementById("lat").value = location.lat();
		document.getElementById("lng").value = location.lng();
		myLocation = createAddressMarker(location);
		map.addOverlay(myLocation);
		
		myLocation.openInfoWindowHtml("<p>" + place.address + "</p>",
		{maxWidth:300});
	}
}

function createAddressMarker(location)
{
		var marker = new GMarker(location, {draggable:true,
icon:largePinIcon, bouncy:false, title:"Drag to reposition"});

		GEvent.addListener(marker, "dragstart", function()
		{
			marker.setImage("images/map/large-pin-float.png");
			map.closeInfoWindow();
		}
		);
		
		GEvent.addListener(marker, "dragend", function()
		{
			marker.setImage("images/map/large-pin.png");
			var point = myLocation.getLatLng();
			
			document.getElementById("lat").value = point.lat();
			document.getElementById("lng").value = point.lng();
		}
	);
	return marker;
}

function startEdit()
{
	document.getElementById("static-location").style.display = "none";
	document.getElementById("edit-location").style.display = "block";
	
	if (myLocation != null)
	{
		var location = myLocation.getLatLng();
		map.removeOverlay(myLocation);
		myLocation = createAddressMarker(location);
		map.addOverlay(myLocation);
		myLocation.openInfoWindowHtml("<p>Search for a new address, or drag to fine-tune.</p>",
		{maxWidth:300});
	}
}