/******************************************************
 * mapManager.js                                      *
 *                                                    *
 * This holds the bulk of the map-related javascript. *
 ******************************************************/

// Whether or not the building overlay is shown
var showOverlay = false;

// Whether or not the navbar is hidden
var showNavPanel = true;

// How the navbar results are sorted
var navPanelState = NAV_BUILDING;

// The state of the map
var mapState = MAP_BUILDING;

// Whether or not an infowindow is open
var showInfoWindow = false;

// The current center of the map
var mapCenter = new GLatLng(MC.lat(), MC.lng());

/* This makes the info window open when the marker is done moving.
   This is incredibly sloppy */
var currentMarker;
var currentHtml;

// Visible Points (a quick fix for categories and occupants)
var visiblePoints;

/***
 * Overrides Google's code and performs an action when the map is
 * finished scrolling
 */
function onMoveEnd()
{
	if(mapState == MAP_BUILDING && currentMarker && currentHtml)
	{
		//currentMarker.openInfoWindowHtml(currentHtml);
		if(showInfoWindow * !currentMarker.detailOpen) {
			currentMarker.showDetailWin();
		}
	}
}

/***
 * Overrides Google's code and performs an action when the map is
 * finished scrolling
 */
function onZoomEnd()
{
	goTo(mapCenter);
}

/***
 * Updates the map size according to the window size
 */
function updateMapSize()
{
	var mapHeight = YAHOO.util.Dom.getViewportHeight();
	mapHeight = mapHeight - mapVerticalPadding;
	if (mapHeight < mapMinHeight)
	{
		mapHeight = mapMinHeight;	
	}
	YAHOO.util.Dom.setStyle('map', 'height', mapHeight+'px');
	map.checkResize();
	if (mapCenter != null) {
		panTo(mapCenter);
	}
	
	navPanel.style.top = findPosY(document.getElementById("map"))+59+'px';
	navPanel.style.height = (map.getSize().height-88)+'px';
	
	document.getElementById("navPanelHeader").style.top = findPosY(document.getElementById("map"))+32+'px';
}

/***
 * Works in conjunction with the updateMapSize function to find the X position
 * of an element on the page
 */
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

/***
 * Works in conjunction with the updateMapSize function to find the Y position
 * of an element on the page
 */
function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

/***
 * Resets the map center and zoom to the original settings
 */
function resetMapCenter()
{
	goTo(MC, DEFAULT_ZOOM);
}

/***
 * The Ajax Response Failure
 */
var responseFailure = function(o)
{
	alert("There was an error loading data. Please reload the page.");
}

/***
 * The nav-panel success; It pulls contents for the nav panel
 */
var navPanelSuccess = function (o)
{   
   eval("var data = " + o.responseText);   
   setNavPanelContents(data);
}

var nav_panel_callback = 
{
   success:navPanelSuccess,
   failure:responseFailure
}


var responseSuccess = function(o)
{
	eval("var dataPoints = " + o.responseText);	
	addPoints(dataPoints);
}

var callback =
{
	success:responseSuccess,
	failure:responseFailure
}

var cObj;

function url(type, value, order)
{
	var retval = "mapquery.php?type="+type+"&value="+value;
	if(order)
		retval += "&order="+order;
	return retval;
}

function displaySearch(id)
{
	var element = document.getElementById(id);
	if(element.value)
	{
		var value = element.value;
		if(navPanelState == NAV_BUILDING || navPanelState == NAV_ID) {
			building(value);
		} else if(navPanelState == NAV_OCCUPANT) {
			occupant(value);
		}
	}  
}

function category(value)
{
	//navPanelCat(value);
	if (value >= 0 && value < categories.length) {
		cObj = YAHOO.util.Connect.asyncRequest('GET',url("category",value,null),callback,null);
	}  else {
		alert("Incorrect Category Number");
	}
	showInfoWindow = false;
}

function occupant(value)
{
	cObj = YAHOO.util.Connect.asyncRequest('GET',url("occupant",value,null),callback,null);
	if(mapState == MAP_CATEGORY)
		selectNone();
	mapState = MAP_OCCUPANT;
	showInfoWindow = false;
	this.map.clearOverlays();
}

function building(value)
{
	cObj = YAHOO.util.Connect.asyncRequest('GET',url("id",value,null),callback,null);
	if(mapState == MAP_CATEGORY)
		selectNone();
	mapState = MAP_BUILDING;	
	showInfoWindow = true;
	map.clearOverlays();
}

