var BoxColor = "#FF0000";	// color of box

// Global vars
var iWidth = 400;	// image width (default)
var iHeight = 300;	// image height (default)
var hspc = 0;		// horizontal image offset
var vspc = 0;		// vertical image offset
var ovBoxSize = 3;	// Zoombox line width;
var zbMapImage = "MapImage"; // default

var MODE_BOX = 1;
var currMode = MODE_BOX;

var zooming = false;
var operationdone = true;

var xMousePos = 0; // Horizontal position of the mouse on the screen
var yMousePos = 0; // Vertical position of the mouse on the screen


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 escala=0;

// Panning global vars
var HACERPAN = false;
var IniPosX = 0;
var IniPosY = 0;

// Identifying global vars
var IDENTIFY = false;


// Global vars for browser type and version
var isNav = (navigator.appName.indexOf("Netscape")>=0);
var isNav4 = false;
var isIE4 = false;
var is5up = false;
if (isNav) {
	if (parseFloat(navigator.appVersion)<5) {
		isNav4=true;
	} else {
		is5up = true;
	}
} else {
	isIE4=true;
	if (navigator.appVersion.indexOf("MSIE")>0) {
		isIE4 = false;
		is5up = true;
	}
}


/****************************************************************************************
Main initialization
****************************************************************************************/

function initData(MapImageName)
{
	zbMapImage = MapImageName;
	
	iWidth = document.getElementById(zbMapImage).offsetWidth;
	iHeight = document.getElementById(zbMapImage).offsetHeight;

	// zoom/selection box
	content = '<img name="zoomImageTop" src="pixel.gif" width=1 height=1>';
	createLayer("zoomBoxTop",50,0,iWidth,iHeight,false,content);
	content = '<img name="zoomImageLeft" src="pixel.gif" width=1 height=1>';
	createLayer("zoomBoxLeft",50,0,iWidth,iHeight,false,content);
	content = '<img name="zoomImageRight" src="pixel.gif" width=1 height=1>';
	createLayer("zoomBoxRight",50,0,iWidth,iHeight,false,content);
	content = '<img name="zoomImageBottom" src="pixel.gif" width=1 height=1>';
	createLayer("zoomBoxBottom",50,0,iWidth,iHeight,false,content);

	// set zoom box color
	setLayerBackgroundColor("zoomBoxTop", BoxColor);
	setLayerBackgroundColor("zoomBoxLeft", BoxColor);
	setLayerBackgroundColor("zoomBoxRight", BoxColor);
	setLayerBackgroundColor("zoomBoxBottom", BoxColor);

	// capture map image's mousemove event
	//document.getElementById(zbMapImage).onmousemove = getMouse;
    	document.onmousemove = getMouse; //captureMousePosition;
}

/****************************************************************************************
ZoomBox initialization
****************************************************************************************/

function initZoomBox()
{
	setZoomBoxMode(1);
	operationdone = false;
	// capture map image's onmousedown and onmouseup events
	document.getElementById(zbMapImage).onmousedown = mapTool;
	document.getElementById(zbMapImage).onmouseup = chkMouseUp;

	updateZoomBoxCursor();
}

/****************************************************************************************
Identification initialization
****************************************************************************************/

function initIdent()
{
	setZoomBoxMode(1);
	operationdone = false;
	IDENTIFY = true;
	document.getElementById(zbMapImage).onmousedown = mapTool;
	document.getElementById(zbMapImage).onmouseup = chkMouseUp;

	updateZoomBoxCursor();
}

/****************************************************************************************
Panning initialization
****************************************************************************************/

function activaPan(){
	operationdone = false;
	window.document.getElementById(zbMapImage).onmousemove = null;
	document.getElementById(zbMapImage).onmousedown = mapTool;

    HACERPAN = true;
    setZoomBoxMode(0);
    
    onResize();
      
    document.getElementById(zbMapImage).style.position = 'absolute';
	window.document.getElementById(zbMapImage).style.left=hspc+1;
	window.document.getElementById(zbMapImage).style.top=vspc+1;
    document.getElementById(zbMapImage).style.cursor = 'move';
}

/****************************************************************************************
Mode and cursor functions
****************************************************************************************/

function setZoomBoxMode(mode)
{
	currMode = mode;
	updateZoomBoxCursor();
}

function updateZoomBoxCursor()
{
  if (!is5up) return;

  var MapImg = document.getElementById(zbMapImage);
  if (MapImg == null) return;

  switch (currMode)
  {
    case MODE_BOX:
	MapImg.style.cursor = "crosshair";
	break;
    default:
	MapImg.style.cursor = "default";
  }
}

