/*

Author : Simon Haddon simon@sibern.com.au
Written: 27/01/2006
Description :
	provide the mapserver mapping interface actions and controls

Credits:

  this software is based on 
  GMap mapping engine (PHP/MapScript, version gmap75.* )
  Copyright (c) 2000-2003, DM Solutions Group 
  and modifications performed by Steffen Vogt, IPG Universitaet Freiburg
  Copyright (c) 2004-05, IPG Universtaet Freiburg
 
  this software includes Javascript code snippets by Dr. Klaus Braun, IPG Universitaet Freiburg
  modifications and extensions by Steffen Vogt & Armin Waespy, IPG Universitaet Freiburg.
  formatFloat from Chris Scott at http://p2p.wrox.com/topic.asp?TOPIC_ID=13031 

*/

// Decide browser version

var ns4 = (document.layers)? true:false;
var ns6 = (document.getElementById)? true:false;
var ie4 = (document.all)? true:false;
if (ie4) var docRoot = 'document.body';
var mapControlsInit = false;
var ie5 = false;

var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;

var myCanvasSelect = "myCanvas";

if (ie4) 
{
	if ((navigator.userAgent.indexOf('MSIE 5') > 0) || (navigator.userAgent.indexOf('MSIE 6') > 0) || (navigator.userAgent.indexOf('MSIE 7') > 0)) 
	{
		if(document.compatMode && document.compatMode == 'CSS1Compat') docRoot = 'document.documentElement';
		ie5 = true;
		//myCanvasSelect = "myCanvas-ie5";
		//alert('fallen into ie5');
	}
	if (ns6) 
	{
	ns6 = false;
	}
}

//alert('Checking Browsers\nns4: '+ ns4 + '\nns6: ' + ns6 + '\nie4: ' + ie4 + '\nie5: ' + ie5 + '\nie7: '+ ie7);

/*******************************************************************/
function printMap()
{
	//alert('About to open a new print window');
  thewindowFeatures = 'toolbar=0,location=0,directories=0,status=1,menuBar=0,scrollBars=1,resizable=0';
	openWindow('index.cfm?fa=mui.print','printwindow',710,700, thewindowFeatures);
}


/*******************************************************************/
//    function to open a new window
function openWindow(windowURL, windowName, width, height, windowFeatures)
{
  thewindowName = 'NewWindow';
  //windowFeatures = 'width=600,height=500 toolbar=0,location=0,directories=0,status=0,menuBar=0,scrollBars=1,resizable=1';
  thewindowFeatures = 'toolbar=1,location=1,directories=0,status=1,menuBar=1,scrollBars=1,resizable=1';
  theWidth = 640;
  theHeight = 480;
  if (arguments.length > 1 && arguments[1] != '') thewindowName = arguments[1];
  if (arguments.length > 2 && arguments[2] != '') theWidth = arguments[2];
  if (arguments.length > 3 && arguments[3] != '') theHeight = arguments[3];
  if (arguments.length > 4 && arguments[4] != '') thewindowFeatures = arguments[4];

  new_win = window.top.open( windowURL, thewindowName, thewindowFeatures+',width='+theWidth+',height='+theHeight, 0 );
  new_win.opener = window;
  new_win.focus();
}


/*******************************************************************/
function mapInit() 
{
   
	//startmenu();
	
	// set JavaScript name for main window
	self.name = "muiMap";
	 
	// Default values for mouse events
	MouseMoveDefault = document.onmousemove;
	MouseDownDefault = document.onmousedown;
	MouseUpDefault = document.onmouseup;
	
	// Capture events
	
	if ( (ns4) || (ie4) || (ns6)) 
	{
		document.onmousemove = mouseMove;
		if (ns4) document.captureEvents(Event.MOUSEMOVE);
	}
	
	// Calculate position of mainmap
	MainMapTop = DL_GetElementTop(document.getElementsByName('mainmap')[0]);
	MainMapLeft = DL_GetElementLeft(document.getElementsByName('mainmap')[0]);
	
	document.getElementsByName('mainmap')[0].style.position = 'absolute';
	document.getElementsByName('mainmap')[0].style.top = MainMapTop;
	document.getElementsByName('mainmap')[0].style.left = MainMapLeft;
	
	MainMapHeight = document.mapserv.imageHeight.value;
	MainMapWidth = document.mapserv.imageWidth.value;

	// Adjust div size rather than in the css
	document.getElementById(myCanvasSelect).style.height = MainMapHeight - 20;
	document.getElementById(myCanvasSelect).style.width = MainMapWidth - 20;
	document.getElementById(myCanvasSelect).style.top = MainMapTop;
	document.getElementById(myCanvasSelect).style.left = MainMapLeft;
	
				
	document.getElementById("cursx").style.top = MainMapTop;
	document.getElementById("cursx").style.left = MainMapLeft;
	document.getElementById("cursx").style.height = MainMapHeight;
	document.getElementById("cursy").style.top = MainMapTop;
	document.getElementById("cursy").style.left = MainMapLeft;
	document.getElementById("cursy").style.width = MainMapWidth;
	
	// initialize measurement line
	jg = new jsGraphics(myCanvasSelect);
	jg.setColor("#ff0000");
	
	// shows a loading map be patient image (could be a gif-animation 
	document.getElementById("loadmap-img").style.top = MainMapTop + (MainMapHeight / 2) - 15;
	document.getElementById("loadmap-img").style.left = MainMapLeft + (MainMapWidth / 2) - 137;
	// here should go the penguin
	// document.getElementById("loadmap-owl").style.top = MainMapTop + (MainMapHeight / 2) - 38;
	// document.getElementById("loadmap-owl").style.left = MainMapLeft + (MainMapWidth / 2) - 131;
	
	//
	
	textnode = document.createTextNode("");
	document.getElementById("tipp").appendChild(textnode);
	
	//
	
	MainMapMovedLeft = MainMapLeft;
	MainMapMovedTop = MainMapTop;

	mapControlsInit = true;

}

