aimsXMLPresent=true;
// client version
var cVersion = "&ClientVersion=4.0"; 
/*
***************************************************************************************

Functions for sending XML requests and XML reponses

***************************************************************************************
*/

// global variables
	// change these in aimsCustom.js to send XML response to custom function.
	// use numbers >= 1000
var selectXMLMode = 6;
var identifyXMLMode = 7;
var queryXMLMode = 8;
var findXMLMode = 14;
var hyperlinkXMLMode = 15;

// variables globales de filtrado
var filtroCalle = '';
var limpiarFiltroCalle = true;
var filtroPortal = '';

// encoding for XML header
var charEncoding = "UTF-8";
var localeEncoding = 'encoding="' + charEncoding + '" ';

// charset for dynamic HTML pages - static pages must be changed manually
var charSet = "ISO-8859-1"

var formColor = "#000000";

// common dynamic variables
var XMLMode = 1;
var okToSend = true;

var xHalf = xDistance/2;
var yHalf = yDistance/2;

// ending position to start parse scan of XML string
var xmlEndPos = 0;

var lastXMLResponse = "";

//var theImageType = "PNG";

var drawOVExtentBox=false;
// force a request for Overview map image with each map request?
var forceNewOVMap = false;
// the base servlet connector URL
var connectorURL = "http://" + hostName + "/servlet/com.esri.esrimap.Esrimap?ServiceName=redirect";

var requestMethod = "Servlet";
if (parent.connectorType!="") requestMethod = parent.connectorType;

	// index of current active MapService - default is zero - multiples in MultiService sample
var activeMapServiceIndex = 0;
	// array for determining if extent coordinates should have comma instead of point for decimals
var forceCommaInRequest = new Array();
forceCommaInRequest[activeMapServiceIndex] = false;
var forceCommaInOV = false;

// adjust limit extent to match image proportions?
var adjustLimit=true;

// dynamic flag for setting focus on external attribute display
var focusOnData = false;
var extWin;

/* send in XML request and get XML response */ 
function sendToServer(URLString,XMLRequest,theType) {
	//alert('Tipo ' + theType + ': ' + XMLRequest);
	// pasamos de la imagen original a la pedida al servidor
	if (XMLRequest.indexOf("GET_IMAGE")!=-1) {
		parent.MapFrame.Inicio = false;
		//alert("Inicio a falso");
	}

	if (parent.PostFrame.document.forms[0]!=null) {
		if (okToSend) {
			XMLMode = theType;
			if (XMLMode==1) showRetrieveMap();
			okToSend = false;
			htmlSendToServer(URLString,XMLRequest,theType);
		} else {
			alert(msgList[10]);
			hideRetrieveMap();
			hideRetrieveData();
		}
	} else {
		alert(msgList[11]);
		hideRetrieveMap();
		hideRetrieveData();
	}
		
}
				
function htmlSendToServer(URLString,XMLRequest,theType) {
	var Servicio="";
	var p = URLString.indexOf("ServiceName=");
	if (p > -1) {
		var l = URLString.indexOf("&");
		if (l > -1)
			Servicio = URLString.substring(p+12,l-1);
		else
			Servicio = URLString.substring(p+12);
	}
	Servicio=Servicios[idxServicio][1]
	htmlSendToServerActiveX(XMLRequest, Servicio);
}

function htmlSendToServerActiveX(XMLRequest, Servicio) {
	var p = document.location.href.lastIndexOf("/");
	var ruta = document.location.href.substring(0, p+1);
	var cVersion = "&ClientVersion=4.0";
	var thePostForm = parent.PostFrame.document.forms[0];
	var xmlHeader = '<?xml version="1.0" ' + localeEncoding + '?>';
	thePostForm.action = ruta + "pages/conn/Mapa.asp";
	thePostForm.ArcXMLRequest.value = xmlHeader + XMLRequest;
	thePostForm.Servicio.value = Servicio;
	if (thePostForm.FormCharset!=null) thePostForm.FormCharset.value = charSet;
	if (thePostForm.BgColor!=null) thePostForm.BgColor.value = "#000000";
	thePostForm.submit();
}
function getHost(theURL) {
	var thisHost = "";
	var startpos = theURL.indexOf("//");
	if (startpos==-1) {
		startpos = 0;
	} else {
		startpos = startpos + 2;
	}
	var endpos = theURL.indexOf("/",startpos);
	if (endpos==-1) endpos = theURL.length;
	thisHost = theURL.substring(startpos,endpos);
	return thisHost;
	
}

