// aimsCustom.js
/*
*  JavaScript template file for ArcIMS HTML Viewer
*		dependent on aimsXML.js, ArcIMSparam.js, aimsCommon.js, aimsMap.js,
*		aimsLayers.js, aimsDHTML.js
*		aimsClick.js, aimsNavigation.js,
*/

// global variables
	var dPixelsPerInches = 97.69230769; // los ppi debe calcularse así: (ancho resolución pantalla)/(pulgadas monitor)
	var dPixelsPerMiles = 63360 * dPixelsPerInches;
	var dPixelsPerFeet = 12.0 * dPixelsPerInches;
	var dPixelsPerKilometers = 39370.07874016 * dPixelsPerInches;
	var dPixelsPerMeters = 39.37007874 * dPixelsPerInches;
	var dPixelsPerCentimeters = 0.39370079 * dPixelsPerInches;

	aimsCustomPresent=true;
	// change these to send XML response to custom function.
	// use numbers >= 1000 and match in useCustomFunction()
	// defaults are defined in aimsXML.js and use standard functions
	
	// xml response mode for selection
	selectXMLMode = 6;
	// xml response mode for identify
	identifyXMLMode = 7;
	// xml response mode for query
	queryXMLMode = 8;
	// xml response mode for find
	findXMLMode = 14;
	// xml response mode hyperlink
	hyperlinkXMLMode = 15;
	// consulta de calle
	queryStreet = 1001;
	// capa de puntos
	addPoint = 1002;
	delPoint = 1003;




// custom function for handling clicks 
// 		flow redirected here when
//		toolMode set to >=1000
function customMapTool(e) {
	if (toolMode == 1001) {
		// insert code here
		return false;
	}
	if (toolMode==1002 || toolMode==1003) {
		// insert code here
		parent.herramientas.clicPunto(mouseX, mouseY);
	} else if (toolMode == 1004 && !parent.MapFrame.Inicio) {
		if (!TieneInfo[idxServicio]) {
			alert("No hay información asociada");
			return;
		}
		var idxCapa = getLayerIdx(TieneInfo[idxServicio][0]);
		//alert("Capa: " + LayerName[idxCapa] + " (" + TieneInfo[idxServicio][0] + ")" + (LayerVisible[idxCapa]?"":" no") + " es visible");
		if (LayerVisible[idxCapa])
			getInfo(e);
	}
}

function getInfo(e) {
	var t = parent.herramientas.frmInfo;
	t.Capa.value = getLayerID(TieneInfo[idxServicio][0]);
	t.Campo.value = TieneInfo[idxServicio][1];
	t.Servicio.value = Servicios[idxServicio][1];
	var d = 1;
	if (TieneInfo[idxServicio][6].toUpperCase() == "POINT")
		d = infoBuffer*mapScaleFactor;
	t.XMin.value = parseInt(mapX-d);
	t.XMax.value = parseInt(mapX+d);
	t.YMin.value = parseInt(mapY-d);
	t.YMax.value = parseInt(mapY+d);
	t.submit();
}