/*******************************************************************/
//function zoomToLocation(laty, longx)
function zoomToLocation(minx, miny, maxx, maxy, regionId, setRegion, highlight)
{

	if (setRegion)
	{
		//alert('Set the region from search');
		top.document.selectedRegion.CoordX.value = minx + ((maxx - minx) / 2);
		top.document.selectedRegion.CoordY.value = miny + ((maxy - miny) /2);
		top.document.selectedRegion.searchRegionId.value = regionId;
		top.document.selectedRegion.regionSelectorEvent.value = "search";
		top.document.selectedRegion.submit();
		loadmap();
	}
	else
	{
		//document.mapserv.coordx.value = longx;
		//document.mapserv.coordy.value = laty;
		document.mapserv.zoom_rect_minx.value = minx;
		document.mapserv.zoom_rect_miny.value = miny;
		document.mapserv.zoom_rect_maxx.value = maxx;
		document.mapserv.zoom_rect_maxy.value = maxy;
		if (highlight)
		{
			document.mapserv.search_id.value = regionId;
			document.mapserv.cmd.value = 'set_extents_highlight';
		}
		else
			document.mapserv.cmd.value = 'set_extents';

		document.mapserv.submit();
	}
	
	loadmap();
}

/*******************************************************************/
function ChangeFunctionality(mode) 
{
	var scale = document.mapserv.scale.value;
	var minscale = document.mapserv.minscale.value;

	//alert("Changing function to " + mode);
	document.mapserv.cmd.value = mode;

	switch(mode)
	{
		case 'zoom_rect':
			//document.mapserv.zoomin_holder.src = navZoominOn.src;
			//top.document.getElementById("icon_max_extent").border = "1";
			/*if (Math.round(scale) < minscale)
			{ // Problems with alert box events
				alert('You may not zoom in any further');			
				document.mapserv.cmd.value = 'zoom_out';
			}*/
			break;
		case 'zoom_out':
  				//document.mapserv.zoomout_holder.src = navZoomoutOn.src;
			break;
		case 'move':
  				//document.mapserv.pan_holder.src = navPanOn.src;
			break;
		case 'max_extent':
				//document.mapserv.zoomext_holder.src = navZoomextOn.src;
			//document.mapserv.target = "_parent";
			document.mapserv.submit();
			loadmap();
			break;
		case 'otherURL':
			// Just need to show loading image
			loadmap();
			break;
		case 'orig_extent':
			document.mapserv.submit();
			loadmap();
			break;
		case 'redraw':
			document.mapserv.submit();
			loadmap();
			break;
		case 'region_search':
  				//document.mapserv.pan_holder.src = navPanOn.src;
			break;
		case 'region_select':
  				//document.mapserv.pan_holder.src = navPanOn.src;
			break;
		case 'query_point':
  				//document.mapserv.query_holder.src = navQueryOn.src;
			break;
		case 'draw_point':
  				//document.mapserv.point_holder.src = navPointOn.src;
			break;
		case 'draw_line':
  				//document.mapserv.line_holder.src = navLineOn.src;
			break;
		case 'draw_poly':
  				//document.mapserv.area_holder.src = navPolyOn.src;
			break;
		case 'measure':
  				//document.mapserv.measure_holder.src = navMeasureOn.src;
			break;
  	case 'print':
  				printMap();
			break;

	}        
	myCanvas_clear();
}

var currStep = 0;
var j = 0;

/*******************************************************************/
function myCanvas_clear() 
{
	myCanvas_clicks = 0;
	dist = 0;
	if (mapControlsInit)
		jg.clear();
	draw_x.length = 0;
	draw_y.length = 0;
	// document.mapserv.distance.value = dist + ' m';
	
	//document.getElementById("zoomrect").style.visibility = 'hidden';
	//document.getElementById("zoomrect").style.width = 1;
	//document.getElementById("zoomrect").style.height = 1;
	
	return;
}

/*******************************************************************/
function QueryCheck(qCmd) 
{
	var cmd = document.mapserv.cmd.value;
	var CoordX = document.mapserv.coordx.value;
	var CoordY = document.mapserv.coordy.value;

 	//alert('QueryCheck=['+qCmd+']=['+cmd+']');
	//loadmap();
	
	if (arguments.length == 1 && qCmd != "")
		cmd = qCmd;

	if (cmd == 'query_point' && clickimg == 1) 
	{
		document.getElementById("loadmap-img").style.visibility = 'hidden';
		openWindow('','querywindow',900,750);
		document.mapserv.target="querywindow";
		clickimg = 0;
		return;
	}
	//else
	//{
	//	if(nwin == 1) 
	//	{
	//		openWindow('','querywindow',900,750);
	//		document.mapserv.target="querywindow";
	//		nwin = 0;
	//		return;  					
	//	}
	//	else 
	//	{
	//		document.mapserv.target="_parent";
	//		clickimg = 0;
	//		return;
	//	}
	//}
	if (cmd == 'region_search')
	{
		var width = 500;
		var height = 300;
		var leftPos = (screen.width / 2) - (width / 2)
		var topPos = (screen.height / 2) - (height / 2)
	
		if (clickimg == 0)
		{
			windowURL = 'index.cfm?fa=mui.addRegion&coordX='+CoordX+'&coordY='+CoordY;
			windowName = 'RegionSelection';
			windowFeatures = 'top='+topPos+',left='+leftPos+',width='+width+',height='+height+',toolbar=0,location=0,directories=0,status=0,menuBar=0,scrollBars=0,resizable=0';
			//if (arguments.length > 1 && arguments[1] != '') 
			//	windowName = arguments[1];
			RegionSelection = window.top.open( windowURL, windowName, windowFeatures, 0 );
			RegionSelection.focus();
			clickimg = 1;
			return false;
		}
		else
		{
			document.mapserv.target="";
			document.mapserv.submit();
			RegionSelection.close();
			clickimg = 0;
		}
		return true;
	}
	
	if (cmd == 'region_select')
	{
		// Get the main window to rebuild itself with the coordinates so that it can work
		// out where was selected and then take appropiate action
		//var regionSelectURL = 'index.cfm?fa=mui.regionSelect&coordX='+CoordX+'&coordY='+CoordY;
		//top.document.location = regionSelectURL;
		// TODO.  Make this bit work the same as the MUI.  All map events directly in the iframe.
		// The only bit that needs figuring out is how to refresh entire screen when clicking on
		// a point outside the current state as this would refresh the region list and the current
		// selection
		top.document.selectedRegion.CoordX.value = CoordX;
		top.document.selectedRegion.CoordY.value = CoordY;
		top.document.selectedRegion.regionSelectorEvent.value = "map";
		top.document.selectedRegion.submit();
		loadmap();
	}
	
	return true;
} 

