var map		// this is our map

var customMap;	// ISU map overlay

var defaultCenterPoint = new GLatLng(DEFAULT_CENTER.y, DEFAULT_CENTER.x);//Default center point - different from default point cordinates

var markerArray = new Array();	// array that stores all of our markers
var point;
var marker;

var markerDataArray = new Array();	// array that stores the marker's string and html its info window
var infoHTML;

var markerEnabledArray = new Array();	// array that stores each marker's status
										// true if marker is currently enabled
var clickable = new Array();	// true if layer's locations can be clicked on map without layer turned on

var layersChecked = new Array();	// true if layer is currently enabled

curInfoWindowI = -1;	// layer number of current marker that has an info window open
curInfoWindowJ = -1;	// location number of current marker that has an info window open

var currentPopUp = "none"; //tracks status of pop-up html window

var printMap = false; //Prevents functions not needed from running for printMap.shtml

var mapLoad = true; //flag for determining if the map is initially loading

/*var infoWinLoc;
var infoWinLayer;*/

// getMapURLParameter
// extracts data after the "?" from the URL
// currentSelection is the current marker with an info window open
// latLng is the set of current map coordinates
// currentZoom is the last map zoom level
// layers is an array of numbers, either 0 or 1, for the status of each respective layer
//                 0 means layer is off
//                 1 means layer is on
// returns an object of the currentSelection and layers array
function getMapURLParameter() {

	var dataFromURL = window.location.href;


	//Check to see if there is text in the link box
	//If there is, uses that link to read the query string from
	//Used to handle when user hits back in their browser
	if (document.getElementById("hiddenInfoBox").value != "")
		dataFromURL = document.getElementById("hiddenInfoBox").value;

	//Checks for and reads query string
	if(dataFromURL.indexOf("?") > -1)
	{
		var rtnQS;
		var currentSelection = "none";
		var latLng = defaultCenterPoint;
		var currentZoom = 17;
		var mapType = "campus";
		var layers = "none";

		rtnQS =  getQS("s", dataFromURL);
		if (rtnQS)
			currentSelection = rtnQS;
			
		rtnQS =  getQS("c", dataFromURL);
		if (rtnQS) 
		{
			var currentLocationSplit = rtnQS.split(',');
			latLng = new GLatLng(currentLocationSplit[0], currentLocationSplit[1]);
		}
		
		rtnQS =  getQS("z", dataFromURL);
		if (rtnQS)
			currentZoom = rtnQS*1;
		
		rtnQS =  getQS("t", dataFromURL);
		if (rtnQS)
			mapType = rtnQS;
			
		rtnQS =  getQS("l", dataFromURL);
		if (rtnQS)
			layers = rtnQS.split(',');;

	}
	else
	{
		currentSelection="none";
		latLng = defaultCenterPoint;
		currentZoom=DEFAULT_ZOOM;
		layers = "none";
		mapType = "campus";
	}
	
	return {currentSelection : currentSelection, latLng : latLng, currentZoom : currentZoom, layers : layers, mapType: mapType, mapSec : mapSec};
}
//javascript:alert(urlData.currentSelection);
var urlData = getMapURLParameter();		// this is the object where we store our data received from another page

function getQS(qs, specificQS)
{
	qs += "=";
	var dataFromURL = window.location.href;

	if (specificQS)
	{
		dataFromURL = specificQS;
	}

	if (dataFromURL.indexOf("?")>-1)
	{
		dataFromURL = dataFromURL.substring(dataFromURL.indexOf("?")+1);
	
		var i = dataFromURL.indexOf(qs);

		if (i>-1)
		{
			dataFromURL = dataFromURL.substring(i + qs.length);
			//alert(dataFromURL);
			if (dataFromURL.indexOf("&") > -1)
			{
				return dataFromURL.substring(0,dataFromURL.indexOf("&"));
			}
			else
			{
				return dataFromURL;
			}
			
		}
		else
			return null;
	}
	else
		return null;
}