function uncheckBoxes() {
	for(var i=0; i<categories.length; i++)
	{
		document.getElementById("check_"+i).checked = false;
		categories[i].checked = false;
	}
	killCookies();
}

function checkBoxes()
{
	for(var i=0; i<categories.length; i++)
	{
		document.getElementById("check_"+i).checked = true;
		categories[i].checked = true;
	}
}

function forceCategory(box)
{
	document.getElementById("check_"+box).checked = true;
	handleChecks(box);
}

function handleChecks(box)
{	
	panTo(MC);
	if(mapState != MAP_CATEGORY)
	{
		this.map.clearOverlays();
		mapState = MAP_CATEGORY;
	}
	if(!categories[box].checked)
	{
		this.categories[box].checked = true;
		if(this.markers[box] == null)
		{
			this.markers[box] = new Array();
			category(box);
		} else
		{
			addCategory(box);
		}
	} else
	{
		this.categories[box].checked = false;
		remCategory(box);
	}	
	setTheCookies(0);
}

function remCategory(num)
{
	for(var i=0; i<markers[num].length; i++)
	{
		map.removeOverlay(markers[num][i]);
	}
}	

function addCategory(num)
{
	for(var i=0; i<markers[num].length; i++)
	{
		map.addOverlay(markers[num][i]);
	}
}

function selectAll()
{
	resetMapCenter();
	for(var i=0; i<categories.length; i++)
	{
		if(!this.categories[i].checked)
		{
			this.categories[i].checked = true;
			if(this.markers[i] == null) {
				this.markers[i] = new Array();
				category(i);
			}
			else
			{
				addCategory(i);
			}
		}
	}
	checkBoxes();	
	setTheCookies(0);
}

function selectNone()
{
	this.map.clearOverlays();
	uncheckBoxes();
	setTheCookies(0);
}


function closeAllTheOthers(myPoint) {
	for(var i=0;i<visiblePoints.length;i++)
	{
		var point = visiblePoints[i];
		if (point.detailOpen)
		{
			if (point != myPoint) {
				point.showDetailWin();
			}
		}
	}
}

function addPoints(points)
{	
	visiblePoints = new Array();
	
	for(var i=0;i<points.length;i++)
	{
		var m = makePoint(points[i]);
		
		if(mapState != MAP_BUILDING)
			visiblePoints[i] = m;
		
		map.addOverlay(m);
		currentMarker = m;
		currentHtml = infoBox(points[i]);
		if(mapState == MAP_CATEGORY)
			markers[points[i].category][i] = m;
	}
	
	if(mapState != MAP_CATEGORY)
		panTo(centerOfPoints(points));	
}

function centerOfPoints(points) {
	// Abstract, overly-large limits
	var xMin = 90;
	var xMax = -90;
	var yMin = 180;
	var yMax = -180;
	
	for(var i=0; i<points.length; i++) {
		if(points[i].latitude < xMin)
			xMin = points[i].latitude;
		if(points[i].latitude > xMax)
			xMax = points[i].latitude;
		if(points[i].longitude < yMin)
			yMin = points[i].longitude;
		if(points[i].longitude > yMax)
			yMax = points[i].longitude;
	}
		
	var newX = (parseFloat((xMax - xMin) / 2.0) + parseFloat(xMin));
	var newY = (parseFloat((yMax - yMin) / 2.0) + parseFloat(yMin));
	
	return new GLatLng(newX, newY);	
}

function panTo(point)
{
	mapCenter = point;
	map.panTo(adjustCenter(point));		
}

function adjustCenter(point) {
	var x_offset = 0;
	var y_offset = 0;
	
	var z_factor =  Math.pow(2,(map.getZoom() - DEFAULT_ZOOM));
	
	if(showNavPanel) {
		x_offset += NAVBAR_OFFSET / z_factor;
	}
		
	if(showInfoWindow) {
		x_offset += INFOWINDOW_OFFSET_X / z_factor;
		y_offset += INFOWINDOW_OFFSET_Y / z_factor;
	}

	return new GLatLng(parseFloat(point.lat())+y_offset, parseFloat(point.lng())+x_offset);
}

function goTo(point)
{
	goTo(point, DEFAULT_ZOOM);
}