function getService(theURL) {
	var theService = "";
	var startpos = theURL.indexOf("ServiceName=");
	if (startpos!=-1) {
		startpos +=12;
		theService = theURL.substring(startpos);
	}
	return theService;
}

/* Envia la peticion XML al conector ActiveX */
function sendMapXMLActiveX(CheckUncheck, idEle, capaEle, whereEle) {
	// CheckUncheck: indica si se ha activado/desactivado una capa (no ha habido cambio de extent)
	// whereEle: clausula where para resaltar un elemento
	beforeMapRefresh();
	showRetrieveMap();
	// adecuamos a la respuesta previsible de ArcIMS
	getXYsActiveX();
	// Parametros
	var servicio = Servicios[idxServicio][1];
	var pServicio = "Servicio=" + servicio;
	var pEnvelope = "&XMin=" + forceComma(eLeft) + "&YMin=" + forceComma(eBottom) + "&XMax=" + forceComma(eRight) + "&YMax=" + forceComma(eTop);
	var pDimensiones = "&Alto=" + iHeight + "&Ancho=" + iWidth;
	var bCapas = 0;
	var nCapas = 0;
	for (i=0; i<GrupoVisible[idxServicio].length; i++)
		if (GrupoVisible[idxServicio][i]) {
			bCapas += Math.pow(2,i);
			nCapas++;
		}
	var pCapas = "&Capas=" + bCapas;
	var pEle = ""
	if (idEle)
		pEle += "&idEle=" + idEle
	if (capaEle)
		pEle += "&capaEle=" + capaEle
	if (whereEle)
		pEle += "&whereEle=" + whereEle
	if (Servicios[idxServicio][8])
		pServicio += "&ecwSvc=" + Servicios[idxServicio][8];
	var parametros = pServicio + pEnvelope + pDimensiones + pCapas + pEle;
	
	theImage.src="images/pixel.gif";

	// Los servicios ECW se tratan de forma distinta
	var preUrl = "pages/conn/";
	if (location.hostname=="jcarlos")
		preUrl = "http://mapa.grafcan.com/website/RegistroPropiedad/pages/conn/n/";
	if (ecw[idxServicio]) {
		transPNG(theImage, "http://195.57.95.86/imgsvr/ecw.aspx?ecw=" + ecw[idxServicio][0] + "&sizex="+iWidth+"&sizey="+iHeight+"&worldtlx="+eRight+"&worldtly="+eTop+"&worldbrx="+eLeft+"&worldbry="+eBottom+"&fill=000000&type=jpeg&quality=94", preUrl + "Mapa.asp?" + parametros, CheckUncheck);
	} else {
		with (theImage.style) {
			backgroundImage = "url('images/pixel.gif')";
			filter = "";
		}
		window.setTimeout('theImage.src=\"' + preUrl + 'Mapa.asp?' + parametros + '\";', 250);
	}
	Inicio = false;
	afterMapRefresh(CheckUncheck);

	if (toolMode==3) { // si lo que se hizo fue un panning...
		moveLayer("theMap",hspc,vspc);
		clipLayer2("theMap",0,0,iWidth,iHeight);
	}
}

function transPNG(oImg, jpgsrc, pngsrc, CheckUncheck) {
	// No solicitar la orto cuando se active/desactive una capa
	if (!CheckUncheck || oImg.style.backgroundImage=="")
		oImg.style.backgroundImage = "url('" + jpgsrc + "')";
	oImg.src = pngsrc;
}

/* Adecua la extension solicitada a las dimensiones del mapa */
function getXYsActiveX() {
	xDistance = Math.abs(eRight-eLeft);
	yDistance = Math.abs(eTop-eBottom);
	xHalf = xDistance / 2;
	yHalf = yDistance / 2;
	// adecuamos la extension solicitada a las dimensiones de la ventana del visor
	if (xDistance > yDistance) {
		var f = xDistance / iWidth;
		yDistance = f * iHeight;
		yHalf = yDistance / 2;
		var mitad = Math.abs(eTop-eBottom) / 2;
		eBottom = eBottom + mitad - yHalf;
		eTop = eBottom + yDistance;
	} else {
		var f = yDistance / iHeight;
		//var f = xDistance / iWidth;
		xDistance = f * iWidth;
		xHalf = xDistance / 2;
		var mitad = Math.abs(eLeft-eRight) / 2;
		eLeft = eLeft + mitad - xHalf;
		eRight = eLeft + xDistance;
	}
	panX = xDistance * panFactor;
	panY = yDistance * panFactor;
	var sFactor = xDistance / iWidth;
	if (aimsLayersPresent)
		if (sFactor!=mapScaleFactor) mapScaleFactor = sFactor;
}