/*******************************************************************/
var draw_x = new Array();
var draw_y = new Array();
var dist = 0;

function myCanvas_is_clicked() 
{

	var cmd = document.mapserv.cmd.value;
	
	//alert('cmd ==='+cmd);
	
	if (cmd == 'region_search')
	{
		QueryCheck();
	}
	
	if (cmd == 'query_point')
	{
		QueryCheck();
	}

	if (cmd == 'region_select')
	{
		QueryCheck();
	}

	if (cmd == 'zoom_out')
	{
		
		document.mapserv.target="";
		document.mapserv.submit();
	}

	if (cmd == 'measure') 
	{
	
		myCanvas_clicks = myCanvas_clicks + 1;
		draw_x[myCanvas_clicks] = mouse_x - MainMapLeft;
		draw_y[myCanvas_clicks] = mouse_y - MainMapTop;
		
		if (myCanvas_clicks == 1) 
		{
			jg.drawLine(draw_x[myCanvas_clicks] - 5, draw_y[myCanvas_clicks], draw_x[myCanvas_clicks] + 5, draw_y[myCanvas_clicks]);
			jg.drawLine(draw_x[myCanvas_clicks], draw_y[myCanvas_clicks] - 5, draw_x[myCanvas_clicks], draw_y[myCanvas_clicks] + 5);
			jg.paint();
		
		}
		else 
		{
			jg.drawLine(draw_x[myCanvas_clicks] - 5, draw_y[myCanvas_clicks], draw_x[myCanvas_clicks] + 5, draw_y[myCanvas_clicks]);
			jg.drawLine(draw_x[myCanvas_clicks], draw_y[myCanvas_clicks] - 5, draw_x[myCanvas_clicks], draw_y[myCanvas_clicks] + 5);
			jg.drawLine(draw_x[myCanvas_clicks - 1], draw_y[myCanvas_clicks - 1], draw_x[myCanvas_clicks], draw_y[myCanvas_clicks]);
			jg.paint();
			
			dist_x = draw_x[myCanvas_clicks] - draw_x[myCanvas_clicks - 1];
			dist_y = draw_y[myCanvas_clicks] - draw_y[myCanvas_clicks - 1];
			dist = dist + (document.mapserv.MaxX.value - document.mapserv.MinX.value) / document.mapserv.imageWidth.value * Math.sqrt(dist_x * dist_x + dist_y * dist_y);
			document.mapserv.distance.value = Math.round(dist) + ' m';
		}
	}
	
	if (cmd == 'draw_poly') 
	{
		jg.clear();
		myCanvas_clicks = myCanvas_clicks + 1;
		draw_x[myCanvas_clicks - 1] = mouse_x - MainMapLeft;
		draw_y[myCanvas_clicks - 1] = mouse_y - MainMapTop;
		
		jg.setColor("#ff0000");
		jg.drawPolygon(draw_x, draw_y);
		jg.paint();
		
	}
	
	if (cmd == 'draw_line') 
	{
		myCanvas_clicks = myCanvas_clicks + 1;
		draw_x[myCanvas_clicks - 1] = mouse_x - MainMapLeft;
		draw_y[myCanvas_clicks - 1] = mouse_y - MainMapTop;
		
		if (myCanvas_clicks == 1) 
		{
			jg.drawLine(draw_x[myCanvas_clicks -1] - 5, draw_y[myCanvas_clicks - 1], draw_x[myCanvas_clicks - 1] + 5, draw_y[myCanvas_clicks - 1]);
			jg.drawLine(draw_x[myCanvas_clicks - 1], draw_y[myCanvas_clicks - 1] - 5, draw_x[myCanvas_clicks - 1], draw_y[myCanvas_clicks - 1] + 5);
			jg.paint();
		
		}
		else 
		{
			jg.drawLine(draw_x[myCanvas_clicks - 1] - 5, draw_y[myCanvas_clicks - 1], draw_x[myCanvas_clicks - 1] + 5, draw_y[myCanvas_clicks - 1]);
			jg.drawLine(draw_x[myCanvas_clicks - 1], draw_y[myCanvas_clicks - 1] - 5, draw_x[myCanvas_clicks - 1], draw_y[myCanvas_clicks - 1] + 5);
			jg.drawLine(draw_x[myCanvas_clicks - 2], draw_y[myCanvas_clicks - 2], draw_x[myCanvas_clicks - 1], draw_y[myCanvas_clicks - 1]);
			jg.paint();
		}
	}
	
	if (cmd == 'draw_point') 
	{
		jg.clear();
		myCanvas_clicks = myCanvas_clicks + 1;
		draw_x[myCanvas_clicks - 1] = mouse_x - MainMapLeft;
		draw_y[myCanvas_clicks - 1] = mouse_y - MainMapTop;
		
		jg.setColor("#ff0000");
		jg.fillEllipse(mouse_x - MainMapLeft,mouse_y - MainMapTop,10,10);
		jg.paint();
	}
}

