// aimsSitmap.js
/*
*  Sitmap functions and variables 
*/

		// sitmap
		var sitmapTocIndex = -1;               // almacena el índice de la última seleccionada
		var aimsLabelPresent = new Array();
		var aimsEscalaPresent=false;
		var sitmapMeasureEnabled = false;
		var sitmapTamanoGrande = false;
		var aimsTOCPresent=true;
		var aimsShowFotos=false;
		var aimsShowPdf=false;
		var sitmapShowServiceClicked=false;
		var sitmapTitle = "";
		var sitmapIDFirstLayerNivelTerritorial = 0;
		var sitmapIDLastLayerNivelTerritorial = 0;
		var sitmapIDFirstLayerCartografia = 0;
		var sitmapIDLastLayerCartografia = 0;
		var sitmapCodTemas = new Array();
		var sitmapCodGrupoTemas = new Array();
		var sitmapPendienteTips = false;
		var sitmapRootUrl = sitmapGetRootUrl();
		var sitmapPreviousActiveLayer = -1;
		var sitmapParams = top.document.location.search;
		var sitmapParamsUC = sitmapParams.toUpperCase();
		var sitmapInitUrl = top.document.location.href;
		var sitmapEscalaSeleccionada = false;
		var sitmapFirstActiveLayerID = 0;
		var sitmapVistaIdentificacion = "";
	  var sitmapVistaGeneral = "";	    
	  var sitmapMostrarListado = false;
	  var closing = false;
	  
		var sitmapLabelListFields = "";   // campos para seleccionar la etiqueta a mostrar (también los tips)
		var sitmapSearchListFields = ""; // campos que deben aparecer en las listas de búsqueda

		var sitmapDimensionesListados = ""; // almacena el ANCHO, ALTO, CAMPO1, CAMPO2, ..., CAMPON de la ventana de LISTADO (píxeles). 
											// con el formato: ancho, alto, campo1, ..., campo2
		var sitmapDimensionesIdentificacion = ""; // introducir el ANCHO y ALTO de la ventana de IDENTIFICACION (píxeles).
												  // Formato: ancho, alto
		var sitmapDimensionesNiveles = ""; // introducir el ANCHO y ALTO de la ventana de NIVELES (píxeles).
										   // Formato: ancho, alto
		var sitmapFilterListFields = ""; // campos que deben aparecer en la página de Filtro
		var sitmapRenderListFields = ""; // campos que deben aparecer en la página de Render (Temáticos)
		var sitmapShowService = "";			 // indica si la capa activa puede mostrar el popup de servicios
		
		var sitmapTocCartografia = false; // indica si se ha seleccionado la pestaña de cartografía en el TOC
		var sitmapOrtoVisible = false; // indica si las capas de ortofotos están visibles
		var sitmapCartoVisible = false; // indica si las capas de cartografía están visibles
		
		var sitmapCatalogo = false; // indica si se ha cargado el catálogo
		var sitmapPrinting = false; // indica si se ha lanzado una petición para impresión
		var sitmaptop = top; // carga el top
		var sitmapMaxFactorDownloadCartografia = 6; // factor de escala para la descarga de cartografia
		var sitmapTieneWms = false;
		var sitmapWmsChecked = false;
		
		// verano: variables para almacenar los valores de identificación y fotos para el listado 
		var sitmapListadoCodes = new Array();
		var sitmapListadoShapes = new Array();
		var sitmapListadoItemNames = new Array();
		var sitmapListadoEnvelopes = new Array();
		var sitmapListadoSdeTable = "";
		
		// verano: grid
		var sitmapDrawGrid = false;
		var sitmapGridDesde = new Array();
		var sitmapGridHasta = new Array();
		var sitmapGridOffset = new Array();
		
		// indica si los tips se han cargado
		var sitmapTipsLoaded = false;
		
		// descarga: carga un array con las capa indicando si se permite la descarga
		var sitmapLayerDescarga = new Array();
		

	// begin tips settings
	//==========================================================
	// uses aimsCustom.js, aimsNavigation.js-mouseStuff(), toc.aspx,
	// TipFrame.aspx, toolbar.htm(clearTips button)
	//
	// Tips are activated through the legend, if a layer is invisible then one 
	// cannot load the tips for that layer.
	//
	// Tips works with Point and Polygon data
	//
	var useTips = true;           // controls clear tips on toolbar
	var TipsLayerID = -1;         // set from toc.aspx
	var TipsField = new Array();  // set in toc.aspx
	var sitmapTips = new Array(); // almacena todos los tips
	var TipsX = new Array();      // stores the X coordinates
	var TipsY = new Array();      // stores the Y coordinates
	var TipsMinX = new Array();      // stores the X coordinates
	var TipsMinY = new Array();      // stores the Y coordinates
	var TipsMaxX = new Array();      // stores the X coordinates
	var TipsMaxY = new Array();      // stores the Y coordinates
	var TipsValues = new Array(); // stores the strings
	//==========================================================
	// end tips settings 

		// zoom history
		var sitmapUseZoomHistory=false; 
		var sitmapZoomHistoryPresent=false; 
		
	// DDE (AÑADIDO EL 18 ENE 2006
	var useDDE = true;
	var ddeSpatialQuery = new Array(); // array que almacena los filtros de todas las capas
	function ddeExport() {
	    if (sitmapCatalogo) {
            if (ctlgEsCartografia) {
                // debemos comprobar la escala: si supera 1:1000 (factor < sitmapMaxFactorDownloadCartografia) descargamos de la retícula
                if (mapScaleFactor >= sitmapMaxFactorDownloadCartografia) {
                    // al ser de una escala mayor descargamos de la retícula asociada a la capa de cartografía
		            alert("Debe acercarse a la zona donde se encuentra la cartografía vectorial que desea descargarse");
		            return;
			     }
            } 	    
	        var fmeWin = window.open("../common/ctlgDdeDownload.aspx?t=" + ctlgTipoCartografia + "&minx=" + eLeft + "&miny=" + eBottom + "&maxx=" + eRight + "&maxy=" + eTop,"DDEDownload","width=550,height=500,top=20,left=20,scrollbars=no,resizable=no");
	    } else {
    	    var fmeWin = window.open("../common/ddeDownload.htm","DDEDownload","width=550,height=500,top=20,left=20,scrollbars=no,resizable=no");
    	}
    	return true;
	}
	// fin DDE
		
		// obtiene el valor de un parámetro de la url
		function sitmapGetParam(param) {
		
			var tmp1 = top.document.location.search; 
			var str = tmp1.toUpperCase();
			var startpos;
			var endpos;
			var item = "";
			var pos = str.indexOf("&" + param.toUpperCase() + "=");
			if (pos==-1) {
				pos = str.indexOf("?" + param.toUpperCase() + "=");
			}
			if (pos != -1) {
				startpos = pos + param.length + 1;
				endpos = str.indexOf("&",startpos);
				if (endpos==-1) endpos = tmp1.length;
				item = tmp1.substring(startpos+1,endpos);
			}
			return item;
		}
		
		// establece el campo por el que hay que filtrar dependiendo del nivel territorial
		function sitmapGetCodNivelTerritorial() {
			var level = sitmapGetParam("l");
			var value = "";
			switch(level) {
				case "p": // provincia
					value = "";
					break;
				case "c": // comarca
					value = "COD_COMARC";
					break;
				case "m": // municipio
					value = "COD_MUN";
					break;
				case "n": // nucleo
					value = "COD_NUCLEO";
					break;
			}
			return value;
		}
		
		
		
		
		// enlaza con la página de datos alfanuméricos
		function sitmapDatosAlfanumericos() {
			if (checkIfActiveLayerAvailable()) {
				var nivelterritorial = sitmapGetParam("l");
				var code = sitmapGetParam("c");
				var tema = sitmapCodTema;
				var url;
				var terriCode;
				var terriTema;
				var territorio;
				
				switch(nivelterritorial) {
				case "p": // provincia
					terriCode = "";
					terriTema = "PROVINCIA";
					break;
				case "c": // comarca
					terriCode = code.replace(/'/g, "");
					terriTema = "COMARCA";
					break;
				case "m": // municipio
					terriCode = code.substr(2);
					terriTema = "MUNICIPIO";
					break;
				case "n": // nucleo
					terriTema = "COD_NUCLEO";
					terriCode = code;
					break;
			}
				territorio=parent.title;
				// url="http://www.dipmalaga.es/sitmapweb_alfa/inicio2.asp?Claves="+ terriCode +"&TipoTerri="+ terriTema +"&CodTabla="+ tema +"&Territorio="+ territorio;
        // url = "/alfanet/Redirect.aspx?Claves="+ terriCode +"&TipoTerri="+ terriTema +"&Territorio="+ territorio + "&CodTema=" + tema;
		url = "../AlfaRedirect.aspx?c=" +code+ "&t=" + territorio + "&Claves="+ terriCode +"&TipoTerri="+ terriTema +"&Territorio="+ territorio + "&CodTema=" + tema;
				window.open(url, 'alfanumerico1','width=1000,height=700,top=0,left=0');				
				
			}
		}
		

	// recuperamos la url inicial, sin los parámetros "layers", "box" ni las extensiones iniciales
	function sitmapGetStartUrl() {
		var v = sitmapParams.split("?");
		var p = v[1].split("&");
		var name = "";
		var val = "";
		var url = "?";
		var pos;
		var sbstr;

		for (var i=0;i<p.length; i++) {
			sbstr = p[i];
			pos = sbstr.indexOf("=");
			name = sbstr.substring(0,pos);
			val  = sbstr.substring(pos+1, sbstr.length);
			nameu = name.toUpperCase();

			switch(nameu) {
				case "BOX":
				case "LAYERS":
				case "STARTLEFT":
				case "STARTRIGHT":
				case "STARTTOP":
				case "STARTBOTTOM":
				case "QUERYZOOM":
					break;
				case "QUERY":
					
					if (url != "?") url += "&";
					url = url + (name + "=" + sitmapGetParamQuery());
					break;
				default:
					if (url != "?") url += "&";
					url += name + "=" + val;
					break;
			}
		}
		return url;
	}		
		
	// indica si el servicio ArcIMS que se está lanzando es el servicio de Sitmap
	function sitmapIsAService() {
		return (getService(imsURL).toUpperCase().indexOf("SITMAP_SERV") >= 0);
	}

	// formatea una cantidad poniéndole puntos de separación de miles
	function sitmapAddDots( strValue ) {
		strValue = new String(strValue);
	  var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})');

	    //check for match to search criteria
	    while(objRegExp.test(strValue)) {
	       //replace original string with first group match,
	       //a dot, then second group match
	       strValue = strValue.replace(objRegExp, '$1.$2');
	    }
	  return strValue;
	}	
	
	// función que pone activa una capa
	function sitmapSetTocActiveLayer(i) {
		var  theForm = document.forms[0];
		ActiveLayer=LayerID[i];
		ActiveLayerType=LayerType[i];
		ActiveLayerIndex=i;
		setActiveLayer(i);
		var isOk = checkHyperLinkLayer(i);
		if (toolMode==15) {
				
			if (!isOk) {
				currentHyperLinkLayer="";
				currentHyperLinkField="";
				currentHyperLinkPrefix="";
				currentHyperLinkSuffix="";
				alert(t.msgList[47]);
			
			}
		}
	}
	
	// función que actualiza el desplegable de capas activas
	function sitmapUpdateActiveLayerCombo(obj) {

		obj.options.length = 0;
		var activeLayerVisible = false;
		obj.options[0] = new Option("Seleccione:","");

		var optIndex = 1;
		var lastComboItem = 0;

		if (ActiveLayer == "") ActiveLayer = -1;
		for (var i=sitmapIDFirstLayerNivelTerritorial;i<=sitmapIDLastLayerNivelTerritorial;i++){
			if (LayerVisible[i] == 1) {
			    // si estamos en el catálogo, activamos la última seleccionada
				if (sitmapCatalogo && ctlgTocIndex >= 0) { 
				    ActiveLayerIndex = ctlgTocIndex;
				 }
				 // si estamos en el sitmap, activamos la última seleccionada
				if (!sitmapCatalogo && sitmapTocIndex >= 0) { 
				    ActiveLayerIndex = sitmapTocIndex;
				 }
				 
				// la ponemos seleccionada si sigue visible
				if (i == ActiveLayerIndex) {
					activeLayerVisible = true;
					lastComboItem = optIndex;
				}
				obj.options[optIndex] = new Option(LayerName[i],i);
				optIndex++;
			}
		}
		// seleccionamos el elemento adecuado
		if (lastComboItem == 0 && obj.options.length>0) lastComboItem++;
		if (lastComboItem + 1 > obj.options.length) lastComboItem = 0;
		obj.selectedIndex = lastComboItem;
		// si la capa activa no está visible, activamos la última capa visible
		ActiveLayer = LayerID[obj.options[obj.selectedIndex].value];
		// si la capa activa es nueva, la activamos 
		if (sitmapPreviousActiveLayer != ActiveLayer) {
			sitmapSetActiveLayer(obj);
		}
		sitmapPreviousActiveLayer = ActiveLayer;

		// actualizamos el buttom frame		
		writeBottomFrame();

	}
	
	// activa la capa seleccionada	
	function sitmapSetActiveLayer(obj) {
	    
			if (obj.selectedIndex ==0) return;
			var id = obj.options[obj.selectedIndex].value;

            // actualizamos el índice del catálogo
            if (sitmapCatalogo){
             ctlgTocIndex = id;
             }
              // actualizamos el índice del sitmap
            if (!sitmapCatalogo){
             sitmapTocIndex = id;
             }
			sitmapSetTocActiveLayer(id);
			parent.TOCFrame.setDataLayer(id);
			sitmapCodGrupoTema = sitmapCodGrupoTemas[id];
			sitmapCodTema = sitmapCodTemas[id];
			sitmapPreviousActiveLayer = id;
			// mostramos los tips
					
			if (!okToSend) // si no podemos pedir los tips, marcamos la petición
				sitmapPendienteTips = true;
			else 
				showTips();
	}
	
	// almacena el directorio virtual raíz de la aplicación
	function sitmapGetRootUrl() {
		var path = document.location.pathname;
		var i=-1;
		if ((i = path.toLowerCase().indexOf("sitmap_provincia")) >= 0) url = path.substr(0,i);
		if ((i = path.toLowerCase().indexOf("sitmap_comarcas")) >= 0) url = path.substr(0,i);
		if ((i = path.toLowerCase().indexOf("sitmap_municipios")) >= 0) url = path.substr(0,i);
		if ((i = path.toLowerCase().indexOf("sitmap_nucleos")) >= 0) url = path.substr(0,i);
		if ((i = path.toLowerCase().indexOf("sitmap_servicios")) >= 0) url = path.substr(0,i);
		if ((i = path.toLowerCase().indexOf("sitmap_catalogo")) >= 0) url = path.substr(0,i);
		
		return url;
	}
	
	
	// función que formatea los campos de sde.
	function sitmapFormatSdeFields(field) {
		return field.replace(/_/g, " ");
	}
	
	
	// obtiene la consulta inicial que aparece en la url (query=)
	function sitmapGetParamQuery() {
		var escQuery = sitmapGetParam("query");  //escQuery es  igual a (p, m, n, c	)
		var query = "";
		if (escQuery != "") {
			escQuery = replacePlus(escQuery);
			escQuery = unescape(escQuery);
			query = makeXMLsafe(escQuery);
			escQuery="";
		}	
		
		return query;
	}


