// Mouse Event Functions
// mouse events for the Drag object and Scroll2 object
// 19991007

// Copyright (C) 1999 Dan Steinman
// Distributed under the terms of the GNU Library General Public License
// Available at http://www.dansteinman.com/dynapi/

// Modification has been make by Willa Zhu

var iWidth = 0; 	// image width
var iHeight = 0;	// image height
var hspc = 0; 		// horizontal image offset
var vspc = 0; 		// vertical image offset
var ovBoxSize = 1; 	// box line width
var mapName = "mapImg"; // Map Name in the HTML Page
var drawing = false;
var mouseIsDown = false;

var currlon, currlat;
		
// Global vars to save mouse position
var mouseX=0;
var mouseY=0;
var x1=0;
var y1=0;
var x2=0;
var y2=0;
var zleft=0;
var zright=0;
var ztop=0;
var zbottom=0;
var selected_leftLon, selected_rightLon, selected_topLat, selected_botLat;

function resetGeo() {
	DynMouseDown(toLonStr(leftLon),toLatStr(topLat));
	DynMouseMove(toLonStr(rightLon),toLatStr(botLat));
	hideLayer("boxTop");
	hideLayer("boxLeft");
	hideLayer("boxRight");
	hideLayer("boxBottom");
}

function Format(v,w,p)
{
  var str,txt
  var i,j
  var dot

  str = v.toString()
  dot = str.indexOf(".")
  if (dot >= 0)
  {
    if (dot + p < str.length)
    {
      str = str.slice(0,dot+p+1)
    }
  }
  j = w - str.length
  if (j <= 0) { return str }
  txt = ""
  while (j != 0) 
  {
    txt = txt + " "
    j--
  }
  txt = txt + str
  return txt
}


function myFormat(num) {
  a = Math.round(parseFloat(num)*100);
  str = a.toString();
  len=str.length;
  str1 = str.slice(0,(len-2));
  str2 = str.slice((len-2),len);
  finalstr = str1 + '.' + str2;
  return(finalstr);
}

function x2lon(x) {
	var c=(rightLon - leftLon)/(rightMargine-leftMargine);
	lon = parseFloat(leftLon + c*(x-leftMargine));
	return(lon);
}

function y2lat(y) {
	var c=(botLat - topLat)/(botMargine-topMargine);
	lat = parseFloat(topLat + c*(y-topMargine));
	return(lat);
}

function toLonStr(lon) {
	hemis = 'E';
	if(lon > 180) {
		lon = 360 - lon;
		hemis = 'W';
	}
	if(lon < 0) {
	   lon = lon * (-1);
	   hemis = 'W';
 	}
        
	lonstr = myFormat(lon) + ' ' + hemis;
	return(lonstr)
}

function toLatStr(lat) {
	hemis = 'N';
	if(lat < 0) {
		lat = (-1) * lat;
		hemis = 'S';
	}
	latstr = myFormat(lat) + ' ' + hemis;
	return(latstr);
}

function StrtoLon(lonstr) {
    var arr = lonstr.split(' ');
	lon = arr[0];
	if(arr[1] == 'W') {
//		lon = 360 - lon;
	  lon = (-1)*lon;
	}
	return(lon)
}

function StrtoLat(latstr) {
	var arr = latstr.split(' ');
	lat = arr[0];
	if(arr[1] == 'S') {
		lat = (-1) * lat;
	}	
	return(lat);
}

function initMouseEvents() {
	document.onmousedown = mouseDown
	document.onmousemove = mouseMove
	document.onmouseup = mouseUp
	if (is.ns) document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP)
	resetGeo();
}

function mouseDown(e) {
//	if ((is.ns && e.which!=1) || (is.ie && event.button!=1)) return true
	var x = (is.ns)? e.pageX : event.x+document.body.scrollLeft
	var y = (is.ns)? e.pageY : event.y+document.body.scrollTop
 	var obj = null;
	
   	if (is.ns) obj = e.target;
	else obj = event.srcElement;
	if (obj == document[mapName]) {
	   mouseIsDown = true;
	   drawing=false;
	   getImageXY(e);
	   if ((mouseX>rightMargine) || (mouseY>botMargine) || (mouseX<=leftMargine) ||(mouseY<=topMargine)) {	  
	   }
	   else {		
	     startDrawBox(e);	
		 //xpxl= mouseX-leftMargine-1;
	     //ypxl = mouseY-topMargine-1;
	     //if (is.ns && e.target!=document) routeEvent(e)
	     //if (Scroll && ScrollTestActive()) return false
	     //else if (Drag && drag.mouseDown(x,y)) return false
	     //else return DynMouseDown(mouseX,mouseY)
		 currlon=x2lon(mouseX);
		 currlat=y2lat(mouseY);
		 
		 selected_leftLon=currlon;
		 selected_topLat =currlat;
		 DynMouseDown(toLonStr(currlon),toLatStr(currlat));
	   }
	   return false;  //important to return flase for NS
	}
	return true;
}

