//mainMap.js
//This file contains the main map functions and variables for stickymap.
// Taken out of mappage.php, June 9, 2006, by: Max Sklar

//The main map object (see google maps api)
var map;
	
//This is the last marker that was clicked.
var currentMarker;
var currentMarkerPoint;

//This is the last icon that the user clicked.  The number will be used in iconDatabase to get the data from the icon.
var currentIcon;

//This is the last marker ID that we've used.  This is very important if we want to go back into the database
// to find more information about the marker.
//Eventually -> combine this all into a struct?
var currentTitle;
var currentID;
var currentDescription;
var currentMinZoom;
var currentMaxZoom;
var currentOrgs;
var currentSecurity;
var currentOwner;

//Get the icon database that was loaded in loadIcons.php
// iconDatabase[currentIcon][0] is the name
// iconDatabase[currentIcon][1]  is the google maps icon object
// iconDatabase[currentIcon][2] is the icon id number in our mysql database.
var iconDatabase = getIconDatabase();

//This sample marker will be used to add samples to the map while creating and editing.
var sampleMarker;

//Are we in the process of moving the marker?
var movingMarker = false;

//Keep track of the old boundaries of the map while the map is moving.
var oldBounds;

//Are in in the view list mode?  If so, this is the number of the list.
var inViewListMode = 0;

//Map controls
var mapZoomControl = new GLargeMapControl();
var mapSmallZoomControl = new GSmallMapControl();

mapSmallZoomControl.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT,  new GSize(5, 40));
}

var mapTypeControl = new GMapTypeControl();
var mapOverviewControl = new GOverviewMapControl();
var mapScaleControl = new GScaleControl();

function onLoad() {	
	//Check for Browser Compatibility,  quit gracefully if not compatible.
	if (!GBrowserIsCompatible()) {
		alert("There was a problem loading the page.  You may have the wrong browser.");
		return;
	}
	
	initializeMap();
	addMapListeners();
	switchTab(initialTab);
}
		
//In this function, we initialize the map.
function initializeMap() {
	//Create the map
	var mapDiv = document.getElementById("map");
	map = new GMap2(mapDiv);
	map.addControl(mapSmallZoomControl);
	map.addControl(mapTypeControl);
	map.enableDoubleClickZoom();
	map.enableScrollWheelZoom();

	GEvent.addDomListener(mapDiv, "DOMMouseScroll", wheelevent);
	mapDiv.onmousewheel = wheelevent;

	function findCenter_nonGeocode() {
		if (pointedLat && pointedLng) {
			if (!pointedZoom) pointedZoom = 15;
			map.setCenter(new GLatLng(parseFloat(pointedLat), parseFloat(pointedLng)), parseInt(pointedZoom));
		}
		else {
			defaultCenterAndZoom();
		}
	}

	function makeGeocodeCallback() {
		return function(point) {
			if (point) {
				if (!pointedZoom) pointedZoom = 15;
				map.setCenter(point, parseInt(pointedZoom));
			}
			else findCenter_nonGeocode();
			loadMarkers();
		}
	}
		
	if (pointedLoc) {
		geocoder = new GClientGeocoder();
		geocoder.getLatLng(pointedLoc, makeGeocodeCallback());
	}
	else {
		findCenter_nonGeocode();
		loadMarkers();
	}
}

function wheelevent(e) {
	if (!e) e = window.event;
	if (e.preventDefault) e.preventDefault();
	e.returnValue = false;
	hideToolTip();
}

function defaultCenterAndZoom() {
	map.setCenter(TIMES_SQUARE, 15);
}

function exitExplorerMode() {
	document.getElementById("map_explorer_container").style.display = "none";
}

function enterExplorerMode() {
	inViewListMode = 0;
	//loadMarkers();
}