//******************************************************************************************
// check whether user has zoomed in past minimum extent
//******************************************************************************************
function sitmapCheckMinimumExtent() {
	//alert ("[function checkMinimumExtent]");
	if (enforceMinimumExtent) {
		// get size of current extent
		var currentWidth = eRight - eLeft;
		var currentHeight = eTop - eBottom;
		var centerX = eRight - (currentWidth / 2);
		var centerY = eTop - (currentHeight / 2);
		// if necessary, limit width and height
		if ((currentWidth<minimumWidth) || (currentHeight<minimumHeight)) {
			if (debugOn>3) alert ("[function checkMinimumExtent]\n\nEnforcing minimum extent!");
			// redefine resized extent around current center
			eLeft = centerX - (minimumWidth / 2);
			eRight = centerX + (minimumWidth / 2);
			eBottom = centerY - (minimumHeight / 2);
			eTop = centerY + (minimumHeight / 2);
		}
	}
} // end of function checkMinimumExtent
//------------------------------------------------------------------------------

//******************************************************************************************/
// SPATIAL QUERY: filtra por las consultas por nivel territorial
//******************************************************************************************/

function sitmapAddSpatialQuery(i, subfields, find) {

		// buscamos el campo que define el nivel territorial
		var nivelterritorial = sitmapGetCodNivelTerritorial();
		
		var j;		
		var str = "";
		var tmp1 = "";
		var found = false;
		
		if (sitmapCatalogo && LayerID[i].indexOf("wms")>=0) {
			tmp1 = "1=1"; 
		} else {
			var flds = LayerFieldList[i].split(',');
			for (j=0; j<flds.length; j++) {
			  if (flds[j].indexOf(nivelterritorial) >= 0) {
					if (!sitmapEsProvincia()) {
						// si no el codigo no lleva comillas se lo ponemos
						if (sitmapcode.indexOf("\'")<0) {
							sitmapcode = "\'" + sitmapcode + "\'";
						}
					}
					tmp1 =  nivelterritorial + '=' + sitmapcode;
					found = true;
				}
			}
		}
		
		//var flds = LayerFieldList[i].split(',');
		//for (j=0; j<flds.length; j++) {
		// if (flds[j].indexOf(nivelterritorial) >= 0) {
		//		// si no el c'odigo no lleva comillas se lo ponemos
		//		if (sitmapcode.indexOf("\'")<0) {
		//			sitmapcode = "\'" + sitmapcode + "\'";
		//		}
		//		tmp1 =  nivelterritorial + '=' + sitmapcode;
		//		found = true;
		//	}
		//}



		// OJO: ponemos una condición falsa para todos los 
		// niveles territoriales excepto para la provincia
		// cuando no encuentre el campo de filtrado así como cuando se trata de una capa "no inicial (>1)"
		if (sitmapEsProvincia()) tmp1 = "1=1";
		if (!found && !sitmapEsProvincia() && i>1 && i<sitmapIDFirstLayerCartografia) tmp1 = "1=2"; 
		
		// DDE modificación del 18 ene 2006 (se sustituye un trozo de código por el otro
		if (tmp1 != "" ) { 
				if (sitmapQueryString[i] != undefined) {
					if (sitmapQueryString[i] != "") {
						tmp1 = tmp1 + ' AND (' + parseEntity(swapQuotes(sitmapQueryString[i])) + ')';
					}
				}
				// vemos si tengo estoy realizando una consulta
				if (find && sitmapFindString!="") {
					tmp1 = tmp1 +  " AND (" + sitmapFindString + ")";
				} else {
					tmp1 = makeXMLsafe(tmp1);
				}		
				str = subfields + ' where="' + tmp1 + '"';
		}
		// dde: guardamos los filtros de las capas
		if (subfields == "") {
    		ddeSpatialQuery[i] = tmp1;
        }
		//DDE FIN MODIFICACION
		
		return str;
}

