// aimsCommon.js
/*
*  JavaScript template file for ArcIMS HTML Viewer
*		dependent on aimsXML.js, ArcIMSparam.js, aimsMap.js
*/

aimsCommonPresent=true;


var legendImage="";
var modeBlurb = modeList[0];

// delimiter to be used between coordinates in strings in ArcXML request
var coordsDelimiter = " ";
// delimiter to be used between pairs of coordinates in strings in ArcXML request
var pairsDelimiter = ";";

var chkUnits=false;
var legendTemp = false;

var chkGeocodeLayers = false;

var isArcMapService = false;

// character used by browser in decimals - either point or comma
var decimalChar = ((("theChar is" + (10/100)).indexOf("."))==-1) ? "," : ".";
//alert("Decimal character: " + decimalChar);

/*
***************************************************************************************

Common functions

***************************************************************************************
*/



// when there is a mapservice to load, it proceeds from here
function startUp() {
	if (imsURL != "") {
		//alert(imsURL);
		iWidth = parseInt(document.theImage.width);
		iHeight = parseInt(document.theImage.height);
		getStartExtent();
	}
}

// get the starting extent
function getStartExtent() {	
	if (parent.PostFrame.document.forms[0]!=null) {
		var theString = '<ARCXML version="1.1">\n<REQUEST>\n<GET_SERVICE_INFO renderer="false" extensions="true" ';
		if (aimsLayersPresent) {
			if (LayerID.length>0) {
				theString += 'fields="false" ';
			} else {
				theString += 'fields="true" ';
			}
		} else {
			theString += 'fields="false" ';
		}
		theString += '/>\n</REQUEST>\n</ARCXML>';
		var theReply="";
		sendToServer(imsURL,theString,3);
	} else {
		alert(msgList[2]);
	}
}