/* Procesa la respuesta XML */
function processXML(theReplyIn) {
	//alert(theReplyIn);
	if (doURLencode) {
		theReplyIn = replacePlus(theReplyIn);
		var theReply = unescape(theReplyIn);
	} else {
		var theReply = theReplyIn;
	}
	lastXMLResponse = theReply;
	okToSend = true;
	var theError = getXMLErrorMessage(theReply);

	switch(XMLMode) {
		case 1: /* Map Image */
			var theURL = "";
			theURL = getURL(theReply);
			if (theURL != "") {
				getXYs(theReply);
				// Imagen de mapa resultante
				document.theImage.src = "images/pixel.gif";
				document.theImage.src = theURL;

				afterMapRefresh();
				
				if (toolMode==3) { // si lo que se hizo fue un panning...
					moveLayer("theMap",hspc,vspc);
					clipLayer2("theMap",0,0,iWidth,iHeight);
					//window.setTimeout('showLayer("theMap");',1000);
					if (hasLayer("theMapClicks")) {
						moveLayer("theMapClicks",hspc,vspc);
						clipLayer2("theMapClicks",0,0,iWidth,iHeight);
					}
				}
				
			}
			else
				alert(msgList[14] + theError);
			break;

		case 3: /* ServiceInfo - Extent */
			//alert("processXML()[3]\n" + theReply);
			if (getLimitExtent) {
				var pos = theReply.indexOf("<PROPERTIES");
				var theXYs =  getEnvelopeXYs(theReply, pos)
				limitLeft = theXYs[0];
				limitBottom = theXYs[1];
				limitRight = theXYs[2];
				limitTop = theXYs[3];
			}

			if (adjustLimit) {
				//adjust limit to proportions of defined image size
				var imgW2HRatio = iWidth / iHeight;
				var imgH2WRatio = iHeight / iWidth;
				var itWidth = limitRight - limitLeft;
				var itHeight = limitTop - limitBottom;
				var mapRatio = itHeight / itWidth;
				var ix = limitLeft + (itWidth/2);
				var iy = limitBottom + (itHeight/2);
				var iSize = itWidth/2;
				if (iWidth>=iHeight) {
					//alert("Image wider than tall");
					if (imgH2WRatio<mapRatio) {
						//alert("Map ratio greater than Image" );
						iSize = (itHeight * imgW2HRatio) / 2;
						limitRight = ix + iSize;
						limitLeft = ix - iSize;
					} else {
						//alert("Limit wider than tall");
						iSize = (itWidth * imgH2WRatio) / 2;
						limitTop = iy + iSize;
						limitBottom = iy - iSize;
					}
				} else {
					//alert("Image taller than wide");
					if (imgH2WRatio<mapRatio) {
						//alert("Map ratio greater than Image");
						iSize = (itHeight * imgH2WRatio) / 2;
						limitRight = ix + iSize;
						limitLeft = ix - iSize;
					} else {
						//alert("Map ratio smaller than Image");
						iSize = (itWidth * imgH2WRatio) / 2;
						limitTop = iy + iSize;
						limitBottom = iy - iSize;
					}
				}
				//alert("Adjusted Limits: " + limitLeft + ", " + limitBottom + ", " + limitRight + ", " + limitTop);
			}
			imageLimitLeft=limitLeft;
			imageLimitRight=limitRight;
			imageLimitTop=limitTop
			imageLimitBottom=limitBottom;
			fullLeft = limitLeft;
			fullRight = limitRight;
			fullTop = limitTop;
			fullBottom = limitBottom;

			fullWidth = Math.abs(fullRight - fullLeft);
			fullHeight = Math.abs(fullTop - fullBottom);
			fullOVWidth = Math.abs(fullOVRight - fullOVLeft);
			fullOVHeight = Math.abs(fullOVTop - fullOVBottom);
			// get service info - extent, layers
			//alert("processXML()[4]\n" + theReply);
			forceCommaInRequest[activeMapServiceIndex] = false;
			processStartExtent(theReply);
						
			break;
		
		default:
			// send any responses to custom requests off to the custom handler
				// XMLMode >= 1000 are reserved for custom requests/responses
			if (XMLMode >= 1000) {
				useCustomFunction(theReply);
			} else {
				alert(theReply + msgList[19]);
			}
			
		}
	//}
	
}

