//========================================================================================================
//	MAP DHTML
//========================================================================================================
//---------------------------------------------------------------------------------------------------------
//	Init the variables
//---------------------------------------------------------------------------------------------------------

	var		mapComplete;
	var 	downLeft, downTop;
	var 	downX, downY;
	var		gotoTop, gotoLeft;
	var 	clickedonce;
	var		activeTiles = {};
	var		updateRunning = false;
	var		pauseScroll = false;
	var		totalTileCount = 0;
	
//---------------------------------------------------------------------------------------------------------
//	Init the map object
//---------------------------------------------------------------------------------------------------------
	mapWindow				= document.getElementById('map-viewport');	//	The viewfinder
	mapComplete				= document.getElementById('map-substrate');	//	The complete map, mostly hidden
	
//---------------------------------------------------------------------------------------------------------
//	Browser detection stuff
//  PHP Layers Menu 3.1.1 (C) 2001-2003 Marco Pratesi (marco at telug dot it)
//---------------------------------------------------------------------------------------------------------
	DOM = (document.getElementById) ? 1 : 0;
	NS4 = (document.layers) ? 1 : 0;
	// We need to explicitly detect Konqueror
	// because Konqueror 3 sets IE = 1 ... AAAAAAAAAARGHHH!!!
	Konqueror = (navigator.userAgent.indexOf("Konqueror") > -1) ? 1 : 0;
	// We need to detect Konqueror 2.2 as it does not handle the window.onresize event
	Konqueror22 = (navigator.userAgent.indexOf("Konqueror 2.2") > -1 || navigator.userAgent.indexOf("Konqueror/2.2") > -1) ? 1 : 0;
	Opera = (navigator.userAgent.indexOf("Opera") > -1) ? 1 : 0;
	Opera5 = (navigator.userAgent.indexOf("Opera 5") > -1 || navigator.userAgent.indexOf("Opera/5") > -1) ? 1 : 0;
	Opera6 = (navigator.userAgent.indexOf("Opera 6") > -1 || navigator.userAgent.indexOf("Opera/6") > -1) ? 1 : 0;
	Opera56 = Opera5 || Opera6;
	IE = (navigator.userAgent.indexOf("MSIE") > -1) ? 1 : 0;
	IE = IE && !Opera;
	IE5 = IE && DOM;
	IE4 = (document.all) ? 1 : 0;
	IE4 = IE4 && IE && !DOM;

//---------------------------------------------------------------------------------------------------------
//	If the map exists, register it's events
//---------------------------------------------------------------------------------------------------------
	if (mapComplete)
	{
	//---------------------------------------------------------------------------------------------------------
	//	Center the map
	//---------------------------------------------------------------------------------------------------------
		gotoPosition( gotoTop, gotoLeft );
	
	//---------------------------------------------------------------------------------------------------------
	//	Ignore dragging events
	//---------------------------------------------------------------------------------------------------------
		mapWindow.ondragstart = function(e) { return false; };

	//---------------------------------------------------------------------------------------------------------
	//	Register the mousedown event
	//---------------------------------------------------------------------------------------------------------
		mapWindow.onmousedown = function(e) 
		{
			if (!validBrowser)
			{
				return;
			}
			
			if(!e) var e = window.event;
			if((e.which && e.which == 3) || (e.button && e.button == 2)) return true;

			downLeft = parseInt(mapComplete.style.left);
			downTop  = parseInt(mapComplete.style.top);
			downX 	 = e.screenX;
			downY 	 = e.screenY;
			
			if (clickedonce)
			{
				if (e.clientX)
				{
					posTop = getOffsetTop('map-viewport');
					posLeft = getOffsetLeft('map-viewport');
				
					recordLeft = e.clientX - posLeft - downLeft;
					recordTop  = e.clientY - posTop - downTop;
				}
				
				else
				{
					recordLeft = e.X;
					recordTop  = e.Y;
				}
				
				gotoPosition(recordTop,recordLeft);
				
				clickedonce = false;
				return true;
			}
			
			
			mapWindow.style.cursor = 'move';
			this.onmousemove = movemaps;
			
			clickedonce = true;
		};
	
	//---------------------------------------------------------------------------------------------------------
	//	Register the mouseup event
	//---------------------------------------------------------------------------------------------------------
		mapWindow.onmouseup = function(e) 
		{
			if (!validBrowser)
			{
				return;
			}
			
			this.onmousemove = trackmousemove;
			if(downLeft == parseInt(mapComplete.style.left) &&
			   downTop  == parseInt(mapComplete.style.top)) return true;

			centerX = (downLeft - (viewWidth/2));
			centerY = (downTop - (viewheight/2));

			mapWindow.style.cursor = 'default';
			return startUpdate();
		};
	}