// indica si la capa activa está filtrada
function sitmapIsActiveLayerFiltered(){
	if (sitmapQueryString[ActiveLayerIndex] != undefined) {
		if (sitmapQueryString[ActiveLayerIndex] != "") {
			return true;
		}
	}
	return false;
}

//******************************************************************************************
// LABELS: muestra las etiquetas para la capa activa.
//******************************************************************************************
function sitmapAddLabelsRender(i) {
		var str = "";
		if (TipsField[i] != "") {
			str += '	<SIMPLELABELRENDERER field="'+ TipsField[i] + '">\n';
			str += '		<TEXTSYMBOL antialiasing="true" font="Arial" fontstyle="regular" fontsize="10" />\n';
			str += '	</SIMPLELABELRENDERER>\n';
		}		
		return str;
}

function sitmapAddSimpleRender(i) {
	return LayerSimpleRenderString[i];	
}

function sitmapAddSimpleLabelRender(i) {
	return LayerSimpleLabelRenderString[i];	
}


//******************************************************************************************
// sitmapShowLabels: muestra las etiquetas para la capa activa.
//******************************************************************************************
//if (sitmapMeasureEnabled) {
//		 setToolPic('Measure');
//		 clickFunction('measure');
//	} else {
//		// limpiamos la selección
//		clickFunction('clearsel');
//		// activamos el botón de zoomin
//		clickFunction('zoomin'); 
//		setToolPic('Zoom In');
//	}

