//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;

//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();
var mapTypeControl = new GMapTypeControl();
var mapOverviewControl = new GOverviewMapControl();
var mapScaleControl = new GScaleControl();

function onLoad() {
	//Get the email and password input variables.  Trick using php, but they can also be grabbed with javascript.
	var email = getCookie("email");
	var enc_password = getCookie("enc_password");
			
	userInfo = new UserStruct("", "", 0, "Anonymous");
	
	if (email && enc_password && !isActivating)
		loginToStickymapFromCookie(email, enc_password);
	
	//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.  This error was generated by the Stickymap programmer Max Sklar.");
		return;
	}

	initializeMap();
	adjustMapSize();
	addMapListeners();
	
	if (doSearchAtStart) {
		doSearch();
	} else {
		loadMarkers();
		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(mapZoomControl);
	map.addControl(mapTypeControl);
	map.addControl(mapOverviewControl);
	map.addControl(mapScaleControl);
	map.enableDoubleClickZoom();
	map.enableScrollWheelZoom();

	GEvent.addDomListener(mapDiv, "DOMMouseScroll", wheelevent);
	mapDiv.onmousewheel = wheelevent; 
	
	//Get all data from cookie
	var lat = getCookie('Latitude');
	var lng = getCookie('Longitude');
	var zoom = getCookie('Zoom');

	if (pointedLat && pointedLng) {
		if (!pointedZoom) pointedZoom = 15;
		map.setCenter(new GLatLng(parseFloat(pointedLat), parseFloat(pointedLng)), parseInt(pointedZoom));
	}
	else if (!lat || !lng || !zoom) defaultCenterAndZoom();			
	else {
		map.setCenter(new GLatLng(lat, lng), parseInt(zoom));
	}
}

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() {
			setMapSize(MAP_SIZE_STANDARD);
			document.getElementById("map_explorer_container").style.display = "block";
			inViewListMode = 0;
			loadMarkers();
		}

		//This function loads the markers in from the database.
		function loadMarkers() {
			if (mapViewMode == MAP_VIEW_SIFTER) {
				iconSortLoadMarkers(getSelectedIcon("sifter_icon_choices"));
				return;
			}
			
			if (mapViewMode == MAP_VIEW_SEARCH) {
				return;
			}
			
			if (isMarkerBeingCreated) {
				return;
			}
			
			map.clearOverlays();

			//get bounds
			var bounds = map.getBounds();
			var sw = bounds.getSouthWest();
			var ne = bounds.getNorthEast();
			
			var apparentZoomLevel = map.getZoom();
			
			var URL = "";
			
			if (inViewListMode) {
				URL += "/markerListXml.php?list=" + inViewListMode;
			}
			else {
				URL += "/widget/getMarkersXml.php?";
				//var seeingAllMarkers = document.getElementById("see_all_markers").checked;
				//if (!seeingAllMarkers) URL += "zoom=" + apparentZoomLevel;
				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");
				
				//var stats = xmlDoc.documentElement.getElementsByTagName("stats");
				//var under = parseFloat(stats[0].getAttribute("underneith"));
				
				/*if (seeingAllMarkers) {
					if (markers.length > 80) {
						document.getElementById("see_all_markers").checked = false;
						loadMarkers();
						makeInvisible("see_all_markers_span");
						return;
					}
				}
				else if (markers.length + under > 80) {
					makeInvisible("see_all_markers_span");
				}
				else {
					makeVisible("see_all_markers_span");
				}*/
				
				//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);		
				}
				
				/*
				if (under == 1)
					document.getElementById("map_explorer_zoomin_note").innerHTML = "<b>Zoom in</b> to find <font color='red'>1</font> additional marker.";
				else if (under > 1)
					document.getElementById("map_explorer_zoomin_note").innerHTML = "<b>Zoom in</b> to find <font color='red'>" + under + "</font> additional markers.";
				else {
					document.getElementById("map_explorer_zoomin_note").innerHTML = "No more markers to be revealed here.";
					if (!seeingAllMarkers) makeInvisible("see_all_markers_span");
				}*/
			});
		}
		
		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();
				
				if (inEditMode) exitEditMode();
				if (movingMarker) movingMarker = false;
							
				currentTitle = title;
				currentIcon = iconNumber;
				currentMarker = marker;
				currentMarkerPoint = point;
				
				document.getElementById("markerTitleInLoadingMessage").innerHTML = title;
				document.getElementById("loadMarkerMessage").style.display = "block";
	
				setCookie('Longitude', point.x);
				setCookie('Latitude', point.y);
				setCookie('Zoom', map.getZoom());
				
				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;
}

		//When this function is called, it centers the icon with this id number and
		// goes through what would have happened if the wser clicked on it.
		// It combines CreateMarker and loadMarkerId
		//It also should bring the marker into view
		function virtuallyClickMarker(mid) {
			if (inEditMode) exitEditMode();
			if (movingMarker) movingMarker = false;
			
			switchTab(VIEW_MARKER_DESCRIPTION_TAB);
			
			document.getElementById('iframe_div').style.display = "none";
			
			currentID = mid;
			
			var filename = "/getMarkerInfo.php?id=" + mid;
			filename += "&iebug=" + Math.random();
			doWithFile(filename, true, function(xmlDoc) {
				var markers = xmlDoc.documentElement.getElementsByTagName("marker");
				var marker = markers[0];
	
				//Set the variables
				currentTitle = marker.getAttribute("title");
				currentIcon = marker.getAttribute("icon");
				
				var lat = marker.getAttribute("latitude");
				var lng = marker.getAttribute("longitude");
				currentMarkerPoint = new GLatLng(lat, lng);
				
				//This could be a problem.  What is the current marker?
				currentMarker = null;
				
				//Set the variables
				currentMinZoom = marker.getAttribute("minZoom");				
				
				currentMaxZoom = marker.getAttribute("maxZoom");
				currentOrgs = marker.getAttribute("orgs");
				currentOwner = marker.getAttribute("owner");

				map.setCenter(currentMarkerPoint, parseFloat(marker.getAttribute("maxZoom")));
				
				//Now get the description and output the text.
				var descFile = "/getMarkerDescription.php?id=" + mid + "&iebug=" + Math.random();
				doWithFile(descFile, false, function(text) {
					currentDescription = text;
					viewText();
				});
			});
		}
		
		//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");
				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;
				

				setCookie('Longitude', point.x);
				setCookie('Latitude', point.y);
				setCookie('Zoom', map.getZoom());
				
				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() {
				loadMarkers();
			});
		}

		//Returns " disabled" if we have security clearance and "" otherwise
		function isDisabled() {
			if (!userInfo) return " disabled";
			if (userInfo.id > 0) return "";
			return " disabled";
		}
		
		//This function places the contents of the textfile into message.
		//Then, moves us there.
		function viewText() {
			if (parseInt(map.getZoom()) < parseInt(currentMinZoom))
				map.setZoom(parseInt(currentMinZoom));
			else if (parseInt(map.getZoom()) > parseInt(currentMaxZoom))
				map.setZoom(parseInt(currentMaxZoom));
				
			closeCreation();
			
			document.title = "Stickymap - " + currentTitle;
			
			var contentFile = "localNetwork/localPage.php?mid=" + currentID;
			
			if (BrowserDetect.browser == "Explorer")
				contentFile += "&iebug=" + Math.random();
				
			document.getElementById('iframe_div').style.display = "block";
			document.getElementById('iframe_area').src = contentFile;
			document.getElementById("loadMarkerMessage").style.display = "none";
			document.getElementById("marker_info_text").innerHTML = "";

			document.getElementById("marker_info_right_col").innerHTML = "";
			document.getElementById("map_explorer_container").style.display = "none";
		}

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 = "moveMarker.php?";
			file += "lat=" + point.y;
			file += "&lng=" + point.x;
			file += "&mid=" + currentID;

			doWithFile(file, false, function(response) {
				var status = eval(response);
				switch(status) {
					case "success":
						alert("The marker has been moved.");
						break;
					case "restricted":
						alert("You do not have permission to move this marker.  This is because the marker has been modified by one or more of our registered users.  If you believe that this marker is in the wrong location, please click \"report\" and tell us about it.");
						break;
					case "failure":
						alert("The move failed.  Please email admin@stickymap.com to report this error");
						break;
				}
				
				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);
	loadMarkers();
	if (inCreationMode)
		changedZoomWhileCreatingMarker();	
}