//This function loads the markers in from the database.
function loadMarkers() {
	if (isMarkerBeingCreated) {
		if (markerCreation_placementFinalized) return;
		GEvent.clearListeners(markerBeingCreated, "infowindowclose");
	}
	
	map.clearOverlays();
	
	if (isMarkerBeingCreated) {
		addMarkerBeingCreatedToMap();
	}
	
	//get bounds
	var bounds = map.getBounds();
	var sw = bounds.getSouthWest();
	var ne = bounds.getNorthEast();
	
	var apparentZoomLevel = map.getZoom();
	
	var URL = "";
	URL += "getMarkersXml.php?";
	URL += "zoom=" + apparentZoomLevel;
	URL += "&maxLat=" + ne.lat() + "&minLat=" + sw.lat() + "&maxLng=" + ne.lng() + "&minLng=" + sw.lng();
	URL += "&mapWidth=" + map.getSize().width + "&mapHeight=" + map.getSize().height;
	
	doWithFile(URL, true, function(xmlDoc) {
		//If the zoom level has changed, stop right here because a new batch is coming.
		if (map.getZoom() != apparentZoomLevel) return;
		
		var markers = xmlDoc.documentElement.getElementsByTagName("marker");
		
		//Go through each marker.
		for(var i = 0; i < markers.length; i++) {
			//This line of code is here in case the zoom level is changed as the markers are loading.
			if (map.getZoom() != apparentZoomLevel) break;
		
			var markerInfo = markers[i];
		
			var point = new GLatLng(markerInfo.getAttribute("y"), markerInfo.getAttribute("x"));
			var title = markerInfo.getAttribute("title");
			var id = markerInfo.getAttribute("id");
			var iconid = markerInfo.getAttribute("icon");
			
			createMarker(point, title, iconid, id);		
		}
	});
}
		
		function createMarker(point, title, iconid, id) {
			var iconNumber = getIconDbNumber(iconid);
			var icon = iconDatabase[iconNumber][1];
			var marker = new GMarker(point, icon);
			map.addOverlay(marker);

			GEvent.addListener(marker, 'mouseover', function() {
				displayTitleToolTip(title + BR + "<span style='font-size : xx-small'>Click for details.</span>");
			});
			
			GEvent.addListener(marker, 'mouseout', function() {
				hideToolTip();
			});

			GEvent.addListener(marker, 'click', function() {
				hideToolTip();
							
				currentTitle = title;
				currentIcon = iconNumber;
				currentMarker = marker;
				currentMarkerPoint = point;
				
				loadMarkerID(id);
			});
		}

		var theObj="";

//Tool tip stuff
//-----------------

function displayTitleToolTip(text) {
	document.getElementById('titleToolTip').innerHTML=text;
	document.getElementById('titleToolTip').style.display="block";
	document.onmousemove = updateToolTipPos;
	window.onscroll=updateToolTipPos;
}

function updateToolTipPos() {
	var ev=arguments[0]?arguments[0]:event;
	var x=mouseX(ev);
	var y=mouseY(ev);
	diffX=24;
	diffY=0;
	document.getElementById('titleToolTip').style.top  = y-2+diffY+"px";
	document.getElementById('titleToolTip').style.left = x-2+diffX+"px";
}

function hideToolTip() {
  document.getElementById('titleToolTip').style.display="none";
  document.onmousemove = null;
}

//Find mouse position
// Difficult because its different on different browsers.
function mouseX(evt) {
	if (evt.pageX) return evt.pageX;
	else if (evt.clientX)
	   return evt.clientX + (document.documentElement.scrollLeft ?
	   document.documentElement.scrollLeft :
	   document.body.scrollLeft);
	else return null;
}

function mouseY(evt) {
	if (evt.pageY) return evt.pageY;
	else if (evt.clientY)
	   return evt.clientY + (document.documentElement.scrollTop ?
	   document.documentElement.scrollTop :
	   document.body.scrollTop);
	else return null;
}
		
		//Look at the database and load the marker with this particular ID.
		//Then, the marker is loaded for viewing (with description)
		function loadMarkerID(id) {
			currentID = id;
			
			var filename = "/getMarkerInfo.php?id=" + id;
			//The IE bug: it appears that getMarkerInfo.php?id=x is stored in the cache.
			//So, we'll also give it a random number so that it thinks its accessing a different page.		
			filename += "&iebug=" + Math.random();
			
			doWithFile(filename, true, function(xmlDoc) {
				var markers = xmlDoc.documentElement.getElementsByTagName("marker");
				var marker = markers[0];
				
				//Set the variables
				currentMinZoom = marker.getAttribute("minZoom");
				currentMaxZoom = marker.getAttribute("maxZoom");
				currentOrgs = marker.getAttribute("orgs");
				currentSecurity = marker.getAttribute("security");
				currentOwner = marker.getAttribute("owner");
				
				//Now get the description and output the text.
				var descFile = "/getMarkerDescription.php?id=" + id + "&iebug=" + Math.random();
				doWithFile(descFile, false, function(text) {
					currentDescription = text;
					viewText();
				});
			});
		}
		