/*******************************************************************/
function DL_GetElementLeft(eElement)
{
	var nLeftPos = eElement.offsetLeft;
	var eParElement = eElement.offsetParent;
	while (eParElement != null)
	{
		nLeftPos += eParElement.offsetLeft;
		eParElement = eParElement.offsetParent;
	}
	return nLeftPos;
}

/*******************************************************************/
function DL_GetElementTop(eElement)
{
	var nTopPos = eElement.offsetTop;
	var eParElement = eElement.offsetParent;
	while (eParElement != null)
	{
		nTopPos += eParElement.offsetTop;
		eParElement = eParElement.offsetParent;
	}
	return nTopPos;
}

	
/*******************************************************************/
/*
	Following hotlist handlers are for building and displaying mouse
	over html for items in the mapping interface 
*/
var hotList = new Array();
var hotListId = 0;
var hotListURL = new Array();
var hotListURLId = 0;
function newHotList()
{
	hotList = new Array();
	hotListId = 0;
	hotListURL = new Array();
}
function addHotList(id, laty, longx, html, urlId ,otherHtml)
{
	var la = laty*1;
	var lo = longx*1;
	hotList[hotListId] = new Array(6);
	hotList[hotListId]['id'] = id;
	hotList[hotListId]['lat'] = la;
	hotList[hotListId]['long'] = lo;
	hotList[hotListId]['html'] = html;
	if (urlId || urlId != "")
		hotList[hotListId]['urlId'] = urlId;
	else
		hotList[hotListId]['urlId'] = "";
	if (otherHtml || otherHtml != "")
		hotList[hotListId]['otherHtml'] = otherHtml;
	else
		hotList[hotListId]['otherHtml'] = "";
	hotListId = hotListId + 1;
}
function addHotListURL(id, url, addId, linkText, onClick, target, preText, postText)
{
	var htmlTarget = "_new";
	var htmlLinkPreText = "";
	var htmlLinkText = "Click here for more info";
	var htmlLinkPostText = "";

	hotListURL[id] = new Array(8);
	hotListURL[id]['url'] = url;
	hotListURL[id]['target'] = target;
	// When addId is true then the last parameter on the url should be
	// the name that the id will be attached to.
	hotListURL[id]['addId'] = addId;
	if (target)
		hotListURL[id]['target'] = target;
	else
		hotListURL[id]['target'] = htmlTarget;
	if (linkText)
		hotListURL[id]['linkText'] = linkText;
	else
		hotListURL[id]['linkText'] = htmlLinkText;
	if (preText)
		hotListURL[id]['preText'] = preText;
	else
		hotListURL[id]['preText'] = htmlLinkPreText;
	if (postText)
		hotListURL[id]['postText'] = postText;
	else
		hotListURL[id]['postText'] = htmlLinkPostText;
	hotListURL[id]['onClick'] = onClick;
}
function overHotListItem(x, y, scale)
{
	var i = 0;
	var foundIt = false;
	var buf = scale/50000000;
	if (scale == '-1') buf=1.0;
	var l = 0;
	var r = 0;
	var t = 0;
	var b = 0;
	var linkHtml = "";
	var linkURL = "";
	var lineBreak = "<br/>";
	var urlId = "";
	
	//alert('hotListId = '+hotListId);
	for (i = 0; i < hotListId; i = i + 1)
	{
		// Create bounding box
		l = hotList[i]['long']-buf;  //Left
		r = hotList[i]['long']+buf;  //Right
		t = hotList[i]['lat']+buf;   //Top
		b = hotList[i]['lat']-buf;   //Bottom

		//alert('Scale:'+scale+' Buf:'+buf+' Comparing:'+l+' < '+x+' && '+x+' < '+r+' && '+t+' > '+y+' && '+y+' > '+b+ 
		//      ' Location:'+hotList[i]['html']+':'+hotList[i]['long']+':'+hotList[i]['lat']); 
		// See if mouse is inside bounding box
		if ( l < x && x < r && t > y && y > b) 
		{
 			// Show hotlist html
			//alert('Found :'+hotList[i]['html']);
 			if (!hotList[i]['urlId'] || hotList[i]['urlId'] == '')
	 			overlib(hotList[i]['html']);
 			else
 			{
				// Add the Id to the end of the URL if wanted
				urlId = hotList[i]['urlId'];
				
				// Build the html 
 				if (hotListURL[urlId]['addId'] == true)
 				{
 					linkURL = hotListURL[urlId]['url'];
 					linkURL = linkURL.replace('[ID]',hotList[i]['id']);
 				}
 				else
 					linkURL = hotListURL[urlId]['url']; // Just plain link
 				//linkURL = linkURL.replace(/"/g,'\\"');
 				//linkURL = linkURL.replace(/'/g,"\\'");
 				if (hotListURL[urlId]['onClick'])
 					linkURL = "<a href=\"Javascript:void(0);\" onclick=\"Javascript:"+
										linkURL+"\">"+
	 				          hotListURL[urlId]['linkText']+"</a>";
 				else
					linkURL = "<a href=\""+linkURL+"\" target=\""+
					          hotListURL[urlId]['target']+"\">"+
	 				          hotListURL[urlId]['linkText']+"</a>";
				if (hotListURL[urlId]['preText'])
					linkHtml = hotListURL[urlId]['preText']+" "+linkURL;
				else
					linkHtml = linkURL;
 				if (hotListURL[urlId]['postText'])
 					linkHtml = linkHtml+" "+hotListURL[urlId]['postText'];
 				if (hotList[i]['otherHtml'])
 					linkHtml = linkHtml+" "+lineBreak+hotList[i]['otherHtml'];
 				//alert('Running ['+linkHtml+']');
 				// Display popup
	 			overlib(hotList[i]['html']+lineBreak+linkHtml, STICKY, MOUSEOFF, WRAP);
 			}
			foundIt = true;
			break;	
		}
	}
	//if (!foundIt)
	//	nd(); // Hide overlib 
}