//---------------------------------------------------------------------------------------------------------
//	Determine the current position, then call makeTiles().
//	Called on page load, and when the map moves	
//---------------------------------------------------------------------------------------------------------
function startUpdate() 
{
	var vportPt1 = calcWindowPos(0, 0);
	var vportPt2 = calcWindowPos(calculateWidth(mapWindow), calculateHeight(mapWindow));
	
	x1 = vportPt1[0];
	y1 = vportPt1[1];
	x2 = vportPt2[0];
	y2 = vportPt2[1];
	
	//	Make the tiles
	makeTiles( x1, y1, x2, y2 );
}

//---------------------------------------------------------------------------------------------------------
//	Draw the tiles that are currently visable
//---------------------------------------------------------------------------------------------------------
function makeTiles( x1, y1, x2, y2 )
{
	//	The size of the tiles
	width			= 200;
	height			= 200;

	//	How many tiles to draw?
	numTileX		= 5; 
	numTileY		= 5;

	//	Define a bunch of stuff
	left_num		= Math.floor( x1 /200 * 1);
	top_num			= Math.floor( y1 / 200 * 1);
	
	//	Draw the tiles that are in the viewport
	for( x = 0; x <= numTileX; x++)
	{
		for( y = 0; y <= numTileY; y++)
		{
			//	Are we beyond the height?
			if (((top_num + y)*200) > totalHeight)
			{
				//	Yes, do not draw the tile
				continue;
			}

			//	Are we boyond the width?
			if (((left_num + x)*200) > totalWidth)
			{
				//	Yes, do not draw the tile
				continue;
			}

			//	Tile should be visable, so draw it
			drawTile( top_num + y, left_num + x, width, height );
		}
	}
}

//---------------------------------------------------------------------------------------------------------
//	Draw a tile, if is not already
//---------------------------------------------------------------------------------------------------------
function drawTile( top_num, left_num, tileWidth, tileHeight )
{
	//	Get the view pos
	top_pos		   = top_num * tileHeight;
	left_pos	   = left_num * tileWidth;
	
	if (top_pos < 0)
	{
		return;
	}

	if (left_pos < 0)
	{
		return;
	}

	//	If the tile is already displayed, just add the image
	if (activeTiles[top_pos + "-" + left_pos])
	{
		//	Generate the tile image filename
		var fileName = top_pos + '_' + left_pos + '.jpg';
		
		//	Make the image path
		srcPath = tileURL + '/tiles_' + zoom + '/' + fileName;
		
		exisitingTile 		= document.getElementById(top_pos + '_' + left_pos);
		exisitingTile.src 	= srcPath;
	}	
	
	//	If the tile is not already displayed, generate it and append  it
	else
	{
		//	Generate the tile image filename
		var fileName = top_pos + '_' + left_pos + '.jpg';
		
		//	Make the image path
		srcPath = tileURL + '/tiles_' + zoom + '/' + fileName;
		
		//	Figure out where to put it
		top_pos			= top_pos;
		left_pos		= left_pos;
		var newHeight	= tileHeight;
		var newWidth	= tileWidth;

		//	Generate the new div element
		newTile	 			 			= document.createElement('img');
		newTile.id 						= top_pos + '_' + left_pos;
		newTile.src 					= srcPath;
		newTile.style.top 	 			= top_pos + 'px';
		newTile.style.left 	 			= left_pos + 'px';
		newTile.style.position 			= 'absolute';
		newTile.style.position 			= 'absolute';
//		newTile.style.zIndex 			= -1;
		
		//	Append the div element
		mapComplete.appendChild(newTile);
		
		totalTileCount++;
	
		//	Record the tile as having been drawn
		activeTiles[top_pos + "-" + left_pos] = 1;
	}
}

