var mousex = 0;
var mousey = 0;
var grabx = 0;
var graby = 0;
var orix = 0;
var oriy = 0;
var elex = 0;
var eley = 0;
var algor = 0;

var dragobj = null;

var maxZoomIn=2;
var maxZoomOut=4;

var mapWidth=0;
var mapHeight=0;
var windowHeight=0;
var mapTop=0;
var mapLeft=0;

zm = new Array(4,2,1,0.5,0.25)

function falsefunc() { return false; } // used to block cascading events

function init() {
	document.onmousemove = update; // update(event) implied on NS, update(null) implied on IE
	getMapSize();
	setInitialView();
	update();
	/** DOMMouseScroll is for Mozilla. */
	if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, false);
	/** Mouse Scroll for IE/Opera. */
	window.onmousewheel = document.onmousewheel = wheel;
	document.getElementById("loadmsg").style.display="none";
	document.getElementById("mapimg"+currentZoom).style.visibility="visible";
	if (browser=="firefox") {setCursor("-moz-grab")} else {setCursor("move")}
	}

function setInitialView() {
	elex=Math.round(mapWidth/2)-initialCenterX;
	eley=Math.round(mapHeight/2)-initialCenterY;
	document.getElementById("mapint").style.left = (elex).toString(10) + "px";
	document.getElementById("mapint").style.top = (eley).toString(10) + "px";
	document.getElementById("mapint").style.display="block";
	// set cursor over map
	//setCursor("mapNormal");
	}

function getMouseXY(e) // works on IE6,FF,Moz,Opera7
{ 
  if (!e) e = window.event; // works on IE, but not NS (we rely on NS passing us the event)

  if (e)
  { 
    if (e.pageX || e.pageY)
    { // this doesn't work on IE6!! (works on FF,Moz,Opera7)
      mousex = e.pageX;
      mousey = e.pageY;
      algor = '[e.pageX]';
      if (e.clientX || e.clientY) algor += ' [e.clientX] '
    }
    else if (e.clientX || e.clientY)
    { // works on IE6,FF,Moz,Opera7
      mousex = e.clientX + document.body.scrollLeft;
      mousey = e.clientY + document.body.scrollTop;
      algor = '[e.clientX]';
      if (e.pageX || e.pageY) algor += ' [e.pageX] '
    }  
  }
}

function update(e)
{
  getMouseXY(e); // NS is passing (event), while IE is passing (null)

  parent.frames["controlframe"].document.getElementById('span_browser').innerHTML = browser;
//  document.getElementById('span_winevent').innerHTML = window.event ? window.event.type : '(na)';
//  document.getElementById('span_autevent').innerHTML = e ? e.type : '(na)';
  parent.frames["controlframe"].document.getElementById('span_mousex').innerHTML = mousex;
  parent.frames["controlframe"].document.getElementById('span_mousey').innerHTML = mousey;
//  document.getElementById('span_grabx').innerHTML = grabx;
//  document.getElementById('span_graby').innerHTML = graby;
  parent.frames["controlframe"].document.getElementById('span_orix').innerHTML = orix;
  parent.frames["controlframe"].document.getElementById('span_oriy').innerHTML = oriy;
  parent.frames["controlframe"].document.getElementById('span_elex').innerHTML = elex;
  parent.frames["controlframe"].document.getElementById('span_eley').innerHTML = eley;
  parent.frames["controlframe"].document.getElementById('span_mapWidth').innerHTML = mapWidth;
  parent.frames["controlframe"].document.getElementById('span_mapHeight').innerHTML = mapHeight;
  parent.frames["controlframe"].document.getElementById('span_windowHeight').innerHTML = windowHeight;
  parent.frames["controlframe"].document.getElementById('span_mapLeft').innerHTML = mapLeft;
  parent.frames["controlframe"].document.getElementById('span_mapTop').innerHTML = mapTop;
  parent.frames["controlframe"].document.getElementById('span_currentZoom').innerHTML = currentZoom;
  parent.frames["controlframe"].document.getElementById('span_algor').innerHTML = algor;
  parent.frames["controlframe"].document.getElementById('span_dragobj').innerHTML = dragobj ? (dragobj.id ? dragobj.id : 'unnamed object') : '(null)';
  absoluteX=(mousex+elex)*Math.pow(2,currentZoom-2);
  absoluteY=(mousey+elex)*Math.pow(2,currentZoom-2);
  //window.status=elex+", "+eley+", z="+currentZoom;
}