/* Prepara la petición XML para el mapa */
function writeXML() {
	var theString = '<ARCXML version="1.1">\n<REQUEST>\n<GET_IMAGE>\n<PROPERTIES>\n<ENVELOPE minx="' + forceComma(eLeft) + '" miny="' + forceComma(eBottom) + '" maxx="' + forceComma(eRight) + '" maxy="' + forceComma(eTop) + '" />\n';
	theString += '<IMAGESIZE height="' + iHeight + '" width="' + iWidth + '" />\n';
	var visString = "";
	if (aimsLayersPresent) {
		// tell the server which layers are to be visible
		theString += '<LAYERLIST >\n';
		for (var i=0;i<layerCount;i++) {
			if (LayerVisible[i]==1) {
				theString += '<LAYERDEF id="' + LayerID[i] + '" visible="true" ';
				if (aimsClassRenderPresent) {
					theString += addSpecialRenderToMap(i);
				} else {
					theString += '/>\n';
				}
				
			}
			else {
				theString += '<LAYERDEF id="' + LayerID[i] + '" visible="false" />\n';
			}
			
		}
		theString += '</LAYERLIST>\n';
	}

	// Color de fondo de mapa
	if (mapBackColor!="")
		theString += '<BACKGROUND color="' + mapBackColor + '" />\n\n';

	if (aimsLegendPresent) {
		// create a legend image
		var legXML = addLegendToMap();
		if (legendVisible) theString += legXML;
	}
	
	theString += '</PROPERTIES>\n';
	
	// any custom stuff to fit here
	if (aimsCustomPresent) theString += addCustomToMap1();
		
	/* Geocoding o punto */
	if (showGeocode) {
		// draw the point . . . also used to display any point with a label on map
		theString += '<LAYER type="acetate" name="GeoCode1">\n';
		theString += '<OBJECT units="database">\n<POINT coords="' + forceComma(geocodeX) + coordsDelimiter + forceComma(geocodeY) + '">\n';
		theString += '<SIMPLEMARKERSYMBOL  type="circle"  outline="' + geocodePointOutColor + '" color="' + geocodePointColor + '" width="' + geocodePointSize +'" overlap="false" />\n</POINT></OBJECT>\n';
		if (geocodeLabel!="") {
			theString += '<OBJECT units="database">\n<TEXT coords="' + forceComma(geocodeX) + coordsDelimiter + forceComma(geocodeY) + '" label="' + geocodeLabel + '">\n';
			theString += '<TEXTMARKERSYMBOL fontcolor="' + geocodePointColor + '" fontsize="12" shadow="64,64,64" glowing="255,255,0" halignment="right" valignment="top" overlap="false" /></TEXT></OBJECT>\n';
		}
		theString += '</LAYER>\n';
		showGeocode = false;
	}
	
	// any custom stuff to fit here
	if (aimsCustomPresent) theString += addCustomToMap2();
		
	// any custom stuff to fit here
	if (aimsCustomPresent) theString += addCustomToMap3();

	// any custom stuff to be drawn on top of everything
	if (aimsCustomPresent) theString += addCustomToMap4();
	
	// render de calle (en desuso, puesto que se hace mediante VML)
	// el parametro filtroCalle se pone a vacio para no entrar en esta porcion de codigo y no solicitar el render de la calle
	if (filtroCalle != '') {
		// las condiciones del filtro de la calle estan en las variables filtroCalle y filtroPortal
		theString += getImagenCalle();
		if (limpiarFiltroCalle) {
			filtroCalle = '';
			filtroPortal = '';
		}
		//alert(theString);
	}

	theString += '</GET_IMAGE>\n</REQUEST>\n</ARCXML>';
	//alert(theString);
	return theString;
}

