//========================================================================================================
//	MAP DHTML
//========================================================================================================

function openPopup ( 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,"resizable=1,scrollbars=1,menubar=0,status=0,toolbar=0,location=0,width=640,height=512,left=100,top=100");
	winobject.focus();

}


//---------------------------------------------------------------------------------------------------------
//	Init the variables
//---------------------------------------------------------------------------------------------------------
	var 	downLeft, downTop;
	var 	downX, downY;
	var		gotoTop, gotoLeft;
	var 	clickedonce, zoom, forceZoom, gotoY, gotoX, iconLayers;
	var		browserString, isSafari;
	var		totalWidth, totalHeight;

	var		activeTiles 	= {};
	var		tileList		= new Array();
	var		updateRunning 	= false;
	var		pauseScroll 	= false;
	var		totalTileCount 	= 0;
	
	iconLayers = document.getElementById('icon-layers-original').innerHTML;
	document.getElementById('icon-layers-original').innerHTML = '';
	
	var browserString = navigator.userAgent.toLowerCase();
	var isSafari 	  = browserString.indexOf('safari') + 1
	
//---------------------------------------------------------------------------------------------------------
//	Start the map functionality
//---------------------------------------------------------------------------------------------------------
	function initMap()
	{
	//---------------------------------------------------------------------------------------------------------
	//	Init the map object
	//---------------------------------------------------------------------------------------------------------
		mapFrame				= document.getElementById('map-frame');		//	The viewfinder
		mapContents				= document.getElementById('map-contents');	//	The complete map, mostly hidden
		loadingPane				= document.getElementById('loading-pane');	//	The complete map, mostly hidden
		activeTiles				= {};
	
		if (!zoom)
		{
			zoom = forceZoom ? forceZoom : defaultLevel;
		
			eval("totalWidth  = width"+zoom+";");
			eval("totalHeight = height"+zoom+";");
			eval("percent	  = percent"+zoom+";");
			
			gotoY ? ( gotoTop  = gotoY ) : eval("gotoTop  = centerx"+zoom+";");
			gotoX ? ( gotoLeft = gotoX ) : eval("gotoLeft = centery"+zoom+";");
			
			mapContents.innerHTML	= '';
			mapContents.innerHTML	= iconLayers;
		}
		
	//---------------------------------------------------------------------------------------------------------
	//	Ignore dragging events
	//---------------------------------------------------------------------------------------------------------
		mapFrame.ondragstart = function(e) { return false; };
	
	//---------------------------------------------------------------------------------------------------------
	//	Display the map contents
	//---------------------------------------------------------------------------------------------------------
		//	Center the map
		gotoPosition( gotoTop, gotoLeft );
		
		//	Display the icon types that the user has previously selected
		showIconLayers();
	
		//	Set the fade timer
		if (loadingPane)
		{
			setTimeout( "fade(90);",2000 );
			setTimeout( "fade(80);",2100 );
			setTimeout( "fade(70);",2200 );
			setTimeout( "fade(60);",2300 );
			setTimeout( "fade(50);",2400 );
			setTimeout( "fade(40);",2500 );
			setTimeout( "fade(30);",2600 );
			setTimeout( "fade(20);",2700 );
			setTimeout( "fade(10);",2800 );
			setTimeout( "fade(0);",2900 );
			setTimeout( "loadingPane.style.display = 'none';",2900 );
		}
			
	//---------------------------------------------------------------------------------------------------------
	//	Register the mousedown event
	//---------------------------------------------------------------------------------------------------------
		mapFrame.onmousedown = function(e) 
		{
			if (!validBrowser || zoom == 1)
			{
				return;
			}
			
			if(!e) var e = window.event;
			if((e.which && e.which == 3) || (e.button && e.button == 2)) return true;
	
			downLeft = parseInt(mapContents.style.left);
			downTop  = parseInt(mapContents.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;
			}

			mapFrame.style.cursor = 'move';
			this.onmousemove = processMapMove;
			
			clickedonce = true;
		};
	
	//---------------------------------------------------------------------------------------------------------
	//	Register the mouseup event
	//---------------------------------------------------------------------------------------------------------
		mapFrame.onmouseup = function(e) 
		{
			if (!validBrowser || zoom == 1)
			{
				return;
			}
			
			this.onmousemove = trackmousemove;
			if(downLeft == parseInt(mapContents.style.left) &&
			   downTop  == parseInt(mapContents.style.top)) return true;
	
			centerX = (downLeft - (viewWidth/2));
			centerY = (downTop - (viewheight/2));
	
			mapFrame.style.cursor = 'default';
			return updateMapContents();
		};
	}