// checkBoxUpdate
// based on the layers array from urlData:
//        markers will be turned on if the respective array location is a 1
// any checkbox that is checked, the layer will be turned on
function checkBoxUpdate() 
{
	if (urlData.layers!="none")
	{
		for(var i = 0; i < urlData.layers.length; i++)
		{
			var chkBox = leftNav[LEFT_NAV_INFO][i][0]; //Collect root check box name
			var chkAll = chkBox.substring(0,3) + 'All' + chkBox.substring(3); //Create id for all chkAll
			var chkLength = leftNav[LEFT_NAV_INFO][i][1];
			var layerNum = leftNav[LEFT_NAV_INFO][i][2];

			var numOfChk="";

			var urlLayerData = urlData.layers[i];
			
			if (urlLayerData.indexOf("a") > -1) //If all check boxes in layer are checked
			{
				numOfChk="a";
			
			}
			else if (urlLayerData.indexOf("n") > -1) //If no check boxes are checked
			{
				numOfChk="n";
			
			}
			else //If some check boxes are checked - saves 0 for not checked, 1 for checked
			{
				numOfChk = urlLayerData.substring(urlLayerData.indexOf("s") + 1);
				numOfChk = convertLayerString(numOfChk, 1, chkLength).toString();
			}
			
			//Clear all check boxes
			
			document.getElementById(chkAll).checked=false;
	 
			for (var j = 0; j < chkLength; j++)
			{
				document.getElementById(chkBox + j).checked=false;
			}

			//Check boxes and run functions to place markers on map
			if (numOfChk=="a")
			{
				var chkBox = leftNav[LEFT_NAV_INFO][i][0];
				var chkAll = chkBox.substring(0,3) + 'All' + chkBox.substring(3);
				document.getElementById(chkAll).checked=true;
				updateNavLeft(chkAll, false); //Calls the function that is used when user clicks on a Check All checkbox
			}
			else if (numOfChk!="n")
			{
				var subChk = numOfChk.split('');
				
				for (x in subChk)
				{
					if (subChk[x]==1)
					{
						document.getElementById(chkBox + x).checked=true;
						updateNavLeftSub(chkBox + x, false) //Calls the function that is used when user clicks on a checkbox
					}
				}	
			}		
		}
	}
}

function showLocation()
{
	if (setMapCenter)
	{
		for(var i = 0; i < markerDataArray.length; i++)
		{
			for(var j = 0; j < markerDataArray[i].length; j++)
			{
				if(urlData.currentSelection == markerDataArray[i][j].id || urlData.currentSelection == markerDataArray[i][j].abrv)
				{
					removeDefaultMarker();
			
					if(markerEnabledArray[i][j]==0)	// if marker is disabled, then enable just the marker
					{
						enableMarker(i, j);
					}
					else	// if marker is enabled, then all we need to do is click marker
					{
						locationClick(i, j, markerDataArray[i][j].html);
					}
				}
			}
		}
	}
}


// findClosestMarker
// this function will show and center on the marker that is closest to the coordinates in latLng
// no marker is shown if there is no marker in range
function findClosestMarker(latLng)
{
	if(latLng)
	{
		var curMin = 999999999;	// current mininum distance from click location to marker
		var minI = 0;	// layer number of marker with smallest distance from click location
		var minJ = 0;	// location number of marker with smallest distance from click location
		var sensitivity = 0.0006;	// maximum allowed distance between click location and marker
		
		//check the distance between every marker and the click location
		//find the least distance using the distance formula
		for(var i = 0; i < markerArray.length; i++)
		{
			if(clickable[i])
			{
				for(var j = 0; j < markerArray[i].length; j++)
				{
					if (markerArray[i][j]!==0)
					{		
						var x1 = latLng.x;
						var y1 = latLng.y;
						var x2 = markerArray[i][j].getLatLng().x;
						var y2 = markerArray[i][j].getLatLng().y;
						if(Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)) < curMin)
						{
							curMin = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
							minI = i;
							minJ = j;
						}
					}
				}
			}
		}
		//make sure the least distance is not too large
		if(curMin < sensitivity)
		{
			map.closeInfoWindow();
			removeDefaultMarker();

			enableMarker(minI, minJ);
		}
	}
}

//show the marker on the map and add its click listener
function enableMarker(layerNum, locNum)
{
	//alert(layerNum + " " + locNum);
	map.addOverlay(markerArray[layerNum][locNum]);
	
	if (markerEnabledArray[layerNum][locNum]!=0)
	{
		GEvent.addListener(markerArray[layerNum][locNum], "click", function()
		{
			locationClick(layerNum, locNum, markerDataArray[layerNum][locNum].html);	
		});
	}

	//If marker already exists, just 'click' on it
	if (markerEnabledArray[layerNum][locNum]!=3)
		locationClick(layerNum, locNum, markerDataArray[layerNum][locNum].html);

}