/*******************************************************************/
function formatFloat(pFloat, pDp)
{
	var m = Math.pow(10, pDp);
	return parseInt(pFloat * m, 10) / m;
}

/*******************************************************************/
function browser_zoom(direction) 
{
	var width = MainMapWidth;
	var height = MainMapHeight;
	var offSetX = 0;
	var offSetY = 0;
	var imgStyle = document.getElementsByName('mainmap')[0].style;
	var scale = document.mapserv.scale.value;
	var minscale = document.mapserv.minscale.value;
	var retVal = false;
	var multiplier = 2; // Can only be 2 for now till code is smarter
	
	if (direction=="+") 
	{
		if (Math.round(scale) > minscale)
		{
			// Then allow zooming in
			width = MainMapWidth * multiplier;
			height = MainMapHeight * multiplier;
			offSetX = MainMapLeft - (MainMapWidth / multiplier);
			offSetY = MainMapTop - (MainMapHeight / multiplier);
			imgStyle.width = width+'px';
			imgStyle.height = height+'px';
			imgStyle.left = offSetX+'px';
			imgStyle.top = offSetY+'px';
			retVal = true;
		}
		else
			alert('You may not zoom in any further');
	}
	if (direction=="-") 
	{
		width = MainMapWidth / multiplier;
		height = MainMapHeight / multiplier;
		offSetX = MainMapLeft + (MainMapWidth / (multiplier*2));
		offSetY = MainMapTop + (MainMapHeight / (multiplier*2));
		imgStyle.width = width+'px';
		imgStyle.height = height+'px';
		imgStyle.left = offSetX+'px';
		imgStyle.top = offSetY+'px';
		retVal = true;
	}
	return retVal;
}

/*******************************************************************/
/* Initialization code. 
 * If you use your own event management code, change it as required. */
if (window.addEventListener)
        /** DOMMouseScroll is for mozilla. */
        window.addEventListener('DOMMouseScroll', mouse_wheel, false);
/** IE/Opera. */
window.onmousewheel = document.onmousewheel = mouse_wheel;

/*******************************************************************/
/* This is high-level function. It must react to delta being more/less than zero. */
function mouse_wheel_handle(delta) 
{
	var direction = "";
	var cmd = ""
	
	//alert('Received a delta of '+delta);
	if (!isMapLoaded())
	{
		if (delta < 0)
		{
			cmd = "wheel_zoom_out";
			direction = "-";
		}
		else
		{
			cmd = "wheel_zoom_rect";
			direction = "+";
		}
	
		if (browser_zoom(direction))
		{
			ChangeFunctionality(cmd);
			loadingMap(true);
			// It would be nice to have to wheel mouse zoom on the point you are currently over
			// But the useability is too hard for the user.  So... Use the image centre instead
			mouse_x = MainMapWidth / 2;
			mouse_y = MainMapHeight / 2;
			mouseUpZoom();
		}
	}

}

/*******************************************************************/
/** Event handler for mouse wheel event. */
function mouse_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)
		mouse_wheel_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;
}