/****************************************************************************************
DHTML layer functions
****************************************************************************************/

// Create a DHTML layer
function createLayer(name, inleft, intop, width, height, visible, content) {
	  var layer;
	  if (isNav4) {
	    document.writeln('<layer name="' + name + '" left=' + inleft + ' top=' + intop + ' width=' + width + ' height=' + height +	' visibility=' + (visible ? '"show"' : '"hide"') +  '>');
	    document.writeln(content);
	    document.writeln('</layer>');
	  } else {
	    document.writeln('<div id="' + name + '" style="position:absolute; overflow:hidden; left:' + inleft + 'px; top:' + intop + 'px; width:' + width + 'px; height:' + height + 'px;' + '; z-index:1; visibility:' + (visible ? 'visible;' : 'hidden;'));
	    document.writeln(content);
	    document.writeln('</div>');
	  }
}

// get the layer object called "name"
function getLayer(name) {
	  if (isNav4)
	    return(document.layers(name));
	  else if (isIE4) {
	    layer = eval('document.all.' + name + '.style');
	    return(layer);
	  } else if (is5up) {
		var theObj = document.getElementById(name);
		return theObj.style
	  }
	  else
	    return(null);
}

function isVisible(name) {
	  var layer = getLayer(name);
	  if (layer != null) {
		  if (isNav && layer.visibility == "show")
		    return(true);
		  if (isIE && layer.visibility == "visible")
		    return(true);
	  }
	  return(false);
}

// move layer to x,y
function moveLayer(name, x, y) {
	var layer = getLayer(name);
	if (layer != null) {
		if (isNav4)
			layer.moveTo(x, y);
		else {
			layer.left = x + "px";
			layer.top  = y + "px";
		}
	}
}

// set layer background color
function setLayerBackgroundColor(name, color) {
	var layer = getLayer(name);
    if (layer != null) {
		if (isNav4)
		layer.bgColor = color;
		else
		layer.backgroundColor = color;
	}
}

// toggle layer to invisible
function hideLayer(name) {
	var layer = getLayer(name);
	if (layer != null) {
		if (isNav4)
		layer.visibility = "hide";
		else
			 layer.visibility = "hidden";
	}
}

// toggle layer to visible
function showLayer(name) {
	var layer = getLayer(name);
	if (layer != null) {
		if (isNav4)
		layer.visibility = "show";
		else
		 layer.visibility = "visible";
	}
}

// clip layer display to clipleft, cliptip, clipright, clipbottom
// Not working with Mozilla Milestone 12 (Nav5)
function clipLayer(name, clipleft, cliptop, clipright, clipbottom) {
	  var layer = getLayer(name);
	  if (layer == null) return;
	  if (isNav4) {
		    layer.clip.left   = clipleft;
		    layer.clip.top    = cliptop;
		    layer.clip.right  = clipright;
		    layer.clip.bottom = clipbottom;
	  }
	  else {
		    layer.clip = 'rect(' + cliptop + ' ' +  clipright + ' ' + clipbottom + ' ' + clipleft +')';
	  }
}

function boxIt(theLeft,theTop,theRight,theBottom) {
		clipLayer("zoomBoxTop",theLeft,theTop,theRight,theTop+ovBoxSize);
		clipLayer("zoomBoxLeft",theLeft,theTop,theLeft+ovBoxSize,theBottom);
		clipLayer("zoomBoxRight",theRight-ovBoxSize,theTop,theRight,theBottom);
		clipLayer("zoomBoxBottom",theLeft,theBottom-ovBoxSize,theRight,theBottom);
		showLayer("zoomBoxTop");
		showLayer("zoomBoxLeft");
		showLayer("zoomBoxRight");
		showLayer("zoomBoxBottom");
}


/****************************************************************************************
Navigation functions - used to resize zoom box
****************************************************************************************/

// get cursor location (document coordinates + image coordinates)
function getImageXY(e) {
	// 1st) Capture document coordinates.
    if (isNav) {
        // When the page scrolls in Netscape, the event's mouse position
        // reflects the absolute position on the screen. innerHight/Width
        // is the position from the top/left of the screen that the user is
        // looking at. pageX/YOffset is the amount that the user has 
        // scrolled into the page. So the values will be in relation to
        // each other as the total offsets into the page, no matter if
        // the user has scrolled or not.
        xMousePos = e.pageX;
        yMousePos = e.pageY;
    } else {
        // When the page scrolls in IE, the event's mouse position 
        // reflects the position from the top/left of the screen the 
        // user is looking at. scrollLeft/Top is the amount the user
        // has scrolled into the page. clientWidth/Height is the height/
        // width of the current page the user is looking at. So, to be
        // consistent with Netscape (above), add the scroll offsets to
        // both so we end up with an absolute value on the page, no 
        // matter if the user has scrolled or not.
        xMousePos = window.event.x+document.body.scrollLeft;
        yMousePos = window.event.y+document.body.scrollTop;
    }
    // 2nd) Calculate image coordinates
    mouseX = xMousePos - hspc
    mouseY = yMousePos - vspc
}