function sitmapShowLabels() {
	if (checkIfActiveLayerAvailable()) {
	    
		// indicamos que vamos a mostrar etiquetas y hacemos la petición 
		if (aimsLabelPresent[ActiveLayerIndex] != null) {
			aimsLabelPresent[ActiveLayerIndex] = !aimsLabelPresent[ActiveLayerIndex]; // mostramos la opción contraria
			

		} else {
			aimsLabelPresent[ActiveLayerIndex] = true;
			
		}	
		
		
			
    	sendMapXML();
	}
}
//******************************************************************************************
// sitmapTips: muestra los tips para la capa activa.
//******************************************************************************************
var layertype;
var layerIsScaled = false;

function showTips() {
	var t = parent.MapFrame;
	// si no hay definido ningún campo, no lanzamos los tips. Tampoco lo lanzamos si es un wms
	if (TipsLayerID.indexOf("wms")>=0){
		// definimos la extensión de la capa
		t.LayerExtent[t.ActiveLayerIndex] = t.fullLeft + "|" + t.fullBottom + "|" + t.fullRight + "|" + t.fullTop;
		return ;
	}
	if (TipsField[TipsLayerID] == "") {
		// definimos la extensión de la capa
		t.LayerExtent[t.ActiveLayerIndex] = t.fullLeft + "|" + t.fullBottom + "|" + t.fullRight + "|" + t.fullTop;
		return;
	}

	// parent.MapFrame.sitmaptop.TipFrame.document.location = sitmapRootUrl + "common/TipFrame.aspx";
	showRetrieveData();
    layertype = parent.MapFrame.LayerType[parent.MapFrame.ActiveLayerIndex];
	// ponemos la petición de los Tips falsa, a la espera de la carga
	sitmapTipsLoaded = false;
	sendTipsRequest(layertype, layerIsScaled);
}