function goTo(point, zoom)
{
	mapCenter = point;
	if(zoom != DEFAULT_ZOOM) {
		map.setCenter(adjustCenter(point), zoom);
	} else {
		map.setCenter(adjustCenter(point));
	}
}

function makePoint(data)
{
	marker = new PdMarker(new GLatLng(data.latitude,data.longitude), icons[data.category]);
	//marker = new PdMarker(new GLatLng(data.latitude,data.longitude));
	marker.setTooltip(data.bId+". "+data.name);
	marker.setDetailWinHTML(data);
	marker.setHoverImage("images/buzz.png");


/*
	var marker = new GMarker(new GLatLng(data.latitude,data.longitude), icons[data.category]);
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(infoBox(data));
		});
	GEvent.addListener(marker, "mouseover", function() {
		marker.image = "/images/buzz.png";
		});
	map.addOverlay(marker);
	*/
	
	return marker;
}

function infoBox(data)
{
	var result = "";
	result += "<div align='center'><table width='196'>";
	if(data.name)
		result += "<tr><td width='108'><b><a href='http://gtalumni.org/map/index.php?id="+data.id+"'>data.id. "+data.name+"</a></b></td></tr>";
	if(data.image) {
		result += "<tr><td><img width=160 height=144 src='http://www.gtalumni.org/campusmap/buildings/"+data.image+"' /></td></tr>";
	}
	if(data.address)
		result += "<tr><td>"+data.address+"</td></tr>";		
	if(data.phone)
		result += "<tr><td>"+data.phone+"</td></tr>";	
	if(data.occupants) {
		result += "<tr><td>";
		for(var i=0; i<data.occupants.length; i++)
		{
			if(data.occupants[i].url)
				result += '<a href="http://'+data.occupants[i].url+'" target="_new">';
			result += data.occupants[i].name;
			if(data.occupants[i].url)
				result += "</a>";
			result += "<br/>";
		}
		result += "</td></tr>";
	}
	result += "</table></div>";
	
	return result;
}

/* OVERLAY CODE */

function toggleOverlay() {
	if(showOverlay) {
		map.removeTPhoto(photo);
		showOverlay = false;
		document.getElementById("overlay_link").innerHTML = "show building overlay";
	} else {
		map.addTPhoto(photo);
		showOverlay = true;
		document.getElementById("overlay_link").innerHTML = "hide building overlay";
	}
}

/* NAV PANEL CODE */

function populateNavPanel() {
	populateNavPanel(NAV_BUILDING);
}

function populateNavPanel(order) {
	switch(navPanelState) {
		case NAV_OCCUPANT:
			cObj = YAHOO.util.Connect.asyncRequest('GET',url("oAll","1",order),nav_panel_callback,null);
			break;
		case NAV_ID:
			cObj = YAHOO.util.Connect.asyncRequest('GET',url("iAll","1","bId"),nav_panel_callback,null);
			break;
		case NAV_BUILDING:
		default:
			cObj = YAHOO.util.Connect.asyncRequest('GET',url("all","1",order),nav_panel_callback,null);
			break;	
	}	
}

function navPanelCat(value) {
	if (value >= 0 && value < categories.length) {
		cObj = YAHOO.util.Connect.asyncRequest('GET',url("category",value,null),nav_panel_callback,null);
	}  else {
		alert("Incorrect Category Number");
	}
}

function setNavPanelContents(oArray) {
	var output = "";
	var occupant;
	var building;
	var showID = false;
	
	if(!showNavPanel) {
	}
	
	switch(navPanelState) {
		case NAV_OCCUPANT:
			for(var i=0;i<oArray.length;i++) {		
				occupant = oArray[i];
				output += '<a href="javascript:void(0)" onclick="occupant(\'' + occupant['oId'] + '\')">';
				output += '<em>'+occupant['name']+'</em>';
				output += '</a>';
						
				output += '<ul>';
				if(occupant['buildings']) {
					for(var j=0; j<occupant['buildings'].length; j++) {
						building = occupant['buildings'][j];
						output += '<li>';
						output += '<a href="javascript:void(0)" onclick="building(\'' + building['bId'] + '\')">' + building['name'] + '</a>';
						output += '</li>';
					}
				}
				output += '</ul>';
			}			
			break;
		case NAV_ID:
			showID = true;
		case NAV_BUILDING:
		default:
			for(var i=0;i<oArray.length;i++) {
				output += '<a href="javascript:void(0)" onclick="building(\'' + oArray[i]['bId'] + '\')">';
				if(showID) {
					output += oArray[i]['bId']+'. ';
				}
				output += oArray[i]['name'];
				output += '</a><br/>';
			}
			break;
	}
		
	document.getElementById("navPanelBody").innerHTML = output;
}

