var BoxColor = "#999999";	// color of box
var BoxSize = 1;	// box line width;

// Global vars
var iWidth = sAncho_Pix;	// image width (default)
var iHeight = sAlto_Pix;	// image height (default)
var hspc = 0;		// horizontal image offset
var vspc = 0;		// vertical image offset
var ovBoxSize = 1;	// Zoombox line width;
var zbMapImage = "MainWindow"; // default

var MODE_BOX = 0;
var currMode = MODE_BOX;

var zooming = false;

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;

// Global vars for browser type and version
var isNav = (navigator.appName.indexOf("Netscape")>=0);
var isGecko = (navigator.userAgent.toLowerCase().indexOf('gecko') != -1)
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;
	}
}

is5up = false;
var inicio=navigator.userAgent.indexOf("MSIE");
inicio=inicio+5;
if ( parseFloat(navigator.userAgent.substr(inicio,3)) >= 6 )
{
   is5up = true;
}

var isFF=(isNav && !isNav4);
function initZoomBox(iMapWidth, iMapHeight, MapImageName)
{
	iWidth = iMapWidth;
	iHeight = iMapHeight;
	zbMapImage = MapImageName;
	// zoom/selection box
	content = '<img name="zoomImageTop" src="pixel.gif" width="1" height="1">';
	createLayer("zoomBoxTop",0,0,iWidth,iHeight,false,content);
	content = '<img name="zoomImageLeft" src="pixel.gif" width="1" height="1">';
	createLayer("zoomBoxLeft",0,0,iWidth,iHeight,false,content);
	content = '<img name="zoomImageRight" src="pixel.gif" width="1" height="1">';
	createLayer("zoomBoxRight",0,0,iWidth,iHeight,false,content);
	content = '<img name="zoomImageBottom" src="pixel.gif" width="1" height="1">';
	createLayer("zoomBoxBottom",0,0,iWidth,iHeight,false,content);

	// set zoom box color
	setLayerBackgroundColor("zoomBoxTop", BoxColor);
	setLayerBackgroundColor("zoomBoxLeft", BoxColor);
	setLayerBackgroundColor("zoomBoxRight", BoxColor);
	setLayerBackgroundColor("zoomBoxBottom", BoxColor);

	if (isNav) {
		document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
	}

	if(!isFF)
		document.forms['direcc'].onmousedown = mapTool;
	if(!isFF)
		document.onmouseup = chkMouseUp;
	else
		document.onmouseup=mapTool;
	document.forms['direcc'].onmousemove = getMouse;

	updateZoomBoxCursor();
}

function setZoomBoxMode(mode)
{
	if ( mode == MODE_BOX)
	{
		currMode = mode;
		updateZoomBoxCursor();
	}
}


/****************************************************************************************
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 {
		if(isGecko)
		{
			var html = ""
			html +='<DIV ID="'+name+'" name="'+name+'"';
			html +=' STYLE="position: absolute; overflow:hidden;';
			html +=' left:' + inleft + 'px; top:' + intop + 'px;'
			html +=' width:' + width + 'px; height:' + height + 'px;';
			html +=' z-index:1;';
			html +=' visibility:' + (visible ? 'visible;' : 'hidden;');
			html +='">';
			html +=content;
			html +='</DIV>';
			document.getElementById('dchild').insertAdjacentHTML('beforeEnd',html);
		}else{
		    var html='';
		    html=html+'<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;');
		    html=html+content;
		    html=html+'</div>';
		    document.writeln(html);
		}
	  }
}

// 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 || isGecko) {
		var theObj = document.getElementById(name);
		return theObj.style
	  }else
	  	return(null);
	  /*
	  }else if (isGecko){
		var theObj = document.getElementById(name);
		return theObj;
	  */
	  /*
	  } 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) {

	//alert('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
function getImageXY(e) {
	if (isNav4) {
		if(nIE){
			mouseX=e.pageX;
			mouseY=e.pageY;
		}

	} else {
		if(!isNav){
			mouseX=event.clientX + document.body.scrollLeft-2;
			mouseY=event.clientY + document.body.scrollTop-2;
		}
		else{
			mouseX=e.clientX + document.body.scrollLeft-2;
			mouseY=e.clientY + document.body.scrollTop-2;
		}

	}

	//window.status="mouseX" + mouseX +"  mouseY"+ mouseY;
	// subtract offsets from page left and top
	mouseX = mouseX-hspc;
	mouseY = mouseY-vspc;
	if(document.forms['direcc']['punto'].checked==true){
		consultarPunto(document.forms['direcc']['norte_p'],document.forms['direcc']['este_p'],e);
	}
	//else window.status="";

}

/*consulta punto en el mapa, a partir de la escala, el XCENTRO y el YCentro*/
function consultarPunto(norte,este,e)
{
	if(mouseX>=0 && mouseX<iWidth && mouseY>=0 && mouseY<iHeight)
	{
		norte.value=convertidorY(parseInt(mouseY));
		este.value=convertidorX(parseInt(mouseX));
	}

}
//sPX2CM variable global
function convertidorX(x){
	//var iWidth=446;
	var XCentro=parseInt(document.direcc.XCentro.value);
	var Escala=parseInt(document.direcc.Escala.value);
	//var px2cm=0.12544;
	//var px2cm=0.17625;
	var gw=parseFloat(sPX2CM * Escala);
	var ginitx=parseInt(parseInt(XCentro)-parseInt(gw/2));
	var  xnuevo=parseInt(parseInt(x*(gw/iWidth)) + parseInt(ginitx));
	return xnuevo;
}