//---------------------------------------------------------------------------------------------------------
//	Process the map movements
//---------------------------------------------------------------------------------------------------------
	function processMapMove(e) 
	{
		if(!e) var e = window.event;
		
		clickedonce = false;
	
		moveLeft 				= (downLeft + e.screenX - downX);
		moveTop  				= (downTop  + e.screenY - downY);
		mapContents.style.left 	= moveLeft + 'px';
		mapContents.style.top  	= moveTop + 'px';
	}

//---------------------------------------------------------------------------------------------------------
//	Determine the current position, then call renderVisableTiles().
//	Called on page load, and when the map moves	
//---------------------------------------------------------------------------------------------------------
	function updateMapContents() 
	{
		x1 		  = -(parseInt(mapContents.style.left));
		y1 		  = -(parseInt(mapContents.style.top));
		x2 		  = viewWidth - parseInt(mapContents.style.left);
		y2  	  = viewheight - parseInt(mapContents.style.top);
		
		//	Make the tiles
		renderVisableTiles( x1, y1, x2, y2 );
	}

//---------------------------------------------------------------------------------------------------------
//	Draw the tiles that are currently visable
//---------------------------------------------------------------------------------------------------------
	function renderVisableTiles( x1, y1, x2, y2 )
	{
		//	The size of the tiles
		width			= 200;
		height			= 200;
	
		//	How many tiles to draw?
		numTileX		= 4; 
		numTileY		= 4;
	
		//	Calculate the actual number
		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)
				{
					continue;
				}
	
				//	Are we boyond the width?
				if (((left_num + x)*200) >= totalWidth)
				{
					continue;
				}
	
				//	Tile should be visable, so draw it
				makeTile( top_num + y, left_num + x, width, height );
			}
		}
	}

//---------------------------------------------------------------------------------------------------------
//	Draw a tile, if is not already
//---------------------------------------------------------------------------------------------------------
	function makeTile( 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?uid=' + GenUniqueImageID();
			
			//	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?uid=' + GenUniqueImageID();
			
			//	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.width 	 		= '200px';
			//newTile.style.height 	 		= '200px';
			
			newTile.style.position 			= 'absolute';
			
			//	This is kinda weird on Safari....
			if (!isSafari)
			{
				//newTile.style.zIndex = -1;
			}
			
			//	Append the div element
			mapContents.appendChild(newTile);
			totalTileCount++;
		
			//	Record the tile as having been drawn
			activeTiles[top_pos + "-" + left_pos] = 1;

			//	Add to the tile list, so we can clear later
			tileList.push( top_pos + '_' + left_pos );
		}
	}

//---------------------------------------------------------------------------------------------------------
//	Center on a specific map location
//---------------------------------------------------------------------------------------------------------
	function gotoPosition( top, left )
	{
		topPos  = (-top) + (viewheight/2);
		leftPos = (-left) + (viewWidth/2);
		
		moveMapPosition(topPos, leftPos);
	}
	
//---------------------------------------------------------------------------------------------------------
//	Manually scroll the map to a given locations
//---------------------------------------------------------------------------------------------------------
	function moveMapPosition( mvTop, mvLeft )
	{
		//	Move the map
		document.getElementById('map-contents').style.top  = mvTop + 'px';
		document.getElementById('map-contents').style.left = mvLeft + 'px';
		
		//	Update the tiles
		updateMapContents();
	}