function togglePanel() {
	if(showNavPanel) {
		shrinkNav();
		document.getElementById("navPanelButton").src = "images/maximize.png";
	} else {
		growNav();
		document.getElementById("navPanelButton").src = "images/minimize.png";
	}
	
	showNavPanel = !showNavPanel;
	panTo(mapCenter);
}

function hidePanel() {
	document.getElementById("navPanel").style.visibility = "hidden";
}

function showPanel() {
	document.getElementById("navPanel").style.visibility = "visible";
}

function shrinkNav() {
	var attributes = {
		height: {
			from: 99,
			to: 0,
			unit: '%'
		}
	};
		
	var anim = new YAHOO.util.Anim('navPanelBodyBorder', attributes, .5, YAHOO.util.Easing.easeIn);
	anim.onComplete.subscribe(hidePanel);
	anim.animate();
	//toggleSortBar();
}

function toggleSortBar() {
	if((document.getElementById("navPanelSortBar")).style.display == "none")
		(document.getElementById("navPanelSortBar")).style.display = "";
	else
		(document.getElementById("navPanelSortBar")).style.display = "none";
}

function growNav() {
	var attributes = {
		height: {
			from: 0,
			to: 100,
			unit: '%'
		}
	};
		
	//toggleSortBar();
	showPanel();
	
	var anim = new YAHOO.util.Anim('navPanelBodyBorder', attributes, .5, YAHOO.util.Easing.easeOut);
	//anim.onComplete.subscribe(showPanel);
	anim.animate();
}


function resizeNavTo(height) {
	var attributes = {
		height: {
			to: height
		}
	};
	
	var anim = new YAHOO.util.Anim('navPanelBodyBorder', attributes, .5, YAHOO.util.Easing.easeOut);
	anim.animate();
}

function toggleSortOrder(option) {
	toggleNavHeaderLook(option);
	
	switch(option) {
		case NAV_BUILDING:
			navPanelState = NAV_BUILDING;
			break;
		case NAV_ID:
			navPanelState = NAV_ID;
			break;
		case NAV_OCCUPANT:
			navPanelState = NAV_OCCUPANT;
			break;
	}
	
	populateNavPanel();
}

function toggleNavHeaderLook(option) {
	switch(option) {
		case NAV_BUILDING:
			document.getElementById("nav_header_bld").style.fontWeight = "bold";
			document.getElementById("nav_header_id").style.fontWeight = "normal";
			document.getElementById("nav_header_occ").style.fontWeight = "normal";
			break;
		case NAV_ID:
			document.getElementById("nav_header_bld").style.fontWeight = "normal";
			document.getElementById("nav_header_id").style.fontWeight = "bold";
			document.getElementById("nav_header_occ").style.fontWeight = "normal";
			break;
		case NAV_OCCUPANT:
			document.getElementById("nav_header_bld").style.fontWeight = "normal";
			document.getElementById("nav_header_id").style.fontWeight = "normal";
			document.getElementById("nav_header_occ").style.fontWeight = "bold";
			break;
	}
}

function focusForm(form) {
	if(form.value == SEARCH_TEXT) {
		form.value = "";
		form.style.color = "#000000";
	}
}
function blurForm(form) {
	if(form.value == "") {
		form.value = SEARCH_TEXT;
		form.style.color = "#666666";
	}
}

/* COOKIE CODE */

function setTheCookies(id) {
	var newCookie = "";
	if(mapState == MAP_CATEGORY) {
		for(var i=0; i<categories.length; i++) {
			if(this.categories[i].checked) {
				if(newCookie != "") {
					newCookie += ",";
				}
				newCookie += i;				
			}
		}
		setCookie("category",newCookie);
	} else {
		setCookie("id",id);
	}
}

function setCookie(name, value) {
	WM_setCookie("type",name);
	WM_setCookie("value",value);
}

function getCookie(name) {
	return WM_readCookie(name);	 
}

function killCookie(name) {
	WM_killCookie(name);	 
}

function killCookies() {
	killCookie("type");
	killCookie("value");	 
}