//******************************************************************************************
// sitmapShowServiceMap: abre un popup en las capas de servicios
//******************************************************************************************
function sitmapShowServiceMap(query) {
		var url = "../SITMAP_servicios/viewer.htm?Query=" + query + "&ActiveLayer=1&Layers=11&l=m&c="+sitmapcode + "&queryzoom=yes"; // ponemos el nivel territorial de municipios (l=m)
		var w = window.open(url,"SITMAP_servicios","width=400,height=250,top=20,left=20,scrollbars=yes,toolbars=yes,resizable=yes");
//		var w = window.open(url,"SITMAP_servicios");
		w.focus();
}

// función que se lanza cuando el usuario selecciona alguna opción del menú 
// entre "identificar, fotos, pdf o presta servicio a"
function sitmapIdentifyClick(opt) {
    aimsShowPdf=false;
	aimsShowFotos=false;	
	switch(opt) {
		case "Fotos":
			aimsShowFotos=true;		
		case "Pdf":
			aimsShowPdf=true;	
			break;
	}
	clickFunction("identify");
		
	setToolPic(opt);
}

// muestra el listado de las características de la capa activa
function sitmapShowList(){
	if (checkIfActiveLayerAvailable()) {
		// debemos analizar si hay una vista definida para la identificación
		if (!sitmapIsListEnabled()) {
				var w = open(appDir + '../common/notenabled.aspx?t=l','NotEnabled','width=400,height=250,top=20,left=20,scrollbars=yes,resizable=yes');
				window.close();
				w.focus();
		} else {
			toolMode=1;
			queryStartRecord=1;
			sitmapMostrarListado = true;
			getFind(sitmapcode);
			setToolPic("Zoom In");
		}
	}
}


// indica si una capa pertenece al grupo de capas que no se deben tocar
// en la construcción del AXL
// Las capas fijas tienen en los AXL el formato id="fixed#10"
function sitmapIsAMasterLayer(layerIdIndex){
    return (LayerID[layerIdIndex].indexOf("fixed#") >=0);
}

// función que indica si estamos en el nivel territorial de provincia
function sitmapEsProvincia(){
	return sitmapGetCodNivelTerritorial() == "";
}

// comprueba si hay datos definidos en WEB_SDE para mostrar etiquetas
function sitmapLabelEnabled(){
	return (sitmapLabelListFields != "");
}


// comprueba si podemos lanzar el render en base a que haya campos definidos
function sitmapIsRenderEnabled(){
	return (sitmapRenderListFields != "");
}

// comprueba si hay datos definidos en WEB_SDE para realizar un filtro
function sitmapIsFilterEnabled(){
	return (sitmapFilterListFields != "");
}

// comprueba si hay datos definidos en WEB_SDE para mostrar el listado
function sitmapIsListEnabled(){
	return (sitmapSearchListFields != "");
}