//hide the marker on the map and remove its listeners
function disableMarker(layerNum, locNum)
{
	markerArray[layerNum][locNum].closeInfoWindow();
	map.removeOverlay(markerArray[layerNum][locNum]);
	GEvent.clearListeners(markerArray[layerNum][locNum], "click");
}

// function that will be called whenever location needs to be found on the map
function locationClick(layerNum, locNum, html)
{
	if(!isInfoWindowOpen(layerNum, locNum) && setMapCenter)
	{
		if(map.getCenter() != markerArray[layerNum][locNum].getLatLng())
		{
			//Center on coordinates using offset
			map.setCenter(virtualCenter(markerArray[layerNum][locNum].getLatLng()));
			
		}

		if (directionsFlag && !markerDataArray[layerNum][locNum].noTab)
		{
			markerArray[layerNum][locNum].openInfoWindowTabsHtml(buildTabsHtml(layerNum, locNum)); //Display Tabbed Pop-up
		}
		else
		{
			markerArray[layerNum][locNum].openInfoWindowHtml(html);
		}

		currentPopUp = markerDataArray[layerNum][locNum].abrv; //Preserve state of marker that has pop-up

		if (markerEnabledArray[layerNum][locNum]==0)
			updateMarker(layerNum, locNum);
	}
}

//Creates an offset to compensate for overlayed left nav and mast head
function virtualCenter(point){

  var maxInfoWinHeight = 280; //Height of tallest info window in px
  var fromTopHeight = 215; //How many pxs down from top of browser you want top of the tallest info window to be

  var xOffs = -47.5; //right padding / 2 - left padding / 2
  var yOffs = Math.floor(map.getSize().height/2)-maxInfoWinHeight - fromTopHeight;

  var pixCenter = map.fromLatLngToDivPixel(point);

  var virtualPxCenter = new GPoint(pixCenter.x + xOffs, pixCenter.y + yOffs);
  return map.fromDivPixelToLatLng(virtualPxCenter);
}

function isInfoWindowOpen(layerNum, locNum)
{
	if(layerNum == curInfoWindowI && locNum == curInfoWindowJ)
		return true;
	else
		return false;
}

//this is called when locationClick is called
function updateMarker(layerNum, locNum)
{
	curInfoWindowI = layerNum;
	curInfoWindowJ = locNum;

	tempListener = GEvent.addListener(markerArray[layerNum][locNum], "infowindowclose", function()
	{
		
		if(markerEnabledArray[layerNum][locNum]== 0 || layerNum == OTHER_LOCATIONS_NUM)
		{
			disableMarker(layerNum, locNum);		
		}
		curInfoWindowI = -1;
		curInfoWindowJ = -1;
		GEvent.removeListener(tempListener);
	});
}

//Currently not used
function removeErrorMarkers()
{
	for(var i = 0; i < markerArray.length; i++)
	{
		if(clickable[i])
		{
			for(var j = 0; j < markerArray[i].length; j++)
			{
				if(!layersChecked[i] && !isInfoWindowOpen(i, j))
				{
					disableMarker(i, j);
				}
			}
		}
	}
}

function clearMap()
{
	//Clears all markers
	for(var i = 0; i < markerDataArray.length; i++)
	{
		for(var j = 0; j < markerDataArray[i].length; j++)
		{
			if (markerDataArray[i][j]!=0)
			{
				disableMarker(i, j);
				markerEnabledArray[i][j] = 0;
			}
		}
	}

	//Clears all checkboxes
	for(var ii = 0; ii < leftNav[LEFT_NAV_INFO].length; ii++)
	{
		var chkBox = leftNav[LEFT_NAV_INFO][ii][0]; //Collect root check box name
		var chkAll = chkBox.substring(0,3) + 'All' + chkBox.substring(3); //Create id for all chkAll
		var chkLength = leftNav[LEFT_NAV_INFO][ii][1];
		var layerNum = leftNav[LEFT_NAV_INFO][ii][2];
		var icon = chkBox.substring(3).toLowerCase() + "Icon";

		document.getElementById(chkAll).checked=false;

		document.getElementById(icon).style.display = 'none';

		layersChecked[layerNum]=false;
		
		for(var jj = 0; jj < chkLength; jj++)
		{
			document.getElementById(chkBox + jj).checked=false;
		}
	}

	//Remove constrution overlay and left nav icon
	map.removeOverlay(constructionArea);
	document.getElementById("conIcon").style.display = 'none';

	//Defaults link information
	document.getElementById("hiddenInfoBox").value = "";
	currentPopUp="none";
	
	removeDefaultMarker();

	//Hide Legends
	for (x in legendsArray)
	{
		hideLegend(legendsArray[x]);
	}

	//Center map on default center point
	map.setCenter(defaultCenterPoint, DEFAULT_ZOOM);
	map.setMapType(customMap);

	//Loads all the initial overlays (ex. default marker)
	//Secondary maps typically have more overlays
	//Found in mapCampus.js, specialMap.js, etc.
	loadInitOverlay();
}