//---------------------------------------------------------------------------------------------------------
//	Handle the four direction scroll buttons
//---------------------------------------------------------------------------------------------------------
	function scrollMapLeft()
	{
		if (zoom == 1)
		{
			return;
		}

		distance = viewWidth/2;
		downLeft = parseInt(document.getElementById('map-contents').style.left);
		downTop  = parseInt(document.getElementById('map-contents').style.top);
		
		var steps = 10;
		for( i=1; i<=steps; i++)
		{
			setTimeout( "moveMapPosition(downTop,(downLeft+"+(distance/steps)*i+"))",i*50 );
		}
	}
	
	function scrollMapUp()
	{
		if (zoom == 1)
		{
			return;
		}

		distance = viewheight/2;
		downLeft = parseInt(document.getElementById('map-contents').style.left);
		downTop  = parseInt(document.getElementById('map-contents').style.top);
		
		var steps = 10;
		for( i=1; i<=steps; i++)
		{
			setTimeout( "moveMapPosition((downTop+"+(distance/steps)*i+"),downLeft)",i*50 );
		}
	}
	
	function scrollMapDown()
	{
		if (zoom == 1)
		{
			return;
		}

		distance = viewheight/2;
		downLeft = parseInt(document.getElementById('map-contents').style.left);
		downTop  = parseInt(document.getElementById('map-contents').style.top);
		
		var steps = 10;
		for( i=1; i<=steps; i++)
		{
			setTimeout( "moveMapPosition((downTop-"+(distance/steps)*i+"),downLeft)",i*50 );
		}
	}
	
	function scrollMapRight()
	{
		if (zoom == 1)
		{
			return;
		}

		distance = viewWidth/2;
		downLeft = parseInt(document.getElementById('map-contents').style.left);
		downTop  = parseInt(document.getElementById('map-contents').style.top);
		
		var steps = 10;
		for( i=1; i<=steps; i++)
		{
			setTimeout( "moveMapPosition(downTop,(downLeft-"+(distance/steps)*i+"))",i*50 );
		}
	}

//---------------------------------------------------------------------------------------------------------
//	Toggle the location items
//---------------------------------------------------------------------------------------------------------
	function showItems( id )
	{
		if(document.getElementById('items'+zoom+'-'+id))
		{
			document.getElementById('items'+zoom+'-'+id).style.display  = 'block';
			document.getElementById('hide'+id).style.display			= 'inline';
			document.getElementById('show'+id).style.display			= 'none';
		}
	
		make_cookie( 'iconlayer'+id, 'show' );
	}
	
	function hideItems( id )
	{
		if( document.getElementById('items'+zoom+'-'+id) )
		{
			document.getElementById('items'+zoom+'-'+id).style.display	= 'none';
			document.getElementById('hide'+id).style.display			= 'none';
			document.getElementById('show'+id).style.display			= 'inline';
		}
	
		make_cookie( 'iconlayer'+id, '' );
	}

//---------------------------------------------------------------------------------------------------------
//	Zoom in/out of the map
//---------------------------------------------------------------------------------------------------------
	function changeZoom(newZoom)
	{
		var percentFromTop;
		var percentFromLeft;
		
		//	The plus or minus icon was clicked...translate to a number
		switch(newZoom) 
		{
      		case 'up':
      			(zoom == levelCount) ? '' : newZoom = zoom+1;
      		break;
			
	   		case 'down':
      			(zoom == 1) ? '' : newZoom = zoom-1;
      		break;
		}

		//	Hide the icons
		hideAllIconLayers();
		
		//	Toggle the highlit indicators
		swapImg('nav' + zoom ,'/images/zoom/' + zoom + '.gif');
		swapImg('nav' + newZoom ,'/images/zoom/' + newZoom + 'a.gif');
		
		//	What current distance from edge?
		currLeft  = parseInt(mapContents.style.left);
		currTop   = parseInt(mapContents.style.top);
		currLeft  = (-currLeft) + (viewWidth/2);
		currTop   = (-currTop) + (viewheight/2);
		
		//	Convert that disatance to the 100% distance
		actualLeft = currLeft/percent;
		actualTop  = currTop/percent;
		
		//	Set the new values
		if (newZoom == 1)
		{
			eval("percent		= percent"+newZoom+";");
			eval("totalWidth	= width"+newZoom+";");
			eval("totalHeight	= height"+newZoom+";");
			gotoTop				= centerx1;
			gotoLeft			= centery1;
		}
		else
		{
			eval("percent		= percent"+newZoom+";");
			eval("totalWidth	= width"+newZoom+";");
			eval("totalHeight	= height"+newZoom+";");
			gotoTop				= Math.ceil(actualTop*percent);
			gotoLeft			= Math.ceil(actualLeft*percent);
		}

		zoom				= newZoom
		
		//	Set the fade timer
		setTimeout( "fade(01);",40 );
		if (loadingPane)
		{
			setTimeout( "loadingPane.style.display = 'block';",45 );
			setTimeout( "loadingPane.src = '/images/loading.gif';",45 );
		}
		setTimeout( "fade(20);",50 );
		setTimeout( "fade(40);",100 );
		setTimeout( "fade(60);",150 );
		setTimeout( "fade(80);",200 );
		setTimeout( "fade(100);",250 );
		setTimeout( "clearActiveTiles();",150 );
		setTimeout( "initMap();",450 );
	}