//---------------------------------------------------------------------------------------------------------
//	Process the map movements
//---------------------------------------------------------------------------------------------------------
function movemaps(e) 
{
	if(!e) var e = window.event;
	
	clickedonce = false;
	
	moveLeft = (downLeft + e.screenX - downX);
	moveTop  = (downTop  + e.screenY - downY);

	mapComplete.style.left = moveLeft + 'px';
	mapComplete.style.top  = moveTop + 'px';
}

function trackmousemove(e)
{
	clickedonce = false;
}

//---------------------------------------------------------------------------------------------------------
//	Perform the size calculations
//---------------------------------------------------------------------------------------------------------
function getOffsetLeft(layer) {
	var value = 0;
	if (DOM) {	// Mozilla, Konqueror >= 2.2, Opera >= 5, IE
		object = document.getElementById(layer);
		value = object.offsetLeft;
		while (object.tagName != "BODY" && object.offsetParent) {
			object = object.offsetParent;
			value += object.offsetLeft;
		}
	} else if (NS4) {
		value = document.layers[layer].pageX;
	} else {	// IE4 IS SIMPLY A BASTARD !!!
		if (document.all["IE4" + layer]) {
			layer = "IE4" + layer;
		}
		object = document.all[layer];
		value = object.offsetLeft;
		while (object.tagName != "BODY") {
			object = object.offsetParent;
			value += object.offsetLeft;
		}
	}
	return (value);
}


function getOffsetTop(layer) {
	var value = 0;
	if (DOM) {
		object = document.getElementById(layer);
		value = object.offsetTop;
		while (object.tagName != "BODY" && object.offsetParent) {
			object = object.offsetParent;
			value += object.offsetTop;
		}
	} else if (NS4) {
		value = document.layers[layer].pageY;
	} else {	// IE4 IS SIMPLY A BASTARD !!!
		if (document.all["IE4" + layer]) {
			layer = "IE4" + layer;
		}
		object = document.all[layer];
		value = object.offsetTop;
		while (object.tagName != "BODY") {
			object = object.offsetParent;
			value += object.offsetTop;
		}
	}
	return (value);
}

function calcWindowPos(x, y) 
{
	var vportRelX = x - parseInt(mapComplete.style.left);
	var vportRelY = y - parseInt(mapComplete.style.top);
	
	return new Array(vportRelX, vportRelY);
}

function calculateHeight(el) 
{
	if(document.defaultView) 
	{
		return parseInt(document.defaultView.getComputedStyle(el, "").getPropertyValue('height'));
	} 
	else if(el.offsetHeight) 
	{
		return el.offsetHeight;
	}
	
	return 0;
}

function calculateWidth(el) 
{
	if(document.defaultView) 
	{
		return parseInt(document.defaultView.getComputedStyle(el, "").getPropertyValue('width'));
	} 
	else if(el.offsetWidth) 
	{
		return el.offsetWidth;
	}
	
	return 0;
}

//---------------------------------------------------------------------------------------------------------
//	Handle the four direction scroll buttons
//---------------------------------------------------------------------------------------------------------
function scrollMapLeft()
{
	distance = viewWidth/2;
	downLeft = parseInt(document.getElementById('map-substrate').style.left);
	downTop  = parseInt(document.getElementById('map-substrate').style.top);
	
	scrollMap(downTop,(downLeft+distance));
}