function moreUpdate()
{
	for (var i in selEventArray)
	{
		document.getElementById("chkMore" + i).checked=false;
	}

	var rtnQS =  getQS("a", document.getElementById("hiddenInfoBox").value);
	if (rtnQS)
	{
		selEventArray = convertLayerString(rtnQS, 1).substring(1).split("");
		showHideLayers();
	}
}

function load()
{
	if (GBrowserIsCompatible())
	{
		map = new GMap2(document.getElementById("map"), {draggableCursor: cursorType});
			
		initTileOverlay(); //creates custom tile layer - mapTileLayer.js	

		//Add Controls, Map Type, Scale
		var ControlPosition = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(280,10));
		map.addControl(new GScaleControl(), ControlPosition);	// scale bar
		var MapTypeControl = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,180));
		map.addControl(new GMapTypeControl(), MapTypeControl);	// change map type bar

		//map.enableGoogleBar();
		
		zoom(); // Calls function to restrict the zoom level
		map.enableScrollWheelZoom();
		map.disableDoubleClickZoom();
		new GKeyboardHandler(map); //Adds keyboard controls

		map.removeMapType(G_NORMAL_MAP);
		map.removeMapType(G_SATELLITE_MAP);
		map.removeMapType(G_HYBRID_MAP);
		map.removeMapType(customMap);

		//Set map type based on query string
		if (urlData.mapType=="campus")
		{
			map.setMapType(customMap);
			changeMapType(document.getElementById("mapTypeISU"))
		}
		else if (urlData.mapType=="hybrid")
		{
			map.setMapType(G_HYBRID_MAP);
			changeMapType(document.getElementById("mapTypeSat"))
		}
		else
		{
			map.setMapType(customMap);
			changeMapType(document.getElementById("mapTypeISU"))
		}
		
		/*var getSel = getQS("s");
		if (getSel)
			urlData.currentSelection = getSel;*/
		
		map.setCenter(urlData.latLng, urlData.currentZoom); //center map based on query string or default

		
		//Loads all the initial overlays (ex. default marker)
		//Secondary maps typically have more overlays
		//Found in mapCampus.js, specialMap.js, etc.
		loadInitOverlay();	

		//Disables center on layer 
		if (urlData.currentSelection == "returnNone" || urlData.currentSelection == "none")
		{
			setMapCenter = false;
		}
		
		checkBoxUpdate(); //Read layer information and check appropriate boxes and add markers

		moreUpdate();

		showLocation();	 //Display marker and pop-up of current selection

		setMapCenter = true;

		setNavHeight(); //Dynamically resizes the height of left nav

		setZoomControls(map.getZoom()); //Set's zoom bar postion according to zoom level
		
		//Display Accessibility Legend if zoom is higher than 16
		if (map.getZoom()>16 && map.getCurrentMapType() == customMap)
			showLegend("accLegend");
		else
			hideLegend("accLegend");
		
		loadListeners(); //Add map Listeners
		
		//Preserve Map State if no pop-up is selected and user leaves and then returns to map using Browser back
		if (urlData.currentSelection == "returnNone")
		{
			map.closeInfoWindow();
			removeDefaultMarker();
		}

		mapLoad = false;

		document.getElementById('mapLoad').style.display='none'; //Hides loading screen
		/**/document.getElementById('mapTypeISU').style.display='block';
		document.getElementById('mapTypeSat').style.display='block';
		document.getElementById('wrapMore').style.display='block';
	}
	else
	{
		window.location.href = "/accessibility/browsercompatibility.shtml";
	}
	
} 