/*******************************************************************/
function mouseMove(e)
{
	var cmd = document.mapserv.cmd.value;
	var t = 0; // Following 4 vars are for moving image and cropping
	var r = 0;
	var b = 0;
	var l = 0;
	var scale = document.mapserv.scale.value;
	var CoordX = 0;
	var CoordY = 0;
	var scale = document.mapserv.scale.value;
	var minscale = document.mapserv.minscale.value;

	if ( (ns4) || (ns6) ) {mouse_x=e.pageX; mouse_y=e.pageY;}
	if (ie4) {mouse_x=event.x; mouse_y=event.y;}
	if (ie5) {mouse_x=eval('event.x+self.'+docRoot+'.scrollLeft') - 1; mouse_y=eval('event.y+self.'+docRoot+'.scrollTop');}
	//alert('mousex' + mouse_x);
	
	
	// Adjust div size rather than in the css
	document.getElementById(myCanvasSelect).style.height = MainMapHeight;
	document.getElementById(myCanvasSelect).style.width = MainMapWidth;
	
	
	if ((MainMapLeft <= mouse_x) && (mouse_x <= MainMapLeft + MainMapWidth) && (MainMapTop <= mouse_y) && (mouse_y <= MainMapTop + MainMapHeight))
	{
		CoordX = parseFloat(document.mapserv.extentMinX.value) + ((document.mapserv.extentMaxX.value - document.mapserv.extentMinX.value) / document.mapserv.imageWidth.value) * (mouse_x - MainMapLeft);
		//CoordX = Math.round(100*CoordX) / 100;
		CoordY = parseFloat(document.mapserv.extentMinY.value) + ((document.mapserv.extentMaxY.value - document.mapserv.extentMinY.value) / document.mapserv.imageHeight.value) * (document.mapserv.imageHeight.value - mouse_y + MainMapTop);
		//CoordY = Math.round(100*CoordY) / 100;
		document.mapserv.coordx.value = CoordX;
		document.mapserv.coordy.value = CoordY;

		//Display the lat and long to the user
		if (top.muiMap.document.mapserv)
			top.writeLatLong(CoordY, CoordX);

		// following commented to use imagemap
		if (scale == '-1') scale = '157491144';  
		//alert('mouse x' + mouse_x);

		overHotListItem(CoordX, CoordY, scale); // Show any html popups

		//var buf = 1 + scale/50000000;
		//if (scale == '-1') buf=5.0;

		//if ( CoordX > (126.9-buf) && CoordX < (126.9 + buf) && CoordY > (37.5 - buf) && CoordY < (37.5 + buf) ) 
		//	overlib('<b>Jeremy Cook</b></BR>Counsellor (Agriculture)</BR><img src=images/counsellors/jeremy_cook.jpg /></BR>quick dial: 11377</BR>fax: 82 2 722 6491</BR>phone(w): 82 2 2003 0188</BR>phone(h): 82 2 749 8441', CAPTION, 'Seoul - South Korea'); return false;
		//else 
		//	nd();

		//document.getElementById("cursx").style.visibility = 'visible';
		//document.getElementById("cursy").style.visibility = 'visible';
		//document.getElementById("cursx").style.left = mouse_x + 1;
		//document.getElementById("cursy").style.top = mouse_y - 1;

		// only small cursor
		document.getElementById("cursx").style.visibility = 'hidden';
		document.getElementById("cursy").style.visibility = 'hidden';
		document.getElementById("cursx").style.left = mouse_x + 0;
		document.getElementById("cursy").style.top = mouse_y - 0;

				
		if (cmd == 'measure')
		{
			document.getElementById(myCanvasSelect).style.visibility = 'visible';
			document.getElementById(myCanvasSelect).style.cursor = 'crosshair';
		}
		else if (cmd == 'region_search')
		{
			document.getElementById("cursx").style.visibility = 'hidden';
			document.getElementById("cursy").style.visibility = 'hidden';
			document.getElementById(myCanvasSelect).style.visibility = 'visible';
			document.getElementById(myCanvasSelect).style.cursor = 'default';
			
		}
		else if (cmd == 'region_select')
		{
			document.getElementById("cursx").style.visibility = 'hidden';
			document.getElementById("cursy").style.visibility = 'hidden';
			document.getElementById(myCanvasSelect).style.visibility = 'visible';
			document.getElementById(myCanvasSelect).style.cursor = 'pointer';
		}
		else if (cmd == 'zoom_out')
		{
			document.getElementById(myCanvasSelect).style.visibility = 'visible';
			document.getElementById(myCanvasSelect).style.cursor = 'crosshair';

			document.onmousedown = mouseDownZoom;

			if (myCanvas_clicks == 1) 
			{

				zoom_rect_x[2] = mouse_x + 1;
				zoom_rect_y[2] = mouse_y - 1;

				document.getElementById("zoomrect").style.top = Math.min(zoom_rect_y[1],zoom_rect_y[2]);
				document.getElementById("zoomrect").style.left = Math.min(zoom_rect_x[1],zoom_rect_x[2]);
				if (ie5) 
				{
					document.getElementById("zoomrect").style.width = Math.abs(zoom_rect_x[2] - zoom_rect_x[1]) + 1;
					document.getElementById("zoomrect").style.height = Math.abs(zoom_rect_y[2] - zoom_rect_y[1]) + 1;
				}
				else 
				{ // ns6
					document.getElementById("zoomrect").style.width = Math.abs(zoom_rect_x[2] - zoom_rect_x[1]) - 1;
					document.getElementById("zoomrect").style.height = Math.abs(zoom_rect_y[2] - zoom_rect_y[1]) - 1;
				}
				document.getElementById("zoomrect").style.visibility = 'visible';
			}

			document.onmouseup = mouseUpZoom;
		}
		else if (cmd == 'zoom_rect') 
		{
			//if (scale > minscale)
			//{
				document.getElementById(myCanvasSelect).style.visibility = 'visible';
				document.getElementById(myCanvasSelect).style.cursor = 'crosshair';
	
				//
				// Entry Points (not used yet)
				//
	
				// if (!zoom_rect_x[1]) zoom_rect_x[1] = mouse_x + 1;
				// if (!zoom_rect_y[1]) zoom_rect_y[1] = mouse_y - 1;
	
				document.onmousedown = mouseDownZoom;
	
				if (myCanvas_clicks == 1) 
				{
	
					zoom_rect_x[2] = mouse_x + 1;
					zoom_rect_y[2] = mouse_y - 1;
	
					document.getElementById("zoomrect").style.top = Math.min(zoom_rect_y[1],zoom_rect_y[2]);
					document.getElementById("zoomrect").style.left = Math.min(zoom_rect_x[1],zoom_rect_x[2]);
					if (ie5) 
					{
						document.getElementById("zoomrect").style.width = Math.abs(zoom_rect_x[2] - zoom_rect_x[1]) + 1;
						document.getElementById("zoomrect").style.height = Math.abs(zoom_rect_y[2] - zoom_rect_y[1]) + 1;
					}
					else 
					{ // ns6
						document.getElementById("zoomrect").style.width = Math.abs(zoom_rect_x[2] - zoom_rect_x[1]) - 1;
						document.getElementById("zoomrect").style.height = Math.abs(zoom_rect_y[2] - zoom_rect_y[1]) - 1;
					}
					document.getElementById("zoomrect").style.visibility = 'visible';
				}
				document.onmouseup = mouseUpZoom;
					
			//}
		}
		else if (cmd == 'draw_poly')
		{
			document.getElementById(myCanvasSelect).style.visibility = 'visible';
			document.getElementById(myCanvasSelect).style.cursor = 'crosshair';
		}
		else if (cmd == 'draw_line')
		{
			document.getElementById(myCanvasSelect).style.visibility = 'visible';
			document.getElementById(myCanvasSelect).style.cursor = 'crosshair';
		}
		else if (cmd == 'query_point')
		{
			document.getElementById(myCanvasSelect).style.visibility = 'visible';
			document.getElementById(myCanvasSelect).style.cursor = 'move';
		}
		else if (cmd == 'draw_point')
		{
			document.getElementById(myCanvasSelect).style.visibility = 'visible';
			document.getElementById(myCanvasSelect).style.cursor = 'crosshair';
		}
		else if (cmd == 'move')
		{
			if (ns6)
			{
				document.getElementById("cursx").style.visibility = 'hidden';
				document.getElementById("cursy").style.visibility = 'hidden';
				document.getElementById(myCanvasSelect).style.visibility = 'visible';
				document.getElementById(myCanvasSelect).style.cursor = 'move';
			}
			else 
			{
				document.getElementById("cursx").style.visibility = 'hidden';
				document.getElementById("cursy").style.visibility = 'hidden';
				document.getElementById(myCanvasSelect).style.visibility = 'hidden';
				document.getElementsByName('mainmap')[0].style.cursor = 'move';
			}
			document.onmousedown = mouseDownMove;

			if (myCanvas_clicks >= 1)
			{
				myCanvas_clicks = 1;

				document.getElementsByName('mainmap')[0].style.left = mouse_x - MouseDownClickLeft + MainMapLeft;
				document.getElementsByName('mainmap')[0].style.top = mouse_y - MouseDownClickTop + MainMapTop;
	
				// Following code is for cropping in divs.  Currently not working
				// when the mouse is moved down or right.
				//t = MouseDownClickTop - mouse_y;
				//r = MouseDownClickLeft - mouse_x + MainMapWidth;
				//b = MouseDownClickTop - mouse_y + MainMapHeight;
				//l = MouseDownClickLeft - mouse_x;
				//document.getElementsByName('mainmap')[0].style.clip = 'rect(' + t + ' ' +  r + ' ' + b + ' ' + l + ')'; //oben, rechts, unten, links
			}
			document.onmouseup = mouseUpMove;
		}
		else
		{
			document.getElementsByName('mainmap')[0].style.cursor = 'crosshair';
			document.getElementById(myCanvasSelect).style.cursor = 'crosshair';

			document.onmousedown = MouseDownDefault;
			document.onmouseup = MouseUpDefault;

			if (myCanvas_clicks == 1) 
				myCanvas_clear();

			document.getElementById(myCanvasSelect).style.visibility = 'hidden';
		}
	}
	else
	{
		if ((myCanvas_clicks >= 1) && (cmd == 'move'))
		{
			myCanvas_clicks = 2;

			MainMapMovedLeft = parseInt(document.getElementsByName('mainmap')[0].style.left);
			MainMapMovedTop = parseInt(document.getElementsByName('mainmap')[0].style.top);

			document.onmouseup = mouseUpMove;
		}
		else if ((myCanvas_clicks == 1) && (cmd == 'zoom_rect')) 
			document.onmouseup = mouseUpZoom;
		else 
			document.onmouseup = MouseUpDefault;

		document.onmousedown = MouseDownDefault;

		//document.getElementById("cursx").style.visibility = 'hidden';
		//document.getElementById("cursy").style.visibility = 'hidden';
	}
}