function scrollMapUp()
{
	distance = viewheight/2;
	downLeft = parseInt(document.getElementById('map-substrate').style.left);
	downTop  = parseInt(document.getElementById('map-substrate').style.top);
	
	scrollMap((downTop+distance),downLeft);
}

function scrollMapDown()
{
	distance = viewheight/2;
	downLeft = parseInt(document.getElementById('map-substrate').style.left);
	downTop  = parseInt(document.getElementById('map-substrate').style.top);
	
	scrollMap((downTop-distance),downLeft);
}

function scrollMapRight()
{
	distance = viewWidth/2;
	downLeft = parseInt(document.getElementById('map-substrate').style.left);
	downTop  = parseInt(document.getElementById('map-substrate').style.top);
	
	scrollMap(downTop,(downLeft-distance));
}

//---------------------------------------------------------------------------------------------------------
//	Manually scroll the map to a given locations
//---------------------------------------------------------------------------------------------------------
function scrollMap( mvTop, mvLeft )
{
	//	Move the map
	document.getElementById('map-substrate').style.top  = mvTop + 'px';
	document.getElementById('map-substrate').style.left = mvLeft + 'px';
	
	//	Update the tiles
	startUpdate();
}

//---------------------------------------------------------------------------------------------------------
//	Toggle the location items
//---------------------------------------------------------------------------------------------------------
function showItems( id )
{
	document.getElementById('items'+id).style.display = 'block';
}

function hideItems( id )
{
	document.getElementById('items'+id).style.display = 'none';
}

//---------------------------------------------------------------------------------------------------------
//	Zoom in/out of the map
//---------------------------------------------------------------------------------------------------------
function changeZoom(level)
{
	var percentFromTop;
	var percentFromLeft;
	
	//	What current distance from edge?
	currLeft  = parseInt(mapComplete.style.left);
	currTop   = parseInt(mapComplete.style.top);
	currLeft  = (-currLeft) + (viewWidth/2);
	currTop   = (-currTop) + (viewheight/2);
	
	//	Convert that disatance to the 100% distance
	actualLeft = currLeft/percent;
	actualTop  = currTop/percent;
	
	//	Update the control form
	document.forms.zoomcontrol['zoom'].value		= level;
	document.forms.zoomcontrol['prevzoom'].value 	= zoom;
	document.forms.zoomcontrol['top'].value			= actualTop;
	document.forms.zoomcontrol['left'].value		= actualLeft;
	document.forms.zoomcontrol.submit();
}

//---------------------------------------------------------------------------------------------------------
//	Center on a specific map location
//---------------------------------------------------------------------------------------------------------
function gotoPosition( top, left )
{
	topPos  = (-top) + (viewheight/2);
	leftPos = (-left) + (viewWidth/2);
	
	scrollMap(topPos, leftPos);
}

//---------------------------------------------------------------------------------------------------------
//	Toggle the location details box
//---------------------------------------------------------------------------------------------------------
var currDetails;

function showLocationDetails( id )
{
	if (id)
	{
		document.getElementById('details'+id).style.display = 'block';
	}
}

function hideLocationDetails( id )
{
	if (id)
	{
		document.getElementById('details'+id).style.display = 'none';
	}
}

//---------------------------------------------------------------------------------------------------------
//	Basic popup opener for the map window
//---------------------------------------------------------------------------------------------------------
function openMapPopup ( content, target, sizeX, sizeY )
{
	//	Center the window
	leftpos	= (screen.width)  ? (screen.width-sizeX)/2 : 100;
	toppos	= (screen.height) ? (screen.height-sizeY)/2 : 100;

	//	Define the window size
	widthVar  = 'width=' + sizeX + ',';
	heightVar = 'height=' + sizeY + ',';
	
	//	Open the window
	winobject    = window.open(content,target,"menubar=0,statusbar=no,scrollbars=1,toolbar=0,location=0," + widthVar + heightVar + "left=" + leftpos + ",top=" + toppos + ",resizable=0" );
	winobject.focus();

}