// process the start extent and set up layers
function processStartExtent(theReply) {
	//alert('Process Start Extent');
	//alert(theReply);
	// check for separators in serviceinfo
	var endpos = 0;
	var startpos = 0;
	var pos = theReply.indexOf("<SEPARATORS");
	if (pos!=-1) {
		
		startpos = theReply.indexOf("ts=",pos);
		if (startpos!=-1) {
			startpos += 4;
			endpos = theReply.indexOf(dQuote,startpos);
			pairsDelimiter = theReply.substring(startpos,endpos);
		}
		startpos = theReply.indexOf("cs=",pos);
		if (startpos!=-1) {
			startpos += 4;
			endpos = theReply.indexOf(dQuote,startpos);
			coordsDelimiter = theReply.substring(startpos,endpos);
		}
	}
	isArcMapService = (theReply.indexOf("<LAYOUTINFO")!=-1);
	if (isArcMapService) {
		if (autoAdjustForArcMapServer) {
			// adjust sizes when displayed by ArcMap Server
			var nasize = parseInt(NorthArrowSize)*2;
			NorthArrowSize = new String(nasize);
		}
	}
	//alert("NorthArrowSize=" + NorthArrowSize);
	pos = theReply.indexOf("<MAPUNITS");
	if (pos!=-1) {
		startpos = theReply.indexOf("units=",pos);
		if (startpos!=-1) {
			startpos += 7;
			endpos = theReply.indexOf(dQuote,startpos);
			MapUnits = theReply.substring(startpos,endpos);
		}
	} else {
		// if the serviceinfo did not have MAPUNITS tag and units are set to Degrees
		 if (MapUnits=="DEGREES") {
		 	// if it is too big for the world. . . allow for oversize extent
				// default to Feet
		 	if ((eRight > 250) || (eTop > 150) || (eLeft < -250) || (eBottom < -150)) MapUnits="FEET";
			// alert(MapUnits);
		 } 
	}
	MapUnits = MapUnits.toUpperCase();
	if (MapUnits=="DECIMAL_DEGREES") MapUnits = "DEGREES";

	// ¿Nos mantenemos en las mismas coordenadas que en el servicio anterior?
	if (!parent.MapFrame.resetExtent) {
		if (eLeft<0 || eBottom <0) {
			
			eLeft = parent.MapFrame.ExtentIni[parent.MapFrame.idxServicio][0];
			eBottom = parent.MapFrame.ExtentIni[parent.MapFrame.idxServicio][1];
			eRight = parent.MapFrame.ExtentIni[parent.MapFrame.idxServicio][2];
			eTop = parent.MapFrame.ExtentIni[parent.MapFrame.idxServicio][3];
			startLeft=eLeft;
			startRight=eRight;
			startTop=eTop;
			startBottom=eBottom;
		}
		/*else
		{
			// Añadido para que funcionen bien las ortos 1:15.000 solo con islas EH y LG (distinto extent)
			if (eLeft == 179129.02) // Si estamos en Full Extent de las 1:15.000 Reseteamos vista...
				{
				eLeft = parent.MapFrame.ExtentIni[parent.MapFrame.idxServicio][0];
				eBottom = parent.MapFrame.ExtentIni[parent.MapFrame.idxServicio][1];
				eRight = parent.MapFrame.ExtentIni[parent.MapFrame.idxServicio][2];
				eTop = parent.MapFrame.ExtentIni[parent.MapFrame.idxServicio][3];
				startLeft=eLeft;
				startRight=eRight;
				startTop=eTop;
				startBottom=eBottom;
				}
		}*/
	} else {
		if (getStartingExtent) {
			
			pos = theReply.indexOf("<PROPERTIES");
			var theXYs =  getEnvelopeXYs(theReply, pos)
			eLeft = theXYs[0];
			eBottom = theXYs[1];
			eRight = theXYs[2];
			eTop = theXYs[3];
			startLeft=eLeft;
			startRight=eRight;
			startTop=eTop;
			startBottom=eBottom;
		} else {
			
			eLeft=startLeft;
			eRight=startRight;
			eTop=startTop;
			eBottom=startBottom;
			xDistance = Math.abs(eRight-eLeft);
			var sFactor = xDistance / iWidth;
			mapScaleFactor = sFactor;
		}
	}

	if (aimsLayersPresent) {
		getLayers(theReply);
		if (setLayerVisible.length>0) setupLayerVisible();
		// Visibilidad de los grupos en la leyenda
		for (i=0; i<LayerName.length; i++) {
			var idGrupo = getIdGrupo(LayerName[i]);
			noListLayer[i] = (NoGruposLeyenda[idxServicio][idGrupo]!=0);
		}
	}

	xDistance = Math.abs(eRight-eLeft);
	yDistance = Math.abs(eTop-eBottom);
	xHalf = xDistance/2;
	yHalf = yDistance/2;
	panX = xDistance * panFactor;
	panY = yDistance * panFactor;
	mouseX = 0;
	mouseY = 0;
	pixelX = xDistance/iWidth;
	pixelY = yDistance/iHeight;
	mapX = eLeft;
	mayY = eTop;
	lastLeft = eLeft;
	lastRight = eRight;
	lastTop = eTop;
	lastBottom = eBottom;
	fullLeft = limitLeft;
	fullRight = limitRight;
	fullTop = limitTop;
	fullBottom = limitBottom;
	fullWidth = Math.abs(fullRight - fullLeft);
	fullHeight = Math.abs(fullTop - fullBottom);		

	chkGeocodeLayers = false;

	hideRetrieveData();

	// Visibilidad de las capas aims según la visibilidad de los grupos de capas
	// (para conservar la misma activación/visibilidad de capas cuando cambiamos de un servicio a otro y mantener la coherencia)
	for (var i=0; i<LayerName.length; i++) {
		var idGrupo = parent.MapFrame.getIdGrupo(LayerName[i]);
		LayerVisible[i] = parent.MapFrame.GrupoVisible[parent.MapFrame.idxServicio][idGrupo];
		//alert(LayerName[i] + " of group " + parent.MapFrame.Grupos[parent.MapFrame.idxServicio][idGrupo]  + " is" + ((LayerVisible[i]!=0)?"":" not") + " visible");
	}
	
	if (parent.MapFrame.Inicio || (parent.MapFrame.resetExtent && parent.MapFrame.cambioServicio)) {
		// Imagen inicial del servicio
		parent.MapFrame.cambioServicio = false;
		parent.MapFrame.theImage.src = parent.MapFrame.ImagenIni[parent.MapFrame.idxServicio][parent.MapFrame.iIndexWH];
		//parent.MapFrame.preImage.src = parent.MapFrame.ImagenIni[parent.MapFrame.idxServicio][parent.MapFrame.iIndexWH];
		parent.MapFrame.afterMapRefresh();
	} else { // cuando no queremos full extent o hay cambio de servicio (para que mantenga la extensión actual)
		sendMapXMLActiveX();
	}
	// Indicamos que estamos en el estado inicial (imagen full-extent precargada)
	if (parent.MapFrame.resetExtent) {
		parent.MapFrame.Inicio = true;
	}
}