// comprueba si hay datos definidos en WEB_SDE para mostrar el listado
function sitmapIsVistaIdentificacionEnabled(){
	return (sitmapVistaIdentificacion != "");
}

// comprueba si hay datos definidos en WEB_SDE para mostrar el listado
function sitmapIsVistaGeneralEnabled(){
	return (sitmapVistaGeneral != "");	    
}


// función que cierra todos los popups
function sitmapCloseWindows() {
		var i=0;
		var windows = new Array();
		windows[i]   = "PopupForm";
		windows[i++] = "QueryWindow";
		windows[i++] = "RenderWindow";
		windows[i++] = "DataWindow";
		windows[i++] = "DataWindowFotos";
		windows[i++] = "DataListWindow";
//		windows[i++] = "PrintPage";
//		windows[i++] = "LayerListWindow";
//		windows[i++] = "SITMAP_servicios";
//		windows[i++] = "limiteClases";
//		windows[i++] = "ZoomHistoryDumpWindow";
		
		for (var j=0;j<windows.length;j++){
			var w = window.open(appCommon + "blank.htm", windows[j],"width=100,height=100,position=absolute,top=3000px,left=3000px");
			w.close();
		}
}

// obtiene las coordenadas mínimas y máximas de todas las características (se utiliza en el popup de "presta servicio a")
function sitmapGetEnvelopeXYs(theReply) {
  // alert(theReply);
	var theEnvelope = new Array();
  featureCount = justGetFeatureCount(theReply);
  hasEnvelopes = (theReply.indexOf("<ENVELOPE minx=") > -1);
  spos = 0;
  epos = 0;

	var minx = 0;
	var miny = 0;
	var maxx = 0;
	var maxy = 0;

	var tmpminx = 0;
	var tmpminy = 0;
	var tmpmaxx = 0;
	var tmpmaxy = 0;  

  // derive x and y from bounding box centroid
  xmlEndPos = 0;
  
  for (i=0; i<featureCount; i++) {
    theEnvelope = getEnvelopeXYs(theReply, xmlEndPos);
		tmpminx = theEnvelope[0];
		tmpminy = theEnvelope[1];
		tmpmaxx = theEnvelope[2];
		tmpmaxy = theEnvelope[3];
    
    if (minx==0 || tmpminx  < minx) minx = tmpminx;
    if (miny==0 || tmpminy  < miny) miny = tmpminy;
    if (maxx==0 || tmpmaxx  > maxx) maxx = tmpmaxx;
    if (maxy==0 || tmpmaxy  > maxy) maxy = tmpmaxy;
    
  }
	var m = 1000;
	theEnvelope[0] = minx - m;
	theEnvelope[1] = miny - m;
	theEnvelope[2] = maxx + m;
	theEnvelope[3] = maxy + m;
	
	return theEnvelope;
}

// obtiene un listado de las coordenadas de las features
function sitmapGetEnvelopes(theReply) {
  var theEnvelopes = new Array();
  featureCount = justGetFeatureCount(theReply);
  hasEnvelopes = (theReply.indexOf("<ENVELOPE minx=") > -1);
  spos = 0;
  epos = 0;

  // derive x and y from bounding box centroid
  xmlEndPos = 0;

  for (i=0; i<featureCount; i++) {
    theEnvelope = getEnvelopeXYs(theReply, xmlEndPos);
    theEnvelopes[i] = theEnvelope[0] + "#" + theEnvelope[1] + "#" + theEnvelope[2] + "#" + theEnvelope[3];
  }
  
  return theEnvelopes;
	
}


// actualiza la escala de la toolbal y la deja a 0
function sitmapUpdateScaleToolbar(){
	var tlb = parent.MapFrame.sitmaptop.ToolFrame.document.getElementById("mapscale");
	if (tlb) tlb.selectedIndex = 0;
}

// actualiza la pestaña de cartografía del TOC
function sitmapRefreshTocCartografia(){
	parent.TOCFrame.updateCartografia();
}

// obtiene la url para el toc dependiendo del nivel territorial
function sitmapGetTocUrl() {
    var u = "";
     if (!sitmapCatalogo) {
        u =  appDir + "toc.aspx?l=" + sitmapGetParam("l");
     } else {
        u = appDir + "toc.aspx";
     }
    return u;
}

// habilita/deshabiltar la función de medida
function sitmapMeasure(){

	sitmapMeasureEnabled = !sitmapMeasureEnabled;	
	if (sitmapMeasureEnabled) {
		 setToolPic('Measure');
		 clickFunction('measure');
	} else {
		// limpiamos la selección
		clickFunction('clearsel');
		// activamos el botón de zoomin
		clickFunction('zoomin'); 
		setToolPic('Zoom In');
	}
}

// habilita/deshabiltar la función de tamaño de la ventana del mapa
function sitmapTamano(){
    

	sitmapTamanoGrande = !sitmapTamanoGrande;
	
	if (sitmapTamanoGrande) {
		 setToolPic('TamanoGrande');
		 clickFunction('TamanoGrande');
	} else {
		setToolPic('TamanoPequeno');
		clickFunction('TamanoPequeno');
	}
}