// start zoom in
function startZoomBox(e) {
	getImageXY(e);
	// keep it within the MapImage
	if ((mouseX<iWidth) && (mouseY<iHeight)) {
		if (zooming) {
			stopZoomBox(e);
		} else {
			x1=mouseX;
			y1=mouseY;
			x2=x1+1;
			y2=y1+1;
			zleft=x1;
			ztop=y1;
			zbottom=y1;
			zright=x1;
			boxIt(x1,y1,x2,y2);
			zooming=true;
		}
	}
	return false;

}

// stop zoom box display
function stopZoomBox(e) {
	zooming=false;
	if ( (zright <zleft+2) && (ztop < zbottom+2) )
	{
		zright = zleft;
		zbottom = ztop;
	}

	hideLayer("zoomBoxTop");
	hideLayer("zoomBoxLeft");
	hideLayer("zoomBoxRight");
	hideLayer("zoomBoxBottom");
	window.scrollTo(0,0);

	return true;
}

// get the coords at mouse position
function getMouse(e) {

  onResize();
  getImageXY(e);

    if (mouseX>0 & mouseX<iWidth & mouseY>0 & mouseY<iHeight & xmin != 0)
    {
	tpixel = (xmax-xmin)/ iWidth;
	xpixel = xmin + (mouseX * tpixel);
	xpixel = xpixel*Math.pow(10, 1);
	xpixel = Math.round(xpixel);
	xpixel = xpixel/Math.pow(10, 1);

	ypixel = ymax - (mouseY * tpixel);
	ypixel = ypixel*Math.pow(10, 1);
	ypixel = Math.round(ypixel);
	ypixel = ypixel/Math.pow(10, 1);

	if (Math.abs(xmax - xmin) >= Math.abs(ymax - ymin)){
	  escala = Math.abs(xmax - xmin) / (iWidth * (0.079375 / 300))
	} else {
	  escala = Math.abs(ymax - ymin) / (iHeight * (0.079375 / 300))
	}

	window.status = 'Escala: 1/' + Math.round(escala) + ' --- X=' + xpixel.toFixed(1) + ' ; Y=' + ypixel.toFixed(1);
	/*
	NOTA: En FireFox por defecto tiene la opción de
		  mostrar los mensajes de estado desactivada;
		  para activarla ir a "herramientas / preferencias"
		  seleccionar la opción "Características Web"
		  pulsar el botón "Avanzadas..." junto a "Activar JavaScript"
		  y marcar la opción "Cambiar texto de la barra de...."
	*/
    } else {
	window.status='No disp.';
    }

    if (mouseX>iWidth)//(xMousePos>hspc+iWidth)
	mouseX = iWidth;
    if (mouseY>iHeight)//(yMousePos>vspc+iHeight)
	mouseY = iHeight;
    if (mouseX<1)//(xMousePos<=hspc)
	mouseX = 1;
    if (mouseY<1)//(yMousePos<=vspc)
	mouseY = 1;

    if (zooming) {
	x2=mouseX;
	y2=mouseY;
	setClip();
    }
    
    return false;

}

// clip zoom 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);
	}
}

/****************************************************************************************
Click/Mouse functions - used to catch mouse button events
****************************************************************************************/

// check for mouseup
function chkMouseUp(e) {
  if (!operationdone) {
	  if (IDENTIFY) {
		getImageXY(e);
		stopZoomBox(e);
		onIdent(mouseX.toFixed(0), mouseY.toFixed(0));
		IDENTIFY = !IDENTIFY;
		operationdone = !operationdone;
		setZoomBoxMode(0);
		return false;
	  } else {
		stopZoomBox(e);
		operationdone = !operationdone;
		onZoomBox(zleft, ztop, zright, zbottom);
		setZoomBoxMode(0);
		return false;
	  }
  }
}