/*******************************************************************/
var zoom_rect_x = new Array();
var zoom_rect_y = new Array();
var myCanvas_clicks = 0;
var mouse_x = 0;
var mouse_y = 0;

function mouseDownZoom(e) 
{
	myCanvas_clear();
	myCanvas_clicks = 1;
	zoom_rect_x[1] = mouse_x + 1;
	zoom_rect_y[1] = mouse_y - 1;
	jg.drawLine(zoom_rect_x[1] - 5 - MainMapLeft, zoom_rect_y[1] - MainMapTop, zoom_rect_x[1] + 5 - MainMapLeft, zoom_rect_y[1] - MainMapTop);
	jg.drawLine(zoom_rect_x[1] - MainMapLeft, zoom_rect_y[1] - 5 - MainMapTop, zoom_rect_x[1] - MainMapLeft, zoom_rect_y[1] + 5 - MainMapTop);
	jg.paint();
}

/*******************************************************************/
function mouseUpZoom() 
{
	var cmd = document.mapserv.cmd.value;
	var scale = document.mapserv.scale.value;
	var minscale = document.mapserv.minscale.value;

	myCanvas_clicks = 2;
	
	if (!zoom_rect_x[2]) zoom_rect_x[2] = mouse_x + 1;
	if (!zoom_rect_y[2]) zoom_rect_y[2] = mouse_y - 1;
	
	if (!zoom_rect_x[1]) zoom_rect_x[1] = mouse_x + 1;
	if (!zoom_rect_y[1]) zoom_rect_y[1] = mouse_y - 1;
	
	jg.drawLine(zoom_rect_x[2] - 5 - MainMapLeft, zoom_rect_y[2] - MainMapTop, zoom_rect_x[2] + 5 - MainMapLeft, zoom_rect_y[2] - MainMapTop);
	jg.drawLine(zoom_rect_x[2] - MainMapLeft, zoom_rect_y[2] - 5 - MainMapTop, zoom_rect_x[2] - MainMapLeft, zoom_rect_y[2] + 5 - MainMapTop);
	jg.paint();
	
	if ((zoom_rect_x[2] != zoom_rect_x[1]) && (zoom_rect_y[2] != zoom_rect_y[1])) 
	{
		document.mapserv.zoom_rect_minx.value = Math.min(zoom_rect_x[1], zoom_rect_x[2]) - MainMapLeft;
		document.mapserv.zoom_rect_miny.value = Math.min(zoom_rect_y[1], zoom_rect_y[2]) - MainMapTop;
		document.mapserv.zoom_rect_maxx.value = Math.max(zoom_rect_x[1], zoom_rect_x[2]) - MainMapLeft;
		document.mapserv.zoom_rect_maxy.value = Math.max(zoom_rect_y[1], zoom_rect_y[2]) - MainMapTop;
	}
	else 
	{
		if (zoom_rect_x[2] != zoom_rect_x[1]) 
		{
			document.mapserv.zoom_x.value = (Math.min(zoom_rect_x[1], zoom_rect_x[2]) + Math.abs(zoom_rect_x[2] - zoom_rect_x[1]) / 2) - MainMapLeft;
			document.mapserv.zoom_y.value = zoom_rect_y[1] - MainMapTop;
		}
		else if (zoom_rect_y[2] != zoom_rect_y[1]) 
		{
			document.mapserv.zoom_x.value = zoom_rect_x[1] - MainMapLeft;
			document.mapserv.zoom_y.value = (Math.min(zoom_rect_y[1], zoom_rect_y[2]) + Math.abs(zoom_rect_y[2] - zoom_rect_y[1]) / 2) - MainMapTop;
		}
		else 
		{
			//alert('Setting to '+zoom_rect_x[1] - MainMapLeft+' x '+zoom_rect_y[1] - MainMapTop);
			document.mapserv.zoom_x.value = zoom_rect_x[1] - MainMapLeft;
			document.mapserv.zoom_y.value = zoom_rect_y[1] - MainMapTop;
		}
	}
	
	if (Math.round(scale) < Math.round(minscale) && cmd == 'zoom_rect')
	{
		alert('You may not zoom in any further');	
		document.getElementById("zoomrect").style.visibility = 'hidden';
		jg.clear();
		
	}
	else
	{
		loadmap();
		document.mapserv.target="";
		document.mapserv.submit();
	}
	
	
}