function grab(context)
	{
	document.onmousedown = falsefunc; // in NS this prevents cascading of events, thus disabling text selection
	if (mousex) {
		dragobj = context;
		document.onmousemove = drag;
		document.onmouseup = drop;
		grabx = mousex;
		graby = mousey;
		elex = orix = dragobj.offsetLeft;
		eley = oriy = dragobj.offsetTop;
		update();
	if (browser=="firefox") {setCursor("-moz-grabbing")} else {setCursor("all-scroll")}
		}
	}

function drag(e) // parameter passing is important for NS family 
	{
	elex = orix + (mousex-grabx);
	eley = oriy + (mousey-graby);
	dragobj.style.position = "absolute";
	dragobj.style.left = (elex).toString(10) + 'px';
	dragobj.style.top  = (eley).toString(10) + 'px';
	update(e);
	return false; // in IE this prevents cascading of events, thus text selection is disabled
	}

function drop() {
	if (browser=="firefox") {setCursor("-moz-grab")} else {setCursor("move")}
	if (dragobj) {
	dragobj = null;
	}
	update();
	document.onmousemove = update;
	document.onmouseup = null;
	document.onmousedown = null;   // re-enables text selection on NS
//	if (elex==orix && eley==oriy) {alert("Click")}
	}

// Get size of map frame
// Return in "mapWidth" and "mapHeight" variables
function getMapSize() {
	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {
			winW = window.innerWidth;
			winH = window.innerHeight;
			}
		if (navigator.appName.indexOf("Microsoft")!=-1) {
			winW = document.body.offsetWidth;
			winH = top.document.body.offsetHeight-top.frames["titleframe"].document.body.offsetHeight;
			}
		}
	mapWidth=winW;
	mapHeight=winH;
	windowHeight=top.document.body.offsetHeight;
	mapTop=0;
	mapLeft=0;
	}

// Zoom in and recenter
// This function activated when the map is double-clicked
function zoomInRecenter(e) {
	getMouseXY(e); // NS is passing (event), while IE is passing (null)
	getMapSize();
	newX=Math.round(mousex-elex-mapWidth/4)*2;
	newY=Math.round(mousey-eley-mapHeight/4)*2;
	zoomIn(newX,newY);
	}

// Zoom in center-to-center
// This function activated when "zoom in" button is clicked
function zoomInCenterCenter() {
	getMapSize();
	newX=Math.round(mapWidth/4-elex)*2;
	newY=Math.round(mapHeight/4-eley)*2;
	zoomIn(newX,newY);
	}

// Zoom out center-to-center
// This function activated when "zoom out" button is clicked
function zoomOutCenterCenter() {
	getMapSize();
	newX=Math.round((-elex-mapWidth/2)/2);
	newY=Math.round((-eley-mapHeight/2)/2);
	zoomOut(newX,newY);
	}

// Zoom in on the map
// newX,newY are the coordinates of the upper left corner on the new map in pixels
function zoomIn(newX,newY) {
	if (currentZoom>maxZoomIn) {
		currentZoom--;
		for(var x=maxZoomIn; x<=maxZoomOut; x++) {
			document.getElementById("mapimg"+x).style.visibility="hidden";
			}
		elex=-newX;
		eley=-newY;
	    document.getElementById("mapint").style.left = elex.toString() + "px";
	    document.getElementById("mapint").style.top  = eley.toString() + "px";
		document.getElementById("mapimg"+currentZoom).style.visibility="visible";
		var newSliderX=47+(3-currentZoom)*8;
		parent.frames["controlframe"].document.getElementById("zoomSlider").style.left=newSliderX+"px";
		// turn on any active overlays
		updateOverlays("in");
		// if current zoom is less than three, turn on building names
		if (currentZoom<3) {
			parent.controlframe.document.getElementById("buildingnames").checked=true;
			parent.controlframe.showIcons('buildingnames');
			}
		}
	}