//sPX2CM variable global
function convertidorY(y){
//	var iHeight=360;
//	var iWidth=446;
	var YCentro=parseInt(document.direcc.YCentro.value);
	var Escala=parseInt(document.direcc.Escala.value);
	var ytmp=parseInt(iHeight-parseInt(y));
	//var px2cm=0.12544;
	//var px2cm=0.17625;
	var gh=parseFloat(sPX2CM*Escala)*parseFloat(iHeight/iWidth);
	var ginity=parseInt(parseInt(parseInt(YCentro)-parseInt(gh/2)));
	var  ynuevo=parseInt(parseInt(ytmp*(gh/iHeight)) + parseInt(ginity));
	return ynuevo;
}

// start zoom in
function startZoomBox(e) {
	getImageXY(e);

	// keep it within the MapImage
	if ((mouseX<iWidth) && (mouseY<iHeight)) {
		if (zooming)
		{
			stopZoomBox(e);
		}
		else
		{
			if(document.forms['direcc']['moverse2'].checked)
				return false;
			zooming=true;
			x1=mouseX;
			y1=mouseY

			x2=x1+1;
			y2=y1+1;
			zleft=x1;
			ztop=y1;
			zbottom=y1;
			zright=x1;
			boxIt(x1,y1,x2,y2);
			if(isFF){
				chkMouseUp(e);
			}


		}
	}
	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)
{
	//window.status="";
	getImageXY(e);

	if (mouseX>iWidth)
		mouseX = iWidth - 1;
	if (mouseY>iHeight)
		mouseY = iHeight - 1;
	if (mouseX<=0)
		mouseX = 1;
	if (mouseY<=0)
		mouseY = 1;


	if (zooming)
	{
		//alert("zooming = "+zooming);
		if(document.forms['direcc']['acercarse'].checked || document.forms['direcc']['alejarse'].checked)
		{
			//alert("1 o 2");
			x2=mouseX;
			y2=mouseY;
			setClip();
		}
	}
	/*
	if ( (currMode == MODE_BOX) && (!zooming) && (mouseX>=0)
		 && (mouseX<iWidth) && (mouseY>=0) && (mouseY<iHeight))
	{
		startZoomBox(e);
		return false;
	}
	*/
	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 ((currMode == MODE_BOX) && (zooming))
	{
		stopZoomBox(e);
		if (zleft == zright && ztop == zbottom)
			onZoomXY(zleft, ztop);
		else
			onZoomBox(zleft, ztop, zright, zbottom);
	}

	return false;
}

// perform appropriate action with mapTool
var entroAmapTool = false;
function mapTool (e) {

	if (entroAmapTool && isFF)
	{
		entroAmapTool=false;
		return;
	}else
		entroAmapTool=true;


	// check mouse left button
	var button;
	if (document.layers)
	{
	 	button = e.which;
	}
	else
	{
		if(window.event)
		button = window.event.button;
		else button=1;

	}
	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()
{
	var MapImg = document.images[zbMapImage];
	if (MapImg == null) return;

	if( document.all)
	{
		vspc = 0; //custom values
		hspc = 0;
		var element = MapImg;

		do
		{
			hspc += element.offsetLeft;
			vspc += element.offsetTop;

		}
		while( (element = element.offsetParent))
	}
	else
	{
		if (isNav && !isNav4) {
			MapImg=document.images[zbMapImage];
			vspc = 0;
			hspc = 0;

			var element = MapImg;
			do
			{
				hspc += element.offsetLeft;
				vspc += element.offsetTop;

			}
			while( (element = element.offsetParent))
		}
		else{
			hspc = MapImg.x;
			vspc = MapImg.y;
		}
	}

	moveLayer( "zoomBoxTop", hspc, vspc);
	moveLayer( "zoomBoxLeft", hspc, vspc);
	moveLayer( "zoomBoxRight", hspc, vspc);
	moveLayer( "zoomBoxBottom", hspc, vspc);
}

function updateZoomBoxCursor()
{
  //cursorStyle=MapImg.style.cursor;
  //return;
  //FIXME ojo aqui no entra con esta condicion
  if (!is5up) return;

  var MapImg = document.images[zbMapImage];
  if (MapImg == null) return;


  switch (currMode)
  {
    case MODE_BOX:
	//MapImg.style.cursor = "url(/cursor/3domove.ani)";
	MapImg.style.cursor = "default";
	  break;
	default:
	        //MapImg.style.cursor = "url(/cursor/3domove.ani)";
	        MapImg.style.cursor = "default";
  }
  cursorStyle=MapImg.style.cursor;

}

function onZoomXY(x, y)
{
	document.forms[0].MainWindow_x.value = x;
	document.forms[0].MainWindow_y.value = y;

	//document.forms[0].submit();
}

function onZoomBox(left, top, right, bottom)
{
	document.forms[0].MainWindow_x.value = left;
	document.forms[0].MainWindow_y.value = top;
	document.forms[0].MainWindow_x2.value = right;
	document.forms[0].MainWindow_y2.value = bottom;

	//document.forms[0].submit();
}