/* Obtiene la extensión del mapa de la respuesta XML */
function getXYs(theString) {
	var tempStr = "";
	var smallStr = "";
	var startpos = 0;
	var endpos = 0;
	var theReply = theString
	var theXYs =  getEnvelopeXYs(theString, 0)
	eLeft = theXYs[0];
	eBottom = theXYs[1];
	eRight = theXYs[2];
	eTop = theXYs[3];
	xDistance = Math.abs(eRight-eLeft);
	yDistance = Math.abs(eTop-eBottom);
	xHalf = xDistance / 2;
	yHalf = yDistance / 2;
	panX = xDistance * panFactor;
	panY = yDistance * panFactor;
	var sFactor = xDistance / iWidth;
	if (aimsLayersPresent)
		if (sFactor!=mapScaleFactor) mapScaleFactor = sFactor;
}

/* Obtiene la URL de la imagen del mapa de la respuesta XML */
function getURL(theReply) {
	var theURL = "";
	var startpos = 0;
	var endpos = 0;

	var pos = theReply.indexOf("OUTPUT");
	if (pos != -1) {
		theURL = getInsideString(theReply,'url="',dQuote,pos,0,false);
	}
	legendImage = getLegendURL(theReply);
	return theURL;

}

/* Obtiene la URL de la imagen de la leyenda del mapa de la respuesta XML */
function getLegendURL(theReply) {
	var theURL = "";
	var startpos = 0;
	var endpos = 0;
	var pos = theReply.indexOf("LEGEND");
	//alert(pos);
	if (pos != -1) {
		theURL = getInsideString(theReply,'url="',dQuote,pos,0,false);
	}
	//alert("Legend:" + theURL);
	return theURL;

}

// get min and max x,y's from xml stream . . . return an array with values
function getEnvelopeXYs(theString, startpos) {
	var theEnvelope = new Array();
	//forceCommaInRequest[activeMapServiceIndex] = false;
	theString = theString.toUpperCase();
	var tempString = "";
	var pos = theString.indexOf("ENVELOPE",startpos);
	if (pos!=-1) {
		pos = pos + 8;
		startpos = theString.indexOf("MINX=",pos);
		startpos += 6;
		var endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		theEnvelope[0] = parseFloat(setDecimalString(tempString)); 
		startpos = theString.indexOf("MINY=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		theEnvelope[1] = parseFloat(setDecimalString(tempString)); 
		startpos = theString.indexOf("MAXX=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		theEnvelope[2] = parseFloat(setDecimalString(tempString)); 
		startpos = theString.indexOf("MAXY=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		theEnvelope[3] = parseFloat(setDecimalString(tempString)); 
		xmlEndPos = endpos;
	}
	return theEnvelope;

}

// set number string to have decimal character to match browser language type - point or comma
function setDecimalString(numberString) {
	if (numberString.indexOf(",")!=-1) forceCommaInRequest[activeMapServiceIndex] = true;
	if (decimalChar==".") {
		numberString = numberString.replace(/,/g, ".");
	} else {
		numberString = numberString.replace(/./g, ",");
	}
	return numberString;
}

function forceComma(theNumber) {
	var comma = ",";
	var dot = ".";
	var charOut = comma;
	var charIn = dot;
	var numberString = new String(theNumber);
	if (forceCommaInRequest[activeMapServiceIndex]) {
		charOut = dot;
		charIn = comma;
	}
	var pos = numberString.indexOf(charOut);
	if (pos!=-1) {
		var begin = numberString.substring(0,pos);
		var ending = numberString.substring(pos+1, numberString.length);
		numberString = begin + charIn + ending;
	}
	return numberString;
}

/* Comprueba si hay un mensaje de error en la respuesta XML */
function getXMLErrorMessage(theString) {
	var pos1 = 0;
	var pos2 = 0;
	var pos3 = 0;
	var theError = "";
	pos3 = theString.indexOf("<ERROR");
	if (pos3!=-1) {
		pos1 = theString.indexOf(">",pos3);
		pos1 += 1;
		pos2 = theString.indexOf("</ERROR");
		theError = theString.substring(pos1,pos2)
	}
	return theError;

}

/* Comprueba si la la variable theURL tiene un host diferente del especificado en la variable theHost */
function isNotSameHostInURL(theURL, theHost) {
	var startpos = theURL.indexOf("//");
	if (startpos==-1) {
		startpos = 0;
	} else {
		startpos = startpos + 2;
	}
	var endpos = theURL.indexOf("/",startpos);
	if (endpos==-1) endpos = theURL.length;
	var thisHost = theURL.substring(startpos,endpos);
	if (thisHost==theHost) {
		return false;
	} else {
		return true;
	}
}