// Zoom out on the map
// newX,newY are the coordinates of the upper left corner on the new map in pixels
function zoomOut(newX,newY) {
	if (currentZoom<maxZoomOut) {
		currentZoom++;
		for(var x=maxZoomIn; x<=maxZoomOut; x++) {
			document.getElementById("mapimg"+x).style.visibility="hidden";
			}
		elex=-newX;
		eley=-newY;
	    document.getElementById("mapint").style.left = elex.toString() + "px";
	    document.getElementById("mapint").style.top  = eley.toString() + "px";
		document.getElementById("mapimg"+currentZoom).style.visibility="visible";
		var newSliderX=47+(3-currentZoom)*8;
		parent.frames["controlframe"].document.getElementById("zoomSlider").style.left=newSliderX+"px";
		// turn on any active overlays
		updateOverlays("out");
		// if current zoom is greater than two, turn off building names
		if (currentZoom>2) {
			parent.controlframe.document.getElementById("buildingnames").checked=false;
			parent.controlframe.showIcons('buildingnames');
			}
		}
	}

// Update all overlays and icon layers
function updateOverlays(inout) {
	showOverlay("bike");
	showOverlay("parking");
	showOverlay("access");
	positionIcons(inout);
	positionAnchors(inout);
	}

// Show an overlay if it is activated
function showOverlay(layername) {
	if (parent.controlframe.document.getElementById(layername).checked) {
		for (var x=maxZoomIn;x<=maxZoomOut;x++) {
			if (x==currentZoom) {
				document.getElementById(layername+x).style.visibility="visible"}
				
			else {
				document.getElementById(layername+x).style.visibility="hidden"}
			}
		}
	}

// Reposition icons after zooming in or out
function positionIcons(inout) {
	for (var i=0; i<document.images.length; i++) {
		img=document.images[i];
		if (img.id.substr(0,5)=="icon_" || img.id=="locator") {
			// get coordinates of center of image
			var imagex=Number(img.style.left.replace(/px/gi,""))+Math.round(img.width/2);
			var imagey=Number(img.style.top.replace(/px/gi,""))+Math.round(img.height/2);
			// adjust coordinates for zooming in or out
			if (inout=="in") {
				imagex=imagex*2;
				imagey=imagey*2
				}
			else {
				imagex=Math.round(imagex/2);
				imagey=Math.round(imagey/2);
				}
			img.style.left=(imagex-Math.round(img.width/2)).toString()+"px";
			img.style.top=(imagey-Math.round(img.height/2)).toString()+"px";
			}
		}
	}

// Reposition building name anchors after zooming in or out
function positionAnchors(inout) {
	var aTags=document.getElementsByTagName("a");
	for (var i=0; i<aTags.length; i++) {
		img=aTags[i];
		if (img.id.substr(0,5)=="icon_") {
			var imagex=Number(img.style.left.replace(/px/gi,""));
			var imagey=Number(img.style.top.replace(/px/gi,""));
			if (inout=="in") {
				imagex=imagex*2;
				imagey=imagey*2
				}
			else {
				imagex=Math.round(imagex/2);
				imagey=Math.round(imagey/2);		
				}
			img.style.left=imagex.toString()+"px";
			img.style.top=imagey.toString()+"px";
			}
		}
	}

// Mouse wheel functions
// It must react to delta being more/less than zero.
function handle(delta) {
	var newX=0;
	var newY=0;
	if (delta < 0) {
		// Wheel down
		// Zoom out, keeping mouse position in the same place in the frame
		newX=Math.round(mousex-elex)/2-mousex;
		newY=Math.round(mousey-eley)/2-mousey;
		zoomOut(newX,newY);
		}
	else {
		// Wheel up
		// Zoom in, keeping mouse position in the same place in the frame
		newX=(mousex-elex)*2-mousex;
		newY=(mousey-eley)*2-mousey;
		//alert(newX+","+newY);
		zoomIn(newX,newY);
		}
	}

// Event handler for mouse wheel event.
function wheel(event) {
	var delta = 0;
	if (!event) /* For IE. */
		event = window.event;
	if (event.wheelDelta) { /* IE/Opera. */
		delta = event.wheelDelta/120;
		// In Opera 9, delta differs in sign as compared to IE.
		if (window.opera) delta = -delta;
		}
	else if (event.detail) { /** Mozilla case. */
		/** In Mozilla, sign of delta is different than in IE.
		* Also, delta is multiple of 3.
		*/
		delta = -event.detail/3;
		}
	/** If delta is nonzero, handle it.
	* Basically, delta is now positive if wheel was scrolled up,
	* and negative, if wheel was scrolled down.
	*/
	if (delta) handle(delta);

	/** Prevent default actions caused by mouse wheel.
	* That might be ugly, but we handle scrolls somehow
	* anyway, so don't bother here..
	*/
	if (event.preventDefault) event.preventDefault();
	event.returnValue = false;
}

