/* Coordenada actual */
var _X = 0.0
var _Y = 0.0

/* Extensión inicial */
var _XMin = 0.0
var _XMax = 0.0
var _YMin = 0.0
var _YMax = 0.0

/* Dimensiones del mapa */
var MapWidth = _XMax - _XMin
var MapHeight = _YMax - _YMin

/* Dimensiones de la imagen */
var ImgWidth = 500
var ImgHeight = 300

/* Factor Zoom */
var ZoomFactor = 4

/* Servicio ArcIMS */
var Servicio = "BIOTATierra"
var NumeroCapas = 3

/* Herramienta actual */
var CurrentTool = ""

/* Mensajes */
var msgRecuperando = "Recuperando imagen..."
var msgSinInicializar = "Haga click en Refrescar"


function CambiaTool(Tool){

	ZoomIn.className = (Tool == ZoomIn.name) ? "ZoomIn_2" : "ZoomIn_1"
	ZoomOut.className = (Tool == ZoomOut.name) ? "ZoomOut_2" : "ZoomOut_1"
	Pan.className = (Tool == Pan.name) ? "Pan_2" : "Pan_1"
	Identify.className = (Tool == Identify.name) ? "Identify_2" : "Identify_1"

	if (Tool == ZoomIn.name){
		oImg.className = "ZoomInCur"
	}
	else if (Tool == ZoomOut.name){
		oImg.className = "ZoomOutCur"
	}
	else if (Tool == Pan.name){
		oImg.className = "PanCur"
	}
	else if (Tool == Identify.name){
		oImg.className = "IdentifyCur"
	}
	//oImg.movable = (Tool == Pan.name) ? 1 : 0
	
	CurrentTool = Tool

}

function CalculateMapDim(){
	MapWidth = _XMax - _XMin
	MapHeight = _YMax - _YMin
}

function CenterAtXY(){
	_XMin = _X - parseInt(MapWidth/2)
	_XMax = _XMin + MapWidth
	_YMin = _Y - parseInt(MapHeight/2)
	_YMax = _YMin + MapHeight
}

function doFullExtent(){
        // Extensión total
        _XMin = 180000
        _XMax = 660000
        _YMin = 3055000
        _YMax = 3260000

        CalculateMapDim()

        // Solicitamos el nuevo mapa
        RequestMap()
}

function doZoomIn(){
	// Nos centramos en el punto
	CenterAtXY()
	
	// Nos acercamos
	var offX = parseInt(MapWidth / ZoomFactor)
	var offY = parseInt(MapHeight / ZoomFactor)
	_XMin = _XMin + offX
	_XMax = _XMax - offX
	_YMin = _YMin + offY
	_YMax = _YMax - offY
	
	CalculateMapDim()

	// Solicitamos el nuevo mapa
	RequestMap()
}

function doZoomOut(){
	// Nos centramos en el punto
	CenterAtXY()
	
	// Nos alejamos
	var offX = parseInt(MapWidth / ZoomFactor)
	var offY = parseInt(MapHeight / ZoomFactor)
	_XMin = _XMin - offX
	_XMax = _XMax + offX
	_YMin = _YMin - offY
	_YMax = _YMax + offY
	
	CalculateMapDim()
	
	// Solicitamos el nuevo mapa
	RequestMap()
}

function doPan(){
	// Nos centramos en el punto
	CenterAtXY()
	
	// Nos alejamos
	var offX = parseInt(MapWidth / 2)
	var offY = parseInt(MapHeight / 2)
	_XMin = _X - offX
	_XMax = _X + offX
	_YMin = _Y - offY
	_YMax = _Y + offY
	
	CalculateMapDim()
	
	// Solicitamos el nuevo mapa
	RequestMap()
}

/*function doPan(){
	if (CurrentTool != Pan.name) return
	
	var Left = parseInt(oImg.style.left)
	var Top = parseInt(oImg.style.top)

	// Establecemos las nuevas coordenadas del mapa
	_XMin = _XMin - Scale_X(Left)
	_XMax = _XMin + MapWidth
	_YMax = _YMax + Top * ScaleFactor_Y()
	_YMin = _YMax - MapHeight 
	
	CalculateMapDim()

	// Solicitamos el nuevo mapa
	RequestMap()
}*/

function doIdentify(){
	// Solicitamos información de celda
	w = window.open("", "RelacionEspecies", "width=585,height=300")
	frmIdentify.X.value = _X
	frmIdentify.Y.value = _Y
        w.focus()
	frmIdentify.submit()
}

function ApplyTool(){
	if (CurrentTool == ZoomIn.name)
		doZoomIn()
	else if (CurrentTool == ZoomOut.name)
		doZoomOut()
	else if (CurrentTool == Pan.name)
		doPan()
	else if (CurrentTool == Identify.name)
		doIdentify()
}

function VerCoordenadas(){
	_X = parseInt(_XMin + Scale_X(window.event.offsetX))
	_Y = parseInt(_YMin + Scale_Y(window.event.offsetY))
	coordX.innerText = FormatNumber(_X, 0, true, false, true)
	coordY.innerText = FormatNumber(_Y, 0, true, false, true)
}

function ScaleFactor_X(){
	return(MapWidth/oImg.width)
}

function ScaleFactor_Y(){
	return(MapHeight/oImg.height)
}

function Scale_X(left){
	return(left * ScaleFactor_X())
}