/*******************************************************************/
var MouseDownClickLeft = 0;
var MouseDownClickTop = 0;

function mouseDownMove() 
{
	myCanvas_clicks = 1;
	MouseDownClickLeft = mouse_x;
	MouseDownClickTop = mouse_y;
}

/*******************************************************************/
function mouseUpMove()
{
	if (myCanvas_clicks == 1) 
	{
		document.mapserv.move_x.value = (MainMapWidth / 2) + (MouseDownClickLeft - mouse_x);
		document.mapserv.move_y.value = (MainMapHeight / 2) + (MouseDownClickTop - mouse_y);
	}
	else if (myCanvas_clicks == 2) 
	{
		document.mapserv.move_x.value = (MainMapWidth / 2) - MainMapMovedLeft + MainMapLeft;
		document.mapserv.move_y.value = (MainMapHeight / 2) - MainMapMovedTop + MainMapTop;
	}

	myCanvas_clear();

	loadmap();

	document.mapserv.target="";
	document.mapserv.submit();
}

/*******************************************************************/
var clickimg = 0;
function is_clicked() 
{
	alert('is_clicked');
	clickimg = 1;
	return;
}


//if (ie4 || ie5) 
//{
//	var LoadMapImg = new Array();
//	LoadMapImg[0] = new Image();
//	LoadMapImg[0].src = "images/LoadMap-1.gif";
//	LoadMapImg[1] = new Image();
//	LoadMapImg[1].src = "images/LoadMap-1.gif";
//	LoadMapImg[2] = new Image();
//	LoadMapImg[2].src = "images/LoadMap-2.gif";
//	LoadMapImg[3] = new Image();
//	LoadMapImg[3].src = "images/LoadMap-3.gif";
//	LoadMapImg[4] = new Image();
//	LoadMapImg[4].src = "images/LoadMap-4.gif";
//	LoadMapImg[5] = new Image();
//	LoadMapImg[5].src = "images/LoadMap-5.gif";
//	LoadMapImg[6] = new Image();
//	LoadMapImg[6].src = "images/LoadMap-6.gif";
//	LoadMapImg[7] = new Image();
//	LoadMapImg[7].src = "images/LoadMap-7.gif";
//	var LoadMapNr = 0;
//}

var	muiLoadingMap = true;

/*******************************************************************/
function loadingMap(loadStatus)
{
	muiLoadingMap = loadStatus;
}

/*******************************************************************/
function isMapLoaded()
{
	return muiLoadingMap;
}

/*******************************************************************/
function loadmap() 
{
	//document.getElementById("headline-img").style.visibility = 'hidden';
	document.getElementById("loadmap-img").style.visibility = 'visible';
	muiLoadingMap = true;
	top.deactivateFields();
	
	//if (ie4 || ie5)
	//{
	//	LoadMapNr = LoadMapNr + 1;
	//	document.getElementById("loadmap-img").getElementsByTagName('img')[0].src = LoadMapImg[LoadMapNr].src;
	//	if (LoadMapNr == 7) 
	//		LoadMapNr = 0;
	//	if (!popupWin) 
	//		setTimeout("loadmap()", 75);
	//	else
	//		document.getElementById("loadmap-img").getElementsByTagName('img')[0].src = LoadMapImg[0].src;
	//}
}

/*******************************************************************/
// Given a width and height set the form values so that the map 
// redraws next time it is refreshed. Take 1 off for border
function setMuiIframeWidthHeight(width, height)
{
	document.mapserv.mapFrameHeight.value = height;
	document.mapserv.mapFrameWidth.value = width;
}


function displaysel(obj1)
{
   // document.getElementById("map_refresh_help").style.visibility="hidden";
    document.getElementById("region_select").style.visibility="hidden";
    document.getElementById("data_select").style.visibility="hidden";
    document.getElementById("legend").style.visibility="hidden";
    var obje1=document.getElementById(obj1);
    obje1.style.visibility="visible";
}


function closesel()
{
    //document.getElementById("map_refresh_help").style.visibility="hidden";
    document.getElementById("region_select").style.visibility="hidden";
    document.getElementById("data_select").style.visibility="hidden";
    document.getElementById("legend").style.visibility="hidden";
    //var obje1=document.getElementById(obj1);
    //obje1.style.visibility="visible";
}