// start draw box displayed
function startDrawBox(e) {
	getImageXY(e);			
	// keep it within the MapImage
	if ((mouseX<iWidth) && (mouseY<iHeight)) {
		if (drawing) {
			stopDrawBox(e);
		} else {
			x1=mouseX+hspc;
			y1=mouseY+vspc;
			x2=x1+1;
			y2=y1+1;
			zleft=x1;
			ztop=y1;
			zbottom=y1;
			zright=x1;

			boxIt(x1,y1,x2,y2);
			
			drawing=true;
		}
	}
	
	return false;
}

// stop box display...
function stopDrawBox(e) {
	drawing=false;

	hideLayer("boxTop");
	hideLayer("boxLeft");
	hideLayer("boxRight");
	hideLayer("boxBottom");

	//return true;
	return false;
}
function mouseMove(e) {
	var x = (is.ns)? e.pageX : event.x+document.body.scrollLeft
	var y = (is.ns)? e.pageY : event.y+document.body.scrollTop
	
	var obj = null;
	if (is.ns && e.target!=document) routeEvent(e)
    if (is.ns) document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP)
	if(mouseIsDown == false) {
	  getImageXY(e);
	  return true;
	}
	
	if (is.ns) obj = e.target;
	else obj = event.srcElement;
	if (obj == document[mapName]) {
	  getImageXY(e);
//	if ((mouseX>iWidth) || (mouseY>iHeight) || (mouseX<=0) ||(mouseY<=0)) {
	  if ((mouseX>rightMargine) || (mouseY>botMargine) || (mouseX<=leftMargine) ||(mouseY<=topMargine)) {
		drawing=false;
	//	return false; //true=allow other elements on the page use that event
	  } else {
		if(drawing == false && mouseIsDown) drawing = true;		
		if (drawing) {
		  x2=mouseX+hspc;
		  y2=mouseY+vspc;
		  currlon=x2lon(mouseX);
		  currlat=y2lat(mouseY);
		  if(x1 <= hspc || y1 <= vspc ) {
			x1=x2-1; 
		    y1=y2-1;
			selected_leftLon=currlon;
			selected_topLat=currlat;
			DynMouseDown(toLonStr(currlon),toLatStr(currlat));
		  }
		  setClip();
		  DynMouseMove(toLonStr(currlon),toLatStr(currlat));
		}
//		return false;
	  }
    }
//	if (Scroll && ScrollTestActive()) return false
//	else if (Drag && drag.mouseMove(x,y)) return false
//	else return DynMouseMove(x,y)
	return false;
}

function mouseUp(e) {
	var x = (is.ns)? e.pageX : event.x+document.body.scrollLeft
	var y = (is.ns)? e.pageY : event.y+document.body.scrollTop

	if (is.ns) obj = e.target;
	else obj = event.srcElement;
	//if(obj == document[mapName]) {
	//For some reason that for NS when mouse started at South-East corner
	//moving to/ending at North-West corner, the obj != document[mapName]
	if (mouseIsDown) {
	  drawing=false;
	  mouseIsDown = false; 
	  if(parseFloat(currlon) < parseFloat(selected_leftLon)) {
	      	selected_rightLon = selected_leftLon;
	      	selected_leftLon = currlon;
      }
	  else selected_rightLon = currlon;
	  DynMouseUp(currlat,selected_topLat);
	  if(parseFloat(currlat) > parseFloat(selected_topLat)) {
	    	selected_botLat = selected_topLat;
	    	selected_topLat = currlat;
	  }
	  else selected_botLat = currlat;
	  DynMouseDown(toLonStr(selected_leftLon),toLatStr(selected_topLat));
	  DynMouseMove(toLonStr(selected_rightLon),toLatStr(selected_botLat));
	}
	//if (is.ns && e.target!=document) routeEvent(e)
	//if (Drag && drag.mouseUp(x,y)) return false
	//else return DynMouseMove(lon,lat)
	return false;
}

// overwrite these functions in your html source to do other mouse handling
function DynMouseDown(x,y) {return true}
function DynMouseMove(x,y) {return true}
function DynMouseUp(x,y) {return true}

// include drag.js and/or scroll2.js after this file to overwrite these variables
Drag = null
Scroll = null

// get the layer object called "name"
function getLayer(name) {
	if (is.ns4) {
		return(document.layers[name]);
	} else if (is.ie4) {
		layer = eval('document.all.' + name + '.style');
		return(layer);
	} else if (is.v >= 5){
		var theObj = document.getElementById(name);
		return theObj.style;
	} else {
		return(null);
	}
}