//---------------------------------------------------------------------------------------------------------
//	When a zoom takes place, make sure we clear the previous tiles
//---------------------------------------------------------------------------------------------------------
	function clearActiveTiles()
	{
		if (!tileList)
		{
			return;
		}
		
		imageObjectsLength	= tileList.length;
		
		for( i=0; i<=imageObjectsLength;i++)
		{
			imageObjectID = tileList[i];
			imageObject   = document.getElementById( imageObjectID );

			if (imageObject)
			{
				mapContents.removeChild(imageObject);
			}
		}
	}

//---------------------------------------------------------------------------------------------------------
//	When a zoom takes place, make sure we hide the previous icons
//---------------------------------------------------------------------------------------------------------
	function hideAllIconLayers()
	{
		for( i=1; i<=icon_types;i++)
		{
			if( document.getElementById('items'+zoom+'-'+i) )
			{
				document.getElementById('items'+zoom+'-'+i).style.display	= 'none';
			}
		}
	}

//---------------------------------------------------------------------------------------------------------
//	This might not be used anymore....
//---------------------------------------------------------------------------------------------------------
function trackmousemove(e)
{
	clickedonce = false;
}

//---------------------------------------------------------------------------------------------------------
//	Toggle the location details box
//---------------------------------------------------------------------------------------------------------
	var currDetails;
	
	function showLocationDetails( id )
	{
		if (id)
		{
			document.getElementById('details'+id).style.display = 'block';
			document.getElementById('details'+id).style.zIndex  = 100;
			
			
		}
	}
	
	function hideLocationDetails( id )
	{
		if (id)
		{
			document.getElementById('details'+id).style.display = 'none';
		}
	}

//---------------------------------------------------------------------------------------------------------
//	Basic popup opener for the map window
//---------------------------------------------------------------------------------------------------------
	function openPopup ( 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,toolbar=0,location=0," + widthVar + heightVar + "left=" + leftpos + ",top=" + toppos + ",resizable=0" ); 
		winobject.focus();
	}

//---------------------------------------------------------------------------------------------------------
//	Fade animation
//---------------------------------------------------------------------------------------------------------
	function fade( level )
	{
		if (loadingPane)
		{
			if (loadingPane.style.filter)
				loadingPane.style.filter="alpha(opacity=" + level + ")"
			else if (loadingPane.style.MozOpacity)
				loadingPane.style.MozOpacity=level/101
			else if (loadingPane.style.opacity)
				loadingPane.style.opacity=level/101
			else if (loadingPane.style.KhtmlOpacity)
				loadingPane.style.KhtmlOpacity=level/100
		}
	}

//-------------------------------------------------------------------------------------------------------
//	Image swap
//-------------------------------------------------------------------------------------------------------
	function swapImg(id,img)
	{
		if( document.getElementById)
		{
			obj	= document.getElementById(id);
			obj.setAttribute( 'src', img );
		}
	}

//-------------------------------------------------------------------------------------------------------
//	When the page loads, re-show the icon layers
//-------------------------------------------------------------------------------------------------------
	function showIconLayers()
	{
		for( i=1; i<=icon_types;i++)
		{
			cookieVal = find_cookie('iconlayer'+i);
			
			if (cookieVal == 'show')
			{
				showItems( i );
			}
		}
	}

//-------------------------------------------------------------------------------------------------------
//	Generate a unique image ID for the tile image
//-------------------------------------------------------------------------------------------------------
	function GenUniqueImageID()
	{
		var dateValue = new Date();
		var timestamp = (dateValue.getTime());
		
		return timestamp;
	}