function buildWordURL() {
	var url = sitmapRootUrl + "common/ExportToWord.aspx?u=1&i=" + document.theImage.src + "&l=" + legendImage + "&url=" + sitmapRootUrl + "&e=" + sitmapEscala + "&t=" + sitmapTitle; 
	url = url + "&n=" + sitmapGetParam("l");
	return url;

}

// display word form
function sitmapExportToWord() {
	hideLayer("measureBox");
     //var Win1 = open(url,"PrintPage","width=50,height=50,scrollbars=no,resizable=no");	
     // alert(url);
    var win = window.open(sitmapRootUrl + "common/wordForm.htm", "WordPage", "width=100,height=200,scrollbars,resizable");
	var doc = win.document;
	//doc.writeln("<center><embed SRC='" + url + "' width='100%' height='100%'></embed></center>");
	win.focus();
	
}
// abre una url en una ventana nueva maximizada.
function fullscreenpopup(url)  {
            window.open(url,'miniwin','toolbar=0,location=0,directories=0,status=0,menubar=no,scrollbars=1,resizable=1,left=0,top=0,width='+window.screen.width+',height='+window.screen.height)
            }
			
function sitmapZoomToEnvelopeDesdeListado(index) {
	var env = sitmapListadoEnvelopes[index].split('#');
	zoomToEnvelope(env[0].replace(",", "."), env[1].replace(",", "."), env[2].replace(",", "."), env[3].replace(",", "."));
}

			
// verano: función que abre la ventana de identificación desde el listado
function sitmapIdentifyDesdeListado(index){

	var url = appDir + "../common/displayAttributeData.aspx";
	url += "?t=" + sitmapListadoSdeTable + "&c=" + sitmapListadoCodes[index] + "&s=" + sitmapListadoShapes[index] + "&d=" + LayerName[ActiveLayerIndex];
	url = (sitmapCatalogo)? url + "&ctlg=1" : url + "&ctlg=0" ;
	
	// mostramos la información del elemento seleccionado
	if (aimsShowFotos) {
		url = url + "&f=" + sitmapCodGrupoTema;
		url = url + "&ct=" + sitmapCodTema;	
		url = url + "&i=" + sitmapListadoItemNames[index];
		url = encodeURI(url);
		var w = open(url ,"DataWindowFotos","width=680,height=590,top=20,left=20,scrollbars=yes,resizable=yes");
		w.focus();
	} else {
    	url = encodeURI(url);
		if (!sitmapCatalogo) {
				var dims = sitmapDimensionesIdentificacion.replace(" ", "").split(",");
				var w = open(url,"DataWindow","width=" + dims[0] + ",height=" + dims[1] + ",top=20,left=20,scrollbars=yes,resizable=yes");
		} else {
				var w = open(url,"DataWindow","width=450,height=475,top=20,left=20,scrollbars=yes,resizable=yes");		
		}
		w.focus();
	}
}	