function processInfo(xml) {
	var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
	if (xmlDoc.loadXML(xml)) {
		var xmlNodes = xmlDoc.selectNodes("//FEATURES/FEATURE/*");
		
		if (xmlNodes.length==0)	{
			alert("No hay información asociada");
			return;
		}

		var iniHtml = '<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n'
		            + '<title>Información</title>\n'
		            + '<link href=\"../estilos/style.css\" rel=\"stylesheet\" type=\"text/css\">\n'
		            + '<script language=\"javascript\" src=\"../scripts/scripts.js\"></script>\n'
		            + '</head>\n'
		            + '<body text=\"#000000\" LINK=\"#000000\" VLINK=\"#000000\" ALINK=\"#000000\">\n'
		            + '<table border=\"0\" cellspacing=\"0\" width=\"100%\">\n'
		            + '  <tr>\n'
		            + '    <td width=\"6\" valign=\"top\" class=\"TitulosVentanas\"></td>\n'
		            + '    <td width=\"100%\" align=\"left\" valign=\"bottom\" nowrap bgcolor=\"#000063\" class=\"TitulosVentanas\">&nbsp;Selecci&oacute;n de elemento...</td>\n'
		            + '    <td width=\"6\" class=\"TitulosVentanas\"></td>\n'
		            + '  </tr>\n'
		            + '  <tr>\n'
		            + '    <td height=\"180\" colspan=\"3\" align=\"center\" valign=\"top\">\n'
		            + '	<div id=\"situacion\" style=\"margin-top: 8px; margin-bottom: 6px; position:relative\">\n'
		            + '	<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\" class=\"MenuTable2\">\n'
		var finHtml = '	</table>\n'
                    + '	</div>\n'
                    + '	</td>\n'
                    + '  </tr>\n'
                    + '</table>\n'
                    + '</body>\n'
                    + '</html>'
		var enca = '	  <tr >'
		         + '	  	<th width=\"40%\" nowrap align=left><font size=2>#ID#</font></td>\n'
		         + '	  	<th width=\"60%\" colspan=\"2\" nowrap align=left><font size=2>#DESC#</font></td>\n'
		         + '	  </tr>\n'
		var fila = '	  <tr id=\"fila#N#\" title=\"Mostrar información...\" onClick=\"javascript:opener.parent.MapFrame.detalleInfo(#ARGS#)\" onMouseOver=\"hilight(this);this.style.cursor=\'hand\';\" onMouseOut=\"fade(this);this.style.cursor=\'auto\';\" >'
		         + '	  	<td width=\"40%\" nowrap><font size=2>#ID#</font></td>\n'
		         + '	  	<td width=\"60%\" colspan=\"2\" nowrap><div align=\"left\"><font size=2>#DESC#</font></div></td>\n'
		         + '	  </tr>\n'

		var content = "";
		var id = "";
		var desc = "";
		var nombre = "";
		var argumentos = "";
		var re = "";
		var tmp;
		var cab = TieneInfo[idxServicio][2].split(";"); // descriptores campos
		var fld = TieneInfo[idxServicio][1].split(";"); // nombres campos
		var uni = null; // unidades
		if (TieneInfo[idxServicio][4]!="") uni = TieneInfo[idxServicio][4].split(";"); // unidades
		var txt = TieneInfo[idxServicio][5]; // texto estático informativo para la ventana
		// el primer argumento es el texto estático
		argumentos = "\'" + txt + "\',";
		if  (xmlNodes.length==1) {
			// lista de argumentos para la llamada al detalle
			var coma = "";
			for (j=0; j<fld.length; j++) {
				re = /#/g;
				nombre = fld[j].replace(re, "").toUpperCase();
				desc = xmlNodes.item(0).getAttribute(nombre);
				if (!desc) desc = "";
				if (uni && uni[j] != "") { // si tiene unidades se las añadimos y formateamos numéricamente
					try {
						var numero = parseFloat(desc)
						if (!isNaN(numero))
							desc = FormatNumber(desc.replace(",","."),2,true,false,true) + " " + uni[j];
					} catch (ex) {}
				}
				argumentos += coma + "\'" + fld[j] + "@" + cab[j] + "@" + desc + "\'";
				coma = ",";
			}
			// campo ID (si existe)
			if (xmlNodes.item(0).getAttribute("ID"))
				argumentos += coma + "\'FID@FID@" + xmlNodes.item(0).getAttribute("ID") + "\'";
			eval("detalleInfo(" + argumentos + ")");
		} else {
			// Encabezado de la tabla de resultados
			re = /#ID#/g
			var encabezado = enca.replace(re, cab[0])
			re = /#DESC#/g
			encabezado = encabezado.replace(re, cab[1])
			content = encabezado
			//
			for (i=0; i<xmlNodes.length; i++) { // features
				argumentos = "\'" + txt + "\',";
				// attributes (solo ID y Descripcion)
				re = /#/g;
				nombre = fld[0].toUpperCase().replace(re, ""); // nombre del campo id
				id = xmlNodes.item(i).getAttribute(nombre); // valor del id
				nombre = fld[1].toUpperCase(); // nombre del campo descriptor
				desc = xmlNodes.item(i).getAttribute(nombre); // valor del descriptor
				re = /#N#/g;
				tmp = fila.replace(re, i); // numero de fila
				re = /#ID#/g;
				tmp = tmp.replace(re, id); // ID
				re = /#DESC#/g;
				tmp = tmp.replace(re, desc); // Descriptor
				// lista de argumentos para la llamada al detalle
				var coma = "";
				for (j=0; j<fld.length; j++) {
					re = /#/g;
					nombre = fld[j].replace(re, "").toUpperCase();
					desc = xmlNodes.item(i).getAttribute(nombre);
					if (!desc) desc = "";
					if (uni && uni[j] != "") { // si tiene unidades se las añadimos y formateamos numéricamente
						try {
							var numero = parseFloat(desc)
							if (!isNaN(numero))
								desc = FormatNumber(desc.replace(",","."),2,true,false,true) + " " + uni[j];
						} catch (ex) {}
					}
					argumentos += coma + "\'" + fld[j] + "@" + cab[j] + "@" + desc + "\'";
					coma = ",";
				}
				// campo ID (si existe)
				if (xmlNodes.item(i).getAttribute("ID"))
					argumentos += coma + "\'FID@FID@" + xmlNodes.item(i).getAttribute("ID") + "\'";
				re = /#ARGS#/g;
				tmp = tmp.replace(re, argumentos);
				content += tmp;			
			}
			var oWin = window.open("", "infoWin", "left=" + window.screenLeft + ",top=" + window.screenTop + ",directories=no,location=no,menubar=no,status=no,toolbar=no,width=400,height=220,scrollbars=yes,resizable=yes");
			//
			oWin.document.write("");
			oWin.document.close();
			//
			oWin.document.write(iniHtml + content + finHtml);			
			oWin.focus();
		}
	} else {
		alert("El formato de la respuesta no es XML");
	}
	
}