// Pan to new location on current zoom level
// NewX and newY are upper left coordinates to move to
// Note: I couldn't get this to work.
function scrollpan(targetX,targetY) {
	var tempX=-elex;
	var tempY=-eley;
	var totalPixels=0;
	while (document.getElementById("mapint").style.left!=-targetX.toString()+"px" || document.getElementById("mapint").style.top!=-targetY.toString()+"px") {
		tempX=-Number(document.getElementById("mapint").style.left.replace(/px/gi,""));
		tempY=-Number(document.getElementById("mapint").style.top.replace(/px/gi,""));
		if (tempX<targetX) tempX++;
		if (tempX>targetX) tempX--;
		if (tempY<targetY) tempY++;
		if (tempY>targetY) tempY--;
		elex=-tempX;
		eley=-tempY;
		update();
		document.getElementById("mapint").style.left = elex.toString() + "px";
		document.getElementById("mapint").style.top  = eley.toString() + "px";
		totalPixels++;
		if (totalPixels==500) {break}
		}
	}

// Pan to new location on current zoom level
// NewX and newY are upper left coordinates to move to
function pan(targetX,targetY) {
	elex=-targetX;
	eley=-targetY;
	document.getElementById("mapint").style.left = elex.toString() + "px";
	document.getElementById("mapint").style.top  = eley.toString() + "px";
	}



// Open a building page
function viewBuilding(id) {
	if (bldgWindow) bldgWindow.close();
	var bldgWindow=window.open("building.asp?id="+id,"buildingWindow");
	}

// Set cursor
function setCursor(cur) {
	document.getElementById("mapint").style.cursor=cur;
	}

// Remove locator from map
function removeLocator() {
	document.getElementById("locator").style.visibility="hidden";
	}

// create a link to this exact map
function createLink() {
	getMapSize();
	var xcenter=Math.round((mapWidth/2-elex)/zm[currentZoom]);
	var ycenter=Math.round((mapHeight/2-eley)/zm[currentZoom]);
	var background="aerial";
	if (parent.frames["controlframe"].document.getElementById("mapBackground").checked) {background="map"}
	var layer="";
	if (parent.frames["controlframe"].document.getElementById("buildingnames").checked) {layer=layer+"buildingnames,"}
	if (parent.frames["controlframe"].document.getElementById("parking").checked) {layer=layer+"parking,"}
	if (parent.frames["controlframe"].document.getElementById("access").checked) {layer=layer+"access,"}
	if (parent.frames["controlframe"].document.getElementById("bike").checked) {layer=layer+"bike,"}
	if (parent.frames["controlframe"].document.getElementById("memorials").checked) {layer=layer+"memorials,"}
	if (parent.frames["controlframe"].document.getElementById("panoramas").checked) {layer=layer+"panoramas,"}
	if (parent.frames["controlframe"].document.getElementById("wireless").checked) {layer=layer+"wireless,"}
	if (parent.frames["controlframe"].document.getElementById("art").checked) {layer=layer+"art,"}
	if (parent.frames["controlframe"].document.getElementById("phones").checked) {layer=layer+"phones,"}
	if (parent.frames["controlframe"].document.getElementById("construction").checked) {layer=layer+"construction,"}
	layer=layer.substring(0,layer.length-1); // remove final comma
	// assemble all parameters in querystring
	var newQS="zoom="+currentZoom+"&xcenter="+xcenter+"&ycenter="+ycenter+"&background="+background
	if (layer!="") newQS=newQS+"&layer="+layer;
	if (document.getElementById("locator").style.visible="visible") {
		var xshow=Math.round((Number(document.getElementById("locator").style.left.replace(/px/gi,""))+20)/zm[currentZoom]);
		var yshow=Math.round((Number(document.getElementById("locator").style.top.replace(/px/gi,""))+20)/zm[currentZoom]);
		newQS=newQS+"&xshow="+xshow+"&yshow="+yshow;
		}
	// update and show link box
	document.getElementById("linktxt").value="http://www.fpm.iastate.edu/maps/default.asp?"+newQS;
	document.getElementById("linkdiv").style.visibility="visible";
	}