/* Solicita la lista de servicios disponibles */
function startMap() {
	showRetrieveData();
	startUp();
}

/*  ************************
*	Extent functions
*	************************
*/

// get the Map Image width
function getMapWidth () {
	var mapFrameWidth = thePageWin.innerWidth;
	
	if (mapFrameWidth == null) {
		//mapFrameWidth = thePageDoc.body.clientWidth;
		mapFrameWidth = iWidths[parent.MapFrame.iIndexWH];
	}
	return mapFrameWidth;
}

 //get the Map Image height
function getMapHeight () {
	var mapFrameHeight = thePageWin.innerHeight;
	
	if (mapFrameHeight == null) {
		//mapFrameHeight = thePageDoc.body.clientHeight;
		mapFrameHeight = iHeights[parent.MapFrame.iIndexWH];
	}
	return mapFrameHeight;
}

/*  *****************************************************
*	Various utility Functions
*	*****************************************************
*/

// disables error checking
function clearError() {
	return true;
}

// reset error checking to default
function resetError() {
	return false;
}


function reloadApp() {
	if (isNav) {
		document.location = "default.htm";
	}
}	

// just get the interior string from the theReply between preString and postString
//		starting from startpos
function justGetValue(theReply,preString,postString,startpos) {
	var theValue = "";
	var pos = theReply.indexOf(preString,startpos);
	if (pos!=-1) {
		pos = pos + preString.length;
		var endpos = theReply.indexOf(postString,(pos));
		if (endpos!=-1) {
			theValue = theReply.substring(pos,endpos);
			xmlEndPos = endpos;
		}
	}
	return theValue;	
}

// replace +  in string with space to allow parsing of unescaped xml response
function replacePlus(inText) {
     var re = /\+/g;
      inText = inText.replace(re," ");
     return inText;
}

// get the substring between beforeString and afterString, starting at startpos
// 		must be found before limitpos (0 for no limit) 
// 		caseSensitive = true or false
function getInsideString(inString,beforeString,afterString,startpos,limitpos,caseSensitive) {
	var returnString = "";
	var ucInString = inString;
	var ucBefore = beforeString;
	var ucAfter = afterString;
	if (limitpos==0) limitpos = inString.length;
	if (!caseSensitive) {
		ucInString = inString.toUpperCase();
		ucBefore = beforeString.toUpperCase();;
		ucAfter = afterString.toUpperCase();;
	}
	pos = ucInString.indexOf(ucBefore,startpos);
	//alert(startpos);
	if ((pos != -1) && (pos<limitpos)) {
		pos = pos + ucBefore.length;
		var endpos = ucInString.indexOf(ucAfter,pos);
		returnString = inString.substring(pos,endpos);
	}	
	
	return returnString;
}

function lockedPopups(oWin, alertar) {
	if (oWin==null || typeof(oWin)=="undefined") {
		if (alertar) alert("Para el correcto funcionamiento de la aplicación, desactive el bloqueo de popups.");
		return true;
	}
	return false;
}