function detalleInfo() {
	// Argumentos:
	//	array de n elementos, donde cada uno de ellos es un par "'CAMPO;DESCRIPTOR;VALOR'"
	var iniHtml = '<html>\n'
				+ '<head>\n'
				+ '<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n'
				+ '<title>#DESC#</title>\n'
				+ '<link href=\"../estilos/style.css\" rel=\"stylesheet\" type=\"text/css\">\n'
				+ '<script language=\"javascript\" src=\"../scripts/scripts.js\"></script>\n'
				+ '<script language=javascript>\n'
				+ 'var consultadas = false\n'
				+ 'function BuscarSubfincas(finca, registro){\n'
				+ '	if (!consultadas) {\n'
				+ '		var frm = document.getElementById("frmBuscarSubfincas")\n'
				+ '		frm.FincaMatriz.value = finca\n'
				+ '		frm.Registro.value = registro\n'
				+ '		frm.submit()\n'
				+ '		consultadas = true\n'
				+ '		document.getElementById("txtVerSubfincas").innerHTML = "<strong>Ocultar subfincas</strong>"\n'
				+ '	} else if (document.getElementById("frameSubfincas").style.display=="none") {\n'
				+ '		document.getElementById("txtVerSubfincas").innerHTML = "<strong>Ocultar subfincas</strong>"\n'
				+ '		document.getElementById("frameSubfincas").style.display = "block"\n'
				+ '	} else {\n'
				+ '		document.getElementById("txtVerSubfincas").innerHTML = "<strong>Ver subfincas</strong>"\n'
				+ '		document.getElementById("frameSubfincas").style.display = "none"\n'
				+ '	}\n'
				+ '}\n'
				+ '</script>\n'
				+ '</head>\n'
				+ '<body text=\"#000000\" LINK=\"#000000\" VLINK=\"#000000\" ALINK=\"#000000\">'
				+ '<table border=\"0\" cellspacing=\"0\" width=\"100%\">'
				+ '  <tr>'
				+ '    <td width=\"6\" valign=\"top\" class=\"TitulosVentanas\"></td>'
	if (parent.MapFrame.TieneInfo[parent.MapFrame.idxServicio][7])
	{
		iniHtml += '    <td width=\"60%\" align=\"left\" valign=\"bottom\" nowrap bgcolor=\"#000063\" class=\"TitulosVentanas\">&nbsp;Elemento seleccionado</td>\n'
		iniHtml += '    <td width=\"40%\" align=\"right\" valign=\"bottom\" nowrap bgcolor=\"#000063\" class=\"TitulosVentanas\"><a style="color:#ffffff" href="javascript:opener.parent.ToolFrame.printMap(#INFO#)">Imprimir consulta<img src="../media/print_blue.gif" align=absbottom border=0 hspace=2 vspace=0></a></td>\n'
	}
	else
	{
		iniHtml += '    <td width=\"100%\" align=\"left\" valign=\"bottom\" nowrap bgcolor=\"#000063\" class=\"TitulosVentanas\">&nbsp;Elemento seleccionado</td>\n'
	}
	iniHtml	+= '    <td width=\"6\" class=\"TitulosVentanas\"></td>\n'
			 + '  </tr>\n'
			 + '  <tr>\n'
			 + '    <td height=\"200\" colspan=\"3\" align=\"center\" valign=\"top\">\n'
			 + '	<div id=\"situacion\" style=\"margin-top: 8px; margin-bottom: 6px; position:relative\">\n'
			 + '	<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\">\n'
			 + '	#REGISTRO#\n'
	var finHtml = '	</table>\n'
                + '	</div>\n'
                + '	</td>\n'
                + '  </tr>\n'
	finHtml += '</table>\n'
	         + '<form name="frmBuscarSubfincas" action="../BuscarSubfincas.asp" method="post" target=frameSubfincas style="display:none">\n'
			 + '<input type=hidden name="FincaMatriz"/>\n'
			 + '<input type=hidden name="Registro"/>\n'
			 + '</form>\n'
             + '</body>\n'
             + '</html>';
	var fila = '	<tr height=\"25\">\n'
			 + '		<td width=\"40%\" valign=top><strong><font size=2>#CAMPO#</font></strong></td>\n'
			 + '		<td align=left valign=top><font size=2>#VALOR#</font>#SUBFINCAS#</td>\n'
 			 + '	</tr>\n'
			 + '	#DESC_VALOR#'
			 + '	#DESC_NUMDIVH#';
	var desc_valor = '<tr><td colspan=2 align=left valign=top>'
 			 + '<p style="margin-left:10px;font-size:9px;text-align:justify"><strong>(2) Bases gráficas validadas, color amarillo.</strong><br/>'
			 + 'La validación es una operación registral mediante la cual, el Registrador '
			 + 'afirma la coincidencia identificativa entre la base gráfica de una finca '
			 + 'registral y la descripción literaria que de la misma se hace en los libros '
			 + 'del Registro de la Propiedad. La coincidencia identificativa, en ningún caso '
			 + 'significa descripción perimetral del contorno exacto de la finca. '
			 + 'Teniendo la validación únicamente como finalidad la de poder localizar fincas '
			 + 'sobre el territorio, en ningún caso puede llegar la misma a producir efectos '
			 + 'de deslinde sobre el dominio inmobiliario inscrito en el Registro de la Propiedad.<br/>'
			 + '<strong>(0) Bases gráficas provisionales, color rojo.</strong><br/>'
			 + 'En este caso existen tales discrepancias entre la descripción gráfica de una finca '
			 + 'registral y su descripción literaria que se hace imposible proceder a la validación '
			 + 'por parte del Registrador. Sin embargo, existen indicios suficientes para sostener '
			 + 'que la representación gráfica efectuada se corresponde inicialmente con la localización '
			 + 'territorial de la finca inscrita.<br/>'
			 + '<strong>(1) Bases gráficas pendientes, color verde.</strong><br/>'
			 + 'La identificación de la base gráfica propuesta, se halla pendiente de calificar por parte del Registrador.<br>'
			 + '<strong>(99) Bases gráficas sin especificar, diferente color.</strong><br/>'
			 + 'Existen dificultades de tipo tecnológico que impiden al sistema identificar como validada, provisional o pendiente una determinada base gráfica registral.</p>'
			 + '</td></tr>';
	var desc_numdivh = '<tr><td colspan=2 align=left valign=top><p style="margin-left:10px;font-size:9px;text-align:justify">'
					 + 'Se denomina <em>Divisi&oacute;n Horizontal</em> a cada uno de los elementos (pisos, locales, garajes)'
					 + ' susceptibles de aprovechamiento independiente por tener salida propia a un elemento com&uacute;n'
					 + ' o a la v&iacute;a p&uacute;blica y que han sido inscritos como fincas independientes en el r&eacute;gimen de'
					 + ' propiedad horizontal de la construcci&oacute;n realizada sobre la finca original.</p></td></tr>';

	var vinculo = '<a href=\"#VINCULO#\" target=\"_blank\" title=\"#VALOR#\">#VALOR#</a>';

	var content = "";
	var sep = "", infoHtml = ""
	var tmp;
	var re;
	var ofReg = "";
	var NomRegistro = "";
	var fincamatriz = "";
	// empezamos en el elemento de índice 1, porque en el 0 tenemos el título de la ventana, tenga o no	
	for (i=1; i<arguments.length; i++) {
		var v = arguments[i].split("@");
		infoHtml += sep + "\'" + v[1] + "@" + v[2] + "\'"
		sep = ","
		// nos saltamos el campo FID
		if (v[0] == "RUTAMDB")
		{
			for (var k=0; k<Registro.length; k++)
			{
				if (v[2] == Registro[k][0])
				{
			 		ofReg = '	<tr>\n'
			  			  + '		<td height=40 colspan=2 align=center valign=top><strong><font size=3>' + Registro[k][1] + '</font></strong></td>\n'
 			 			  + '	</tr>\n'
					NomRegistro = v[2];
					break;
				}
			}
		}
		else if (v[0] != "FID")
		{
			tmp = v[2]; // valor
			if (tmp!="")
			{
				// comprobamos que sea campo hipervínculo
				if (v[0].toUpperCase().substr(0,6) == "HYPLNK") {
					re = /#VALOR#/g;
					tmp = vinculo.replace(re, v[2]);
					re = /#VINCULO#/g;
					tmp = tmp.replace(re, parent.MapFrame.TieneInfo[parent.MapFrame.idxServicio][3] + v[2]);
				}
				// valor del campo				
				re = /#VALOR#/g;
				if (v[0]=="TEXT")
					tmp = fila.replace(re, "<a href='https://www.registradores.org:444/propiedad/propiedad.jsp' target=_blank>" + tmp + "</a>");
				else
					tmp = fila.replace(re, tmp);
				// descriptor del campo
				re = /#CAMPO#/g;
				tmp = tmp.replace(re, v[1]);
				re = /#DESC_NUMDIVH#/g;
				if (v[0]=="TEXT") fincamatriz = v[2]
				if (v[0]=="NUM_DIVH")
				{
					if (v[2]>1)
					{
						// La finca tiene divisiones horizontales
						var s = '&nbsp;&nbsp;&nbsp;<table border=0><tr><td valign=top>'
						      + '<a id=txtVerSubfincas style="font-size:11px;color:#003399" href="javascript:BuscarSubfincas(\'' + fincamatriz + '\',\'' + NomRegistro + '\')"><strong>Ver subfincas</strong></a>&nbsp;&nbsp;</td>'
						      + '<td valign=top><iframe style="width:120px;height:150px;display:none;" frameborder=thin id=frameSubfincas name=frameSubfincas></iframe></td></tr></table>'
						tmp = tmp.replace(/#SUBFINCAS#/g, s)
					}
					else
						tmp = tmp.replace(/#SUBFINCAS#/g, "")
					tmp = tmp.replace(re, desc_numdivh);
				}
				else
				{
					tmp = tmp.replace(/#SUBFINCAS#/g, "")
					tmp = tmp.replace(re, "");
				}
				re = /#DESC_VALOR#/g;
				if (v[0]=="F_ESTADO")
					tmp = tmp.replace(re, desc_valor);
				else
					tmp = tmp.replace(re, "");
			}
			content += tmp;
		}
	}

	// descriptor del elemento
	if (arguments[0]=="") {
		var v = arguments[1].split("@");
		re = /#DESC#/g;
		tmp = iniHtml.replace(re, v[2]);
	} else {
		re = /#DESC#/g;
		tmp = iniHtml.replace(re, arguments[0]);
	}
	// Oficina registral
	tmp = tmp.replace(/#REGISTRO#/g, ofReg);
	
	// Impresión de la info más el mapa de situación
	if (parent.MapFrame.TieneInfo[parent.MapFrame.idxServicio][7])
	{
		re = /#INFO#/g
		//finHtml = finHtml.replace(re, infoHtml)
		tmp = tmp.replace(re, infoHtml)
	}

	//
	var wAncho = 550, wAlto = 235;
	var wOps = "left=" + (window.screenLeft) + ",top=" + (window.screenTop) + ",directories=no,location=no,menubar=no,status=no,toolbar=no,width=" + (wAncho) + ",height=" + (wAlto) + ",scrollbars=yes,resizable=yes";
	var oWin = window.open("", "infodetWin", wOps);
	//
	oWin.document.write("");
	oWin.document.close();
	//
	oWin.document.write(tmp + content + finHtml);
	oWin.focus();
	
}

// send  XML response to custom function
//		flow  redirected here when
//		XMLMode >=1000
function useCustomFunction(theReply) {
	if (XMLMode==1001) { // consulta de calle
		// obtenemos el envelope de la calle
		//alert(theReply);
		var env = getEnvelopeXYs(theReply, 0);
		if (env[0] == null) {
			alert('No se encontró la calle');
			return false;
		}

		// actualizamos el envelope de petición
		if (parent.MapFrame.getMapScale(env[2]-env[0])<4000) {
			// escala mínima de 1:4000
			var ancho = scale2width(4000);
			var alto = scale2height(4000);
			//eLeft = env[0] + (env[2]-env[0])/2.0 - ancho/2.0;
			//eBottom = env[1] + (env[3]-env[1])/2.0 - alto/2.0;
			eLeft = env[0] - (ancho/2.0 - (env[2]-env[0])/2.0);
			eBottom = env[1] - (alto/2.0 - (env[3]-env[1])/2.0);
			eRight = eLeft+ancho;
			eTop = eBottom+alto;
		} else {
			eLeft = env[0];
			eBottom = env[1];
			eRight = env[2];
			eTop = env[3];
		}
		
		// obtenemos la imagen
		sendToServer(imsURL, writeXML(), 1);
		
	} else if (XMLMode==1002) {
		// Obtención envelope finca registral
		var env = getEnvelopeXYs(theReply, 0);
		if (env[0] == null) {
			alert('No se localizó la finca en el mapa');
			return false;
		}

		// actualizamos el envelope de petición
		if (parent.MapFrame.getMapScale(env[2]-env[0])<3000) {
			// escala mínima de 1:4000
			var ancho = scale2width(3000);
			var alto = scale2height(3000);
			eLeft = env[0] - (ancho/2.0 - (env[2]-env[0])/2.0);
			eBottom = env[1] - (alto/2.0 - (env[3]-env[1])/2.0);
			eRight = eLeft+ancho;
			eTop = eBottom+alto;
		} else {
			eLeft = env[0];
			eBottom = env[1];
			eRight = env[2];
			eTop = env[3];
		}		
		// obtenemos la imagen
		var capaEle = parent.MapFrame.CapaFincars
		var finca = parent.herramientas.document.getElementById("oFincaMatriz").value
		var registro = parent.herramientas.document.getElementById("cboRegistro").value
		var whereEle = "REGISTRO='" + registro + "' and TEXT='" + finca + "'"
		sendMapXMLActiveX(false,null,capaEle,whereEle);
	} else {
		alert(msgList[55] + XMLMode + msgList[56]);
	}
	hideLayer("LoadData");
}

// realiza el proceso de descarga de un archivo asociado a una feature
function writeDescargaPDF(theLayer,theLayerType,theFields,leftX,bottomY,rightX,topY,maxReturned) {
	var theString = '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" envelope="false" checkesc ="true" geometry="false" featurelimit="' + maxReturned + '">\n';
	theString += '<LAYER id="' + theLayer + '" />';
	theString += '<SPATIALQUERY subfields="' + theFields + '">';
	theString += '<SPATIALFILTER relation="area_intersection" >';
	theString += '<ENVELOPE maxy="' + forceComma(topY) + '" maxx="' + forceComma(rightX) + '" miny="' + forceComma(bottomY) + '" minx="' + forceComma(leftX) + '" />';
	theString += '</SPATIALFILTER>';
	theString += '</SPATIALQUERY>';
	theString += '</GET_FEATURES>';
	theString += '</REQUEST>';
	theString += '</ARCXML>';
	return theString;
}
function doDescargar(e) {
	// mejor mediante un ASP que haga la llamada al ArcIMS y devuelva un PDF (response.BinaryWrite)
	var theString = writeDescargaPDF();
	sendToServer(imsQueryURL, theString, 1004);
}

// add custom stuff to Map XML request. . . between selection and geocode
function addCustomToMap1(){
	var customString = "";
	return customString;
}

// add custom stuff to Map XML request. . . between clickpoints and copyright
function addCustomToMap2(){
	var customString = "";
	return customString;
}

// add custom stuff to Map XML request. . . under modeOnMap
function addCustomToMap3(){
	var customString = "";
	return customString;
}

// add custom stuff to Map XML request. . . on top of everything
function addCustomToMap4(){
	var customString = "";
	return customString;
}

function getMinExtent(IdCapa, Filtro) {
	var reqXML;
	
 	reqXML  = '<ARCXML version="1.1">\n';
 	reqXML += '<REQUEST>\n';
 	reqXML += '<GET_FEATURES envelope="false" globalenvelope="true" geometry="false" attributes="false" outputmode="xml">\n';
 	reqXML += '<LAYER id="' + IdCapa + '" />\n';
 	reqXML += '<SPATIALQUERY subfields="#ALL#" where="' + Filtro + '" />\n';
 	reqXML += '</GET_FEATURES>\n';
 	reqXML += '</REQUEST>\n';
 	reqXML += '</ARCXML>';
	//alert(reqXML);
	sendToServer(imsQueryURL, reqXML, queryStreet);
}

function getImagenCalle() {
	var theString = '';
	theString = '<LAYER type="featureclass" name="' + parent.MapFrame.CapaCalles + '" visible="true" id="400">\n';
	theString    += '<DATASET fromlayer="' + getLayerID(parent.MapFrame.CapaCalles) + '" />\n';
	theString    += '<SPATIALQUERY where="' + parent.MapFrame.filtroCalle + '" />\n';
	theString    += '<SIMPLERENDERER>\n';
	theString    += '<SIMPLELINESYMBOL color="255,0,0" width="3" />\n';
	theString    += '</SIMPLERENDERER>\n';
	theString    += '</LAYER>\n';
	if (parent.MapFrame.filtroPortal != '') {
		theString    += '<LAYER type="featureclass" name="' + parent.MapFrame.CapaPortales + '" visible="true" id="410">\n';
		theString    += '<DATASET fromlayer="' + getLayerID(parent.MapFrame.CapaPortales) + '" />\n';
		theString    += '<SPATIALQUERY where="' + parent.MapFrame.filtroCalle + ' AND ' + parent.MapFrame.filtroPortal + '" />\n';
		theString    += '<SIMPLERENDERER>\n';
		theString    += '<SIMPLEMARKERSYMBOL color="255,255,255" outline="0,0,255" transparency="1.0" width="8" />\n';
		theString    += '</SIMPLERENDERER>\n';
		theString    += '</LAYER>\n';
	}
	//alert('getImagenCalle(): ' + theString);
	return theString;
}

function getLayerID(capa) {
	for (i=0; i<parent.MapFrame.LayerName.length; i++) {
		if (parent.MapFrame.LayerName[i].toUpperCase() == capa.toUpperCase()) {
			//alert("Capa '" + capa + "' de ID " + parent.MapFrame.LayerID[i]);
			return parent.MapFrame.LayerID[i];
		}
	}
	return -1;
}

function getLayerIdx(capa) {
	for (i=0; i<parent.MapFrame.LayerName.length; i++) {
		if (parent.MapFrame.LayerName[i].toUpperCase() == capa.toUpperCase()) {
			return i;
		}
	}
	return -1;
}

function getScaleFactor(newScale, monitorInches) {
	// Devuelve el factor de escala necesario para calcular
	// las dimensiones del mapa para la escala newScale
	var ppi = screen.width / monitorInches;
	var cte = 39.3701; // 100/2.54 (pulgadas por metro)
	return(newScale / (ppi * cte)); // factor de escala: metros por pixel
}

function getMapScale(new_xDistance, new_yDistance) {
	// returns the current map scale if the map units are not decimal degrees
	// (approximation only, because the actual pixels per inch value 
	// used internally by ArcIMS is unknown)
	var MapScale = 0.0;
	var MapWidthInUnits = (new_xDistance==null)?parent.MapFrame.xDistance:new_xDistance;
	//var ppi = screen.width / 19;
	//var ppm = ppi * 39.3701;

	switch (parent.MapFrame.MapUnits.toUpperCase()) {
		//case aims.imsMapUnits.imsCentimeters
		//	MapScale = MapWidthInUnits / (iWidth / dPixelsPerCentimeters)
		//	break;
		//case aims.imsMapUnits.imsDecimalDegrees
			// not implemented
		//	MapScale = 0.0
		//	break;
		case "FEET":
			MapScale = MapWidthInUnits / (iWidth / dPixelsPerFeet);
			break;
		//case aims.imsMapUnits.imsInches
		//	MapScale = MapWidthInUnits / (iWidth / dPixelsPerInches)
		//case aims.imsMapUnits.imsKilometers
		//	MapScale = MapWidthInUnits / (iWidth / dPixelsPerKilometers)
		case "METERS":
			MapScale = MapWidthInUnits / (iWidth / dPixelsPerMeters);
			//alert(MapScale + " vs " + MapWidthInUnits/(iWidth/ppm) + " (*)");
			break;
		//case aims.imsMapUnits.imsMiles
		//	MapScale = MapWidthInUnits / (iWidth / dPixelsPerMiles)
		//	break;
		default:
			MapScale = 0.0;
	}
	return MapScale;
}

function scale2width(Escala) {
	var MapW = 0.0;

	switch (parent.MapFrame.MapUnits.toUpperCase()) {
		case "FEET":
			MapW = Escala * (iWidth / dPixelsPerFeet);
			break;
		case "METERS":
			MapW = Escala * (iWidth / dPixelsPerMeters);
			break;
		default:
			MapW = 0.0;
	}

	return MapW;
}

function scale2height(Escala) {
	var MapH = 0.0;

	switch (parent.MapFrame.MapUnits.toUpperCase()) {
		case "FEET":
			MapH = Escala * (iHeight / dPixelsPerFeet);
			break;
		case "METERS":
			MapH = Escala * (iHeight / dPixelsPerMeters);
			break;
		default:
			MapH = 0.0;
	}

	return MapH;
}

function escalarMapa(Escala) {	
	// para zoomScale(), el parámetro va de 0.0 a 1.0
	/*zoomScale(Escala);*/

	var mW = scale2width(Escala);
	var mitadX = mW / 2.0;
	var mH = scale2height(Escala);
	var mitadY = mH / 2.0;
	
	var minx = (eLeft + (parent.MapFrame.xDistance/2.0)) - mitadX;
	var maxx = minx + mW;
	var miny = (eBottom + (parent.MapFrame.yDistance/2.0)) - mitadY;
	var maxy = miny + mH;
 	
	zoomToEnvelope(minx, miny, maxx, maxy)
}

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
	//	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 centrarPunto(x, y, Escala, drawIt, theLabel) {
	// ancho del mapa para la escala especificada
	var mW = Escala * (iWidth/dPixelsPerMeters);
	var mitadX = mW / 2.0;
	// alto del mapa para la escala especificada
	var mH = Escala * (iHeight/dPixelsPerMeters);
	var mitadY = mH / 2.0;

	saveLastExtent();
	
	eLeft = x - mitadX;
	eRight = eLeft + mW;
	eBottom = y - mitadY;
	eTop = eBottom + mH;
 	
	if (drawIt) {
		VML_minX = eLeft;
		VML_minY = eBottom;
		VML_maxX = eRight;
		VML_maxY = eTop;
		var coordorigin = VML_maxY-VML_minY;
		var coordsizeX = VML_maxX-VML_minX;
		var coordsizeY = VML_maxY-VML_minY;
		GeometriaVML = "<v:shapetype id='ref' strokecolor='#ff0000' fillcolor='#ff0000' strokeweight='1.5pt'/>"
		             + "<v:group id=g0 style='visibility:visible;position:absolute;top:0;left:0;width:" + iWidth + ";height:" + iHeight + "' coordorigin='0 0' coordsize='" + iWidth + " " + iHeight + "'>"
					 + "<v:oval type='#ref' style='width:5;height:5;top:" + parseInt(iHeight/2) + ";left:" + parseInt(iWidth/2) + "'><v:fill opacity='1'/></v:oval>"
					 + "</v:group>";
		showGeocode=true;
		/*geocodeX=x;
		geocodeY=y;
		geocodeLabel=theLabel;*/
	}
	sendMapXMLActiveX();
}

function ocultarGeometria(hideIt) {
	if (theGeom != null && theGeom.all("g0") != null)
		theGeom.all("g0").style.visibility = (hideIt) ? "hidden" : "visible";
}

function eliminarGeometria() {
	parent.MapFrame.GeometriaVML = "";
	if (theGeom != null && theGeom.all("g0") != null)
		theGeom.innerHTML = "";
}

function isGeometriaVisible() {
	if (theGeom != null && theGeom.all("g0") != null)
		return (theGeom.all("g0").style.visibility == "visible");
	else
		return false;
}

function eliminarMedidas() {
	if (ElementosDeMedida>0) {
		if (document.getElementById('nr' + ElementosDeMedida)!=null) document.getElementById('nr' + ElementosDeMedida).removeNode(true);
		if (document.getElementById('forma')!=null) document.getElementById('forma').removeNode(true);
	}
	ElementosDeMedida = 0;
	MeasureVML = defaultMeasureVML;
}

function pendingRequest() {
	var t = parent.MapFrame;
	if (!t.okToSend || !t.mapLoaded) {
		alert(t.msgList[10]);
		return true;
	}
	else
		return false;
}

function disableGUI(flag) {
	if (parent.herramientas.oServicios!=null) parent.herramientas.oServicios.disabled = flag;
}

function ocultarMedidas() {
	if (hasLayer("measureBox") || hasLayer("areaBox")) {
		clearSelection();
		if (hasLayer("measureBox")) hideLayer("measureBox");
		if (hasLayer("areaBox")) hideLayer("areaBox");
	}
}

/* limpia la actual seleccion */
function clearSelection() {
	showGeocode=false;
	clickCount=0;
	totalMeasure=0;
	totalArea=0;
	currentMeasure=0;
	if (toolMode==20) {
		eliminarMedidas();
		updateMeasureBox();
	} else if (toolMode==1020 /*|| toolMode==1030*/) {
		eliminarMedidas();
		updateAreaBox();
	}
}

/*************************/
/* Consulta de productos */
function consultarProductos(izquierda, abajo, derecha, arriba) {
	/*var pad = document.getElementById('nr' + ElementosDeMedida);
	var l = MeasureVML.indexOf("l");
	var c = MeasureVML.substring(l+1).split(",");	
	if (c.length<6) {
		alert("Seleccione al menos tres puntos");
		return;
	}
	var coords = "";
	var sep = "";
	for (i=0;i<c.length;i+=2) {
		getMapXY(parseInt(pad.style.left) + Math.abs(c[i]), parseInt(pad.style.top) + Math.abs(c[i+1]));
		coords += sep + parseInt(mapX) + "%20" + parseInt(mapY);
		sep = ";";
	}*/
	coords = parseInt(izquierda) + "%20" + parseInt(abajo) + ";"
	       + parseInt(derecha) + "%20" + parseInt(abajo) + ";"
		   + parseInt(derecha) + "%20" + parseInt(arriba) + ";"
		   + parseInt(izquierda) + "%20" + parseInt(arriba);
	//alert(coords);
	// realizamos la consulta
	var xmlhttp;
	if (typeof XMLHttpRequest == "object") 
		xmlhttp = new XMLHttpRequest();
	if (typeof ActiveXObject == "object" || typeof ActiveXObject == "function") 
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	if (xmlhttp) {
		xmlhttp.open("POST", "pedidos/consprod.asp", true);
		// tratamiento asíncrono de la llamada
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				//obj.hideShow();
				var wped = window.open("", "", "menubar=no,status=no,toolbar=no,location=no,width=500,height=400,left="+parseInt(window.screenLeft+iWidth/2)+",top="+parseInt(window.screenTop-iHeight/2)+",scrollbars=no,resizable=no");
				if (!lockedPopups(wped, true)) {
					wped.focus();
					if (xmlhttp.status == 200) {
						wped.document.write(xmlhttp.responseText);
					} else
						wped.document.write(xmlhttp.responseText);
				}
				hideRetrieveMap();
			}
		}
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		var content = "coords=" + coords;
		showRetrieveMap();
		xmlhttp.send(content);
	}
}
function ocultaAreaConsulta() {
	hideLayer("zoomBoxTop");
	hideLayer("zoomBoxLeft");
	hideLayer("zoomBoxRight");
	hideLayer("zoomBoxBottom");
}
/* Consulta de productos */
/*************************/