// check if layer is visible
function isVisible(name) {
	var layer = getLayer(name);
	if (is.ns && layer.visibility == "show")
		return(true);
	if (is.ie && layer.visibility == "visible")
 		return(true);
	return(false);
}

// move layer to x,y
function moveLayer(name, x, y) {
	var layer = getLayer(name);
	if (is.ns4) {
		layer.moveTo(x, y);
	}else {
		layer.left = x + "px";
 		layer.top  = y + "px";
	}
}

// toggle layer to invisible
function hideLayer(name) {
	var layer = getLayer(name);
	if (is.ns4)
		layer.visibility = "hide";
	else
		layer.visibility = "hidden";
}

// toggle layer to visible
function showLayer(name) {
	var layer = getLayer(name);
	if (is.ns4)
		layer.visibility = "show";
	else
		layer.visibility = "visible";
}

// clip layer display to clipleft, cliptip, clipright, clipbottom
function clipLayer(name, clipleft, cliptop, clipright, clipbottom) {
	var layer = getLayer(name);
	if (is.ns4) {
		layer.clip.left   = clipleft;
		layer.clip.top    = cliptop;
		layer.clip.right  = clipright;
		layer.clip.bottom = clipbottom;
	} else {
		var newWidth = clipright - clipleft;
		var newHeight = clipbottom - cliptop;
		layer.height = newHeight + "px";
		layer.width	= newWidth + "px";
		layer.top	= cliptop + "px";
		layer.left	= clipleft + "px";
	}
}

// shown the box
function boxIt(theLeft,theTop,theRight,theBottom) {
	clipLayer("boxTop",theLeft,theTop,theRight,theTop+ovBoxSize);
	clipLayer("boxLeft",theLeft,theTop,theLeft+ovBoxSize,theBottom);
	clipLayer("boxRight",theRight-ovBoxSize,theTop,theRight,theBottom);
	clipLayer("boxBottom",theLeft,theBottom-ovBoxSize,theRight,theBottom);
	showLayer("boxTop");
	showLayer("boxLeft");
	showLayer("boxRight");
	showLayer("boxBottom");
}

// get cursor location
function getImageXY(e) {
	iWidth = document[mapName].width;
	iHeight = document[mapName].height;
	//iWidth = rightMargine - leftMargine;
	//iHeight = botMargine - topMargine;

	if (is.ns4) {
		hspc = document[mapName].x;
		vspc = document[mapName].y;
	} else {
		hspc = getOffsetX(mapName);
		vspc = getOffsetY(mapName);
	}

	if (is.ns) {
		mouseX=e.pageX;
		mouseY=e.pageY;
	} else {
		if(is.ie6) {
			mouseX = event.clientX + document.documentElement.scrollLeft;
		    mouseY = event.clientY + document.documentElement.scrollTop;
		}
		else {
			mouseX=event.clientX + document.body.scrollLeft;
			mouseY=event.clientY + document.body.scrollTop;
		}
	}
	// subtract offsets from page left and top
	mouseX = mouseX-hspc;
	mouseY = mouseY-vspc;
//		  DynMouseMove(mouseX,mouseY);
	//return true;
}

// get the coords at mouse position
function getMouse(e) {
	if(mouseIsDown == false) return;
	
	getImageXY(e);
//	if ((mouseX>iWidth) || (mouseY>iHeight) || (mouseX<=0) ||(mouseY<=0)) {
	if ((mouseX>rightMargine) || (mouseY>botMargine) || (mouseX<=leftMargine) ||(mouseY<=topMargine)) {

		return true;
	} else if (drawing) {
		x2=mouseX+hspc;
		y2=mouseY+vspc;
		setClip();
		return false;
	}
}

// clip box layer to mouse coords
function setClip() {	
	var tempX=x1;
	var tempY=y1;
	if (x1>x2) {
		zright=x1;
		zleft=x2;
	} else {
		zleft=x1;
		zright=x2;
	}
	if (y1>y2) {
		zbottom=y1;
		ztop=y2;
	} else {
		ztop=y1;
		zbottom=y2;
	}

	if ((x1 != x2) && (y1 != y2)) {
		boxIt(zleft,ztop,zright,zbottom);
	}
}

// get X offset of the map in the page (IE)
function getOffsetX(imgElem) {
	xPos = document[imgElem].offsetLeft;
	tempEl = document[imgElem].offsetParent;
  	while (tempEl != null) {
  		xPos += tempEl.offsetLeft;
  		tempEl = tempEl.offsetParent;
  	}
	return xPos;
}

// get Y offset of the map in the page (IE)
function getOffsetY(imgElem) {
	yPos = document[imgElem].offsetTop;
	tempEl = document[imgElem].offsetParent;
	while (tempEl != null) {
  		yPos += tempEl.offsetTop;
  		tempEl = tempEl.offsetParent;
  	}
	return yPos;
}