function Scale_Y(top){
	return((oImg.height - top) * ScaleFactor_Y())
}

function Validar(){
	var msg = ""
	
	if (!(CartBase.checked || Orto.checked || MapaEspecies.checked)){
		msg = "Seleccione al menos una capa"
		return msg
	}
	return msg
}

function GetPixelsPerMeter(){
	var tmp = cboMonitor.options[cboMonitor.selectedIndex].value/1000
	
	return screen.width/tmp
}

function CambiaEscala(){
	
	if (oImg.width == 0)
		return false

	var scale = Math.round(GetPixelsPerMeter() * MapWidth/oImg.width)
	
	Escala.innerText = "1:" + fmtEscala(scale)
}

function fmtEscala(scale){
	value = new String(scale)
	var milesMillones = value.substring(0, value.length-9)
	var millones = value.substring(value.length-9, value.length-6)
	var miles = value.substring(value.length-6, value.length-3)
	var unidades = value.substring(value.length-3, value.length)

	if (milesMillones.length > 0)
		value = milesMillones + "." + millones + "." + miles + "." + unidades
	else if (millones.length > 0)
		value = millones + "." + miles + "." + unidades
	else if (miles.length > 0)
		value = miles + "." + unidades
	else
		value = unidades
	return value
}

function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
{ 
  //if (isNaN(parseInt(num))) return "NaN";
  if (isNaN(parseInt(num))) return "";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	//tmpNum *= iSign;					// Readjust for sign

	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// Le ponemos un 0 al final si el valor es decimal
	if (tmpNumStr.indexOf('.') > 0)
		{
		if (tmpNumStr.substring(tmpNumStr.indexOf("."), tmpNumStr.length).length < (decimalNum+1))
			tmpNumStr += "0";
		}
	else
		if (decimalNum > 0)
			tmpNumStr += ".00";
		

	// Para nuestro formato
	if (tmpNumStr.indexOf('.') > 0)
		tmpNumStr = tmpNumStr.substring(0,tmpNumStr.indexOf('.')) + "_" + tmpNumStr.substring(tmpNumStr.indexOf('.')+1,tmpNumStr.length)
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) 
		{
		var iStart = tmpNumStr.indexOf("_");
		
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) 
			{
			tmpNumStr = tmpNumStr.substring(0,iStart) + "." + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
			}		
		}

	if (iSign == -1) // Readjust for sign
		{
		tmpNumStr = "-" + tmpNumStr;
		}					

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);

	// Para ponerlo en nuestro formato
	if (tmpNumStr.indexOf('_') > 0)
		tmpNumStr = tmpNumStr.substring(0,tmpNumStr.indexOf('_')) + "," + tmpNumStr.substring(tmpNumStr.indexOf('_')+1,tmpNumStr.length)
	
	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}

function Mensaje(texto){
	oMsg.innerText = texto
	if (texto == ""){
		oMap.style.display = ""
		oMsg.style.display = "none"
	}
	else{
		oMap.style.display = "none"
		oMsg.style.display = ""
	}
}

function VerMapa(ruta){
	Mensaje(msgRecuperando)
	//document.write(ruta)
	oImg.src = ruta
}

function onReadyStateChange(){
	if (oImg.readyState == "uninitialized"){
		Mensaje(msgRecuperando)
		if (oImg.src != "")
			window.document.body.style.cursor = "wait"
	}
	else if (oImg.readyState == "interactive" || oImg.readyState == "loaded" || oImg.readyState == "complete"){
		oImg.style.left = 0
		oImg.style.top = 0
		Mensaje("")
		window.document.body.style.cursor = "default"
	}
	else{
		Mensaje(msgRecuperando)
		window.document.body.style.cursor = "wait"
	}
}

function Refrescar(){
	var msg

	msg = Validar(msg)
	if (msg != ""){
		alert(msg)
		return false
	}
	
	if (_XMin == 0 && _XMax == 0 && _YMin == 0 && _YMax == 0){
		_YMin = 3150571
		_YMax = _YMin + 1500
		MapHeight = _YMax - _YMin
		MapWidth = parseInt((ImgWidth/ImgHeight) * MapHeight)
		_XMin = 370008
		_XMax = _XMin + MapWidth
		CalculateMapDim()
	}
	
	RequestMap()
}

function RequestMap(){
	var msg
	var urlMap
	var sEnv, sDim, sLay
	var bCapas = 0

	msg = Validar(msg)
	if (msg != ""){
		alert(msg)
		return false
	}
	
	urlMap = "http://pre.sitcan.com/MapServer/Mapa.asp?"
	
	sEnv = "XMin=" + _XMin + "&YMax=" + _YMax + "&XMax=" + _XMax + "&YMin=" + _YMin
	
	sDim = "&Ancho=" + ImgWidth + "&Alto=" + ImgHeight
	
	if (MapaEspecies.checked)
		bCapas += 1
	if (CartBase.checked)
		bCapas += 2
	if (Orto.checked)
		bCapas += 4
	sLay = "&NumeroCapas=" + NumeroCapas + "&Capas=" + bCapas
	
	sSvc = "&Servicio=" + Servicio
	
	VerMapa(urlMap + sEnv + sDim + sLay + sSvc)
	
	CambiaEscala()
	
}

function onMouseMoveImg(){
	// Coordenadas (del mapa)
	VerCoordenadas()
}

function onMoveStart(){
	//oImg.className = "PanMoveCur"
}