// verano: grid
function sitmapDoMapGrid()
  {
	var iw =iWidth;
	var ih =iHeight;

	if (sitmapPrinting) { // si es la impresión cogemos los with y height de la impresión
		iw = printWidth;
		ih = printHeight;
	} 
  
   var customString = "";
   var numcols = 50;
   var gcolor = "0,0,0";
   var colwidth = parseInt(iw/numcols);
   var text = "";
   var xdisttmp = (iw * Math.abs(eTop-eBottom))/ih;
   var escala = parseInt(xdisttmp/(iw * c_metros_inch));
   var offset = 50000;
   
   var maxxutm = sitmapGetGridX(iw, iw, ih);
   var maxyutm = sitmapGetGridY(ih, ih);
   for (var i=0;i<sitmapGridDesde.length;i++){
	if (escala <=sitmapGridDesde[i] && escala >=sitmapGridHasta[i]){
		offset =sitmapGridOffset[i];
	}
   }

		
   var firstX = sitmapGetGridX(0, iw, ih); // obtenemos el primer punto X
   // ajustamos a un número exacto
   var accurX = firstX;
   if (accurX%offset >0) accurX = firstX - (firstX%offset) + offset;
   
   var firstY = sitmapGetGridY(0, ih); // obtenemos el primer punto Y
   // ajustamos a un número exacto
   var accurY= firstY;
   if (accurY%offset >0) accurY = firstY - (firstY%offset) + offset;

   customString += '<LAYER type="ACETATE" name="mapGrid">\n';
     
	
	// ponemos un poligono blanco en horizontal
	strcoords = 'coords="0 ' + (ih-20) + ';' + iw + ' ' + (ih-20) + ';' + iw + ' ' + ih + ';0 ' + ih + '"';
	customString += '<OBJECT units="pixel">\n<POLYGON ' + strcoords + '>\n';
	customString += '<SIMPLEPOLYGONSYMBOL  boundary="false" fillcolor="255,255,255" />';
	customString += '</POLYGON>\n</OBJECT>\n';
	
	
	// ponemos un polígono blanco en vertical
	strcoords = 'coords="0 0;20 0;20 ' + ih + ';0 ' + ih + '"';
	customString += '<OBJECT units="pixel">\n<POLYGON ' + strcoords + '>\n';
	customString += '<SIMPLEPOLYGONSYMBOL  boundary="false" fillcolor="255,255,255" />';
	customString += '</POLYGON>\n</OBJECT>\n';
	   
 //Do columns      
   for (var i=0;i<numcols;i++)
   {
		var coordXUTM = accurX + (offset*i);
		if (coordXUTM <= maxxutm){
			text = coordXUTM;
			var positionX = sitmapGetGridpixelX(coordXUTM, iw, ih);
			
		    strcoords = 'coords="' + positionX + ' 0;' + positionX + ' ' + ih + '"';
		    customString += '<OBJECT units="pixel">\n<LINE ' + strcoords + '>\n';
		    customString += '<SIMPLELINESYMBOL color="' + gcolor + '" />';
		    customString += '</LINE>\n</OBJECT>\n';

		    customString += '<OBJECT units="pixel">\n';
		    customString += '<TEXT coords="' + (parseInt(positionX)+3) + ' ' + (ih-15) + '" label="X:' + text + '">\n';     
		    customString += '<TEXTMARKERSYMBOL fontsize="10" font="verdana" overlap="false" fontcolor="' + gcolor + '" antialiasing="false" fontstyle="regular"  />\n';
		    customString += '</TEXT>\n</OBJECT>\n';  
		}
   }
   
    

   var rowheight = parseInt(ih/numcols);
   
 //Do rows
   for (var i=0;i<numcols;i++)
   {
		var coordYUTM = accurY + (offset*i);
		if (coordYUTM <= maxyutm){
			text = coordYUTM;
			var positionY = sitmapGetGridpixelY(coordYUTM, ih);
		    strcoords = 'coords="0 ' + positionY + ';' + iw + ' ' + positionY + '"';
		    customString += '<OBJECT units="pixel">\n<LINE ' + strcoords + '>\n';
		    customString += '<SIMPLELINESYMBOL color="' + gcolor + '" />';
		    customString += '</LINE>\n</OBJECT>\n';

		    customString += '<OBJECT units="pixel">\n';
			customString += '<TEXT coords="12' + ' ' + (parseInt(positionY) + 3) + '" label="Y:' + text + '">\n';     
			customString += '<TEXTMARKERSYMBOL angle="90" fontsize="10" font="verdana" overlap="false" fontcolor="' + gcolor + '" antialiasing="false" fontstyle="regular"  />\n';
		    customString += '</TEXT>\n</OBJECT>\n';         
		}

	}
   customString += '</LAYER>\n';
   return customString;
      
 }

 // obtiene la coordenada X UTM a partir de un pixel X
 function sitmapGetGridX(xIn, iw, ih) {
	//xDistance = Math.abs(eRight-eLeft);
	xDistance = (iw * Math.abs(eTop-eBottom))/ih;
//	alert("xDistance:" + xDistance.toFixed(0) + "--" + eLeft.toFixed(0) + "--" + eRight.toFixed(0));
	
	//alert("xDistance1:" + xDistance);
	pixelX = xDistance / iw;
	var x = pixelX * xIn + eLeft; 
	var u = Math.pow(10,0);
	var uX = Math.round(x * u) / u;
	return uX;
}

// obtiene la coordenada Y UTM a partir de un pixel Y
function sitmapGetGridY(yIn, ih) {
	yDistance = Math.abs(eTop-eBottom);
//	alert("yDistance:" + yDistance.toFixed(0) + "--" + eTop.toFixed(0) + "--" + eBottom.toFixed(0));
	pixelY = yDistance / ih;
	var y = pixelY * yIn + eBottom;
	var u = Math.pow(10,0);
	var uY= Math.round(y * u) / u;
	return uY;
}

// obtiene el pixel X a partir de una coordenada UTM X
function sitmapGetGridpixelX(coordX, iw, ih){
	//xDistance = Math.abs(eRight-eLeft);
	xDistance = (iw * Math.abs(eTop-eBottom))/ih;
	return ((coordX - eLeft)/(xDistance / iw));
}

// obtiene el pixel Y a partir de una coordenada UTM Y  
function sitmapGetGridpixelY(coordY, ih){
	yDistance = Math.abs(eTop-eBottom);
	return ((coordY - eBottom)/(yDistance / ih));
}
  
  
// función que actualiza la escala  
function sitmapUpdateEscala(theReply){
	if (sitmapEscala != undefined && !sitmapPrinting) {
		// sitmap -- establecemos la escala y refrescamos el frame de modo
		var pos = theReply.indexOf("<PROPERTIES");
		var theXYs =  getEnvelopeXYs(theReply, pos)
		eRight = theXYs[2];
		eLeft  = theXYs[0];
		eTop   =  theXYs[3];
		eBottom =  theXYs[1];
//		xDistance = theXYs[2]-theXYs[0];
//		yDistance = theXYs[3]-theXYs[1];
		xDistance = eRight-eLeft;
		yDistance = eTop-eBottom;
		
		sitmapEscala = parseInt(xDistance/(iWidth * c_metros_inch));
//		if (debugOn>2) alert(sitmapEscala + "--" + xDistance + "--" + iWidth + "--" + yDistance + "--" + iHeight);
		parent.ModeFrame.document.location= appDir + "../common/ModeFrame.htm";
	}					
}