function addMapListeners() {		
	//This event listener handles a click - adds and takes away markers on clicks.
	GEvent.addListener(map, 'click', function(overlay, point) {
		if (overlay) return;
		if (!point) return;
		
		if (isMarkerBeingCreated) {
			GEvent.clearListeners(markerBeingCreated, "infowindowclose");
		}

		//Check to see if we're in creation mode.  If so, we have work to do.
		if (isPlacingNewMarker) {
			if (!markerCreation_clickedOkayInCreateIcon) clickedOkayInCreateIcon();
			clickedToPlaceNewMarker(point);
		}
		else if (movingMarker) {
			clickedOnMapToMoveMarker(point);
		}
	});
	
	//This Event listener handles a zoom change
	GEvent.addListener(map, 'zoomend', function(oldZoomLevel, newZoomLevel) {
		changedZoomLevel();
	});

	GEvent.addListener(map, 'moveend', function() {
		if (map.getInfoWindow().isHidden()) {
			loadMarkers();
		}
	});
}

var currentlyViewingMarker = false;
		
//This function places the contents of the textfile into message.
//Then, moves us there.
function viewText() {
	closeCreation();
	
	document.title = "Stickymap - " + currentTitle;
	
	var contentFile = "localNetwork/localPage.php?mid=" + currentID;
	
	if (BrowserDetect.browser == "Explorer")
		contentFile += "&iebug=" + Math.random();
	
	var infoHtml = "<iframe id='localNetFrame' name='localNetFrame' src='"+contentFile+"'";
	infoHtml += "frameborder='0' marginwidth='0' marginheight='0' vspace='0' hspace='0'";
	infoHtml += "width='280px' height='180px' scrolling='yes' style='overflow-x: hidden;'></iframe>";
	
	currentlyViewingMarker = true;
	
	currentMarker.openInfoWindowHtml(infoHtml, {autoScroll:true});
	
	GEvent.addListener(currentMarker, 'infowindowclose', function() {
		currentlyViewingMarker = false;
	});
}

function doesUserMatchOwner() {
	if (!userInfo) return 0;
	if (userInfo.id == 0) return 0;
	
	return (currentOwner == userInfo.id)
}

function dumpMarkerInfo() {
	document.getElementById("marker_info_area").style.display = "";
}

		//This function takes an icon ID number, and returns the icon database number that contains this id.
		function getIconDbNumber(iconID) {
			for(var i = 0; i < iconDatabase.length; i++)
				if (iconID == iconDatabase[i][2])
					return i;
		}

		function moveMarker() {
			movingMarker = true;
			document.getElementById("moveMode").style.display = "block";
			alert("Click on the map where you would like to move this marker.");
		}
		
		function exitMoveMarker() {
			movingMarker = false;
			document.getElementById("moveMode").style.display = "none";
		}
		
		function clickedOnMapToMoveMarker(point) {
			var file = 'editMarker.php';
			var icon = iconDatabase[currentIcon][2];
			
			//Post the values to a string:
			var str = "";
			str += createPostStatement("latitude", point.y);
			str += createPostStatement("longitude", point.x);
			str += createPostStatement("user", userInfo.id);
			str += createPostStatement("markerID", currentID);
			str += createPostStatement("editedTitle", currentTitle);
			str += createPostStatement("editedText", currentDescription);
			str += createPostStatement("submit", 1);
			str = str.substr(0,(str.length - 1));  //Get rid of last ampersand

			postWithFile(file, false, str, function(response) {
				alert(response);
				exitMoveMarker();
				loadMarkers();
			});
		}
		
//Recenter the Map to a point, goto map explorer
function recenter(point) {
	doWithFile("stats/recordAction/didAction.php?action=11", false, function(text) {	});
	if ((currentTab != EXPLORER_TAB) && (currentTab != SEARCH_TAB)
		&& (currentTab != CREATION_TAB) && (currentTab != SIFTER_TAB))
		switchTab(EXPLORER_TAB);
	map.setCenter(point, 13);
	changedZoomLevel();
}

function recenterAndZoom(point, zoom) {
	doWithFile("stats/recordAction/didAction.php?action=11", false, function(text) {	});
	if ((currentTab != EXPLORER_TAB) && (currentTab != SEARCH_TAB)
		&& (currentTab != CREATION_TAB) && (currentTab != SIFTER_TAB))
		switchTab(EXPLORER_TAB);
	map.setCenter(point, zoom);
	changedZoomLevel();
}

function changedZoomLevel() {
	if (map.getZoom() < 1) map.setZoom(1);
	if (lockOn17) map.setZoom(17);
}

function justCreatedMarker(mid) {
	map.closeInfoWindow();
	loadMarkers();
}