// perform appropriate action with mapTool
function mapTool (e) {
  if (!operationdone) {
    if (HACERPAN) {
		//start Pan-ing
		beginDrag(e);
    } else {
  	if (IDENTIFY) {
  		//No action is taken
  	} else {
		// check mouse left button

	    if (isNav){
			hspc=e.pageX;
			vspc=e.pageY;
	    } else {
			hspc = event.clientX;
			vspc = event.clientY;
	    }

		var button;
		if (document.layers) { button = e.which; }
		else {	
			if (isNav){ button = e.which; }
			else{ button = event.button;}
		}
		if( button != 1)  return;

		// adjust left-top
		onResize();

		getImageXY(e);

		if ( (currMode == MODE_BOX) && (!zooming) && (mouseX>=0)
			 && (mouseX<iWidth) && (mouseY>=0) && (mouseY<iHeight)) {
			startZoomBox(e);
		return false;
		} else if (zooming) {
			getMouse(e);
			stopZoomBox(e);
		}
	}
    }
  }
	return false;
}


function onResize()
{
  if (!operationdone) {

	var el=document.getElementById(zbMapImage);
	var numels = 0;
	var YWin=el.offsetTop+2;
	var XWin=el.offsetLeft+2;

	if (el == null) return;
	
	var tempEl=el.offsetParent;
	while(tempEl!=null){
		YWin=YWin+tempEl.offsetTop;
		XWin=XWin+tempEl.offsetLeft;
		if(tempEl.offsetTop!=0 || tempEl.offsetLeft!=0) numels=numels+1
		tempEl=tempEl.offsetParent;
	}

	XWin=XWin+(numels/2)-2
	YWin=YWin+(numels/2)-2
	
	hspc=XWin
	vspc=YWin

	moveLayer( "zoomBoxTop", XWin, YWin);
	moveLayer( "zoomBoxLeft", XWin, YWin);
	moveLayer( "zoomBoxRight", XWin, YWin);
	moveLayer( "zoomBoxBottom", XWin, YWin);
  }
}

/****************************************************************************************
Pan-ing functions
****************************************************************************************/

//----------------------------------------------------------------------------
// When drag begins, this function is called.. see addEventListener calls 
// in start function. 
//
function beginDrag(e) {
	if (isNav) e.preventDefault();

	// Stores the current mouse position for further use.
	//
    if (isNav){
	window.lastX=e.clientX;
	window.lastY=e.clientY;
    } else {
		window.lastX=event.clientX;
		window.lastY=event.clientY;
    }

	// Register doDrag event handler to receive generic onmousemove events. 
	//
	window.document.onmousemove=doDrag;

	// Register endDrag event handler to receive generic onmouseup events. 
	//
	window.document.onmouseup=endDrag;

    // Get mouse position at pan-start.
    //
		IniPosX = window.lastX;
		IniPosY = window.lastY;
}

//-------------------------------------------------------------------------------------
// doDrag event - called when dragging
//
function doDrag(e) {
	// Calculates the difference between the last mouse position
	// and the current position. 
	//
    var difX=0;
    var difY=0;

    if (isNav){
	var difX=e.clientX-window.lastX;
	var difY=e.clientY-window.lastY;
    } else {
		difX=event.clientX-window.lastX;
		difY=event.clientY-window.lastY;
    }

	// Same thing but now for dd_area...
	// In this case the user is dragging the image instead the little resize icon. 
	//
	var newX1 = parseInt(window.document.getElementById(zbMapImage).offsetLeft)+difX;
	var newY1 = parseInt(window.document.getElementById(zbMapImage).offsetTop)+difY;
	window.document.getElementById(zbMapImage).style.left=newX1+'px';
	window.document.getElementById(zbMapImage).style.top=newY1+'px';

	// Stores the current mouse position.
	//
    if (isNav){
	window.lastX=e.clientX;
	window.lastY=e.clientY;
    } else {
		window.lastX=event.clientX;
		window.lastY=event.clientY;
    }
    return false;

}

//----------------------------------------------------------------------------
// Called when the mouse button is released
//
function endDrag(e) {
	// Releases the events.

    // Get mouse position at pan-end.
    //
		if (isNav){
		    var FinPosX=e.clientX;
		    var FinPosY=e.clientY;
		} else {
			FinPosX=event.clientX;
			FinPosY=event.clientY;
		}

		window.document.getElementById(zbMapImage).onmousemove=getMouse;
		window.document.getElementById(zbMapImage).onmousedown=null;
	window.document.onmousemove=null;
	window.document.onmouseup=null;
	document.getElementById(zbMapImage).style.cursor = '';
	panRealizado(FinPosX - IniPosX, FinPosY - IniPosY);

		HACERPAN = !HACERPAN;
		operationdone = !operationdone;
		return false;
}
