//*********************************************************************
//*			Servicios disponibles y variable  de servicio activo      *
//*********************************************************************
var EscalaMinima=500;

// Servicios
//	[0]: nombre del servidor ArcIMS
//	[1]: nombre del servicio ArcIMS
//	Aunque sea sólo ECW, hay que especificar un servicio ArcIMS existente, y si el servicio se rellena con alguna capa
//	vectorial, el servicio ArcIMS que se especifique ha de tener tales capas de relleno.
//	[2]: nombre descriptivo del servicio ArcIMS
//	[3]: color de fondo del mapa
//	[4]: descripción alternativa para la impresión
//	[5]: flag de habilitación del servicio
//	[6]: id del servicio (uso interno); no ordenado
//	[7]: id del grupo al que pertenece el servicio
//	[8]: nombre de servicio que se desea que figure en el log (caso de ECW)
var Servicios = new Array(new Array('pre.sitcan.com', 'MapaCallejero',		'Callejero',			'0,0,0',		'Callejero', true, 2, 1, null),
						  new Array('pre.sitcan.com', 'LimitesMunicipales',	'OrtoExpress',			'0,0,0',		'OrtoExpress', true, 3, 1, 'OrtoExpress'),
						  new Array('pre.sitcan.com', 'FincasRegistrales',	'Fincas Registrales',	'255,255,255',	'Fincas Registrales', true, 13, 2, null));

// Agrupación de servicios
//	[0]: id del grupo
//	[1]: nombre del grupo
var SvcGrupos = new Array(new Array(1, 'CARTOGRAF&Iacute;AS B&Aacute;SICAS'),
						  new Array(2, 'CARTOGRAF&Iacute;AS TEM&Aacute;TICAS'));

// Usuarios
//	[0]: usuario
//	[1]: ruta logo
var usr = new Array(new Array('Todos', '../media/logo_Gobcan.jpg'),
					new Array('Prueba', '../media/logo_Gobcan_CMAYOT.jpg') // Medio Ambiente
					);
if (parent.parent.idUsuario<0 || parent.parent.idUsuario>=usr.length) parent.parent.idUsuario = 0;
// Servicios por usuario
//	[0]: id usuario (índice dentro del array usr)
//	[1]: id servicio
var SvcUsuario = new Array(new Array(1, 2),
  						   new Array(1, 3),
						   new Array(1, 7),
						   new Array(1, 8),
						   new Array(1, 9),
						   new Array(1, 10));

// Parámetro para los servicios ECW
//	[0]: archivo de configuración XML
//	[1]: si true, la leyenda, si la tiene, es visible siempre
var ecw = new Array(null,
					new Array('OrtoExpress', true),
					new Array('OrtoExpress', false));

// Descarga de ficheros
//	[0]: nombre de la capa
//	[1]: relacion de campos (el dos primeros campos han de ser el id unico y la descripcion)
//	Los que tenga el prefijo 'hyplnk' son hipervínculos
//	[2]: descriptores de los campos
//	[3]: ruta de descarga de archivos
//	[4]: unidades de cada campo (en caso de que un campo tenga unidades, se formateará numéricamente su valor)
//	[5]: texto estático para la ventana de información
//	[6]: tipo de capa (si point, la dimensión del extent al pedir info es propocional a la escala y fijo para el resto)
//	[7]: impresión con datos de info más mapa de situación
var TieneInfo = new Array(new Array('ic_ptos',	'DESCTIPO;DESCRIPCIO;CATEGORIA', 'Tipo;Nombre;Categoría', '', ';;;Date()', 'Puntos de Interés', 'point', null),
						  new Array('MUNS',		'CODMUN;MUNICIPIO;POBDER00;POBDER01;POBDER02;POBL_05', 'Código ISTAC;Nombre;Pob. Derecho (ISTAC 1-1-00);Pob. Derecho (ISTAC 1-1-01);Pob. Derecho (ISTAC 1-1-02);Pob. Derecho (ISTAC 1-1-05)', '', '', 'Límites municipales', 'polygon', null),
						  new Array('fincars',	'RUTAMDB;TEXT;NUM_DIVH;F_ESTADO;HYPLNK_W', 'Registro de la Propiedad;Número de finca registral donde se describe la porción de territorio seleccionada;Nº de división/es horizontal/es;Estado de identificación registral;Abrir servicio web asociado', 'http://www.registradorestenerife.org/', '', 'Fincas Registrales', 'polygon', null));

// Imágenes iniciales de cada servicio
//	[0]: Imagen inicial (tamaño pequeño)
//	[1]: Imagen inicial (tamaño grande)
var ImagenIni = new Array(new Array('images/MapaCallejero_1.jpg',	'images/MapaCallejero_2.jpg'),
						  new Array('images/OrtoExpress_1.jpg',		'images/OrtoExpress_2.jpg'),
						  new Array('images/fincasregistrales.jpg',		'images/fincasregistrales.jpg'));

// Imágenes de las leyendas de cada servicio
var SvcLegend = new Array('http://mapa.grafcan.com/Mapa/pages/frames/leyendas/Callejero.html',
					      'http://mapa.grafcan.com/Mapa/pages/frames/leyendas/OrtoExpress.html',
						  '../../pages/frames/leyendas/FincasRegistrales.html');
// Texto del vínculo para mostrar la leyenda
var SvcLegendText = new Array('Mostrar leyenda y/o fecha del dato',
				  	          'Mostrar leyenda y/o fecha del dato',
							  'Mostrar leyenda');

// Extensión inicial de los servicios
//	[0]: left
//	[1]: bottom
//	[2]: right
//	[3]: top
var ExtentIni = new Array(new Array(175833, 2990507, 669634, 3297788),
						  new Array(175833, 2990507, 669634, 3297788),
						  new Array(175833, 2990507, 669634, 3297788));

// Extensión máxima de los servicios
//	[0]: left
//	[1]: bottom
//	[2]: right
//	[3]: top
var ExtentMax = new Array(new Array(175833, 2990507, 669634, 3297788),
						  new Array(175833, 2990507, 669634, 3297788),
						  new Array(175833, 2990507, 669634, 3297788));

// Grupos de capas
//	Relación de las vistas que conforman cada servicio (nombres descriptivos)
var Grupos = new Array(new Array('Límites municipales', 'Puntos de Interés'),
					   new Array('Límites municipales'),
					   new Array('Fincas Registrales', 'Límites municipales'));
// Si 1, no aparece el grupo en la leyenda
var NoGruposLeyenda = new Array(new Array(true, true),
					            new Array(false),
								new Array(false, true));

// Si 1, no aparece el grupo en la relación de capas (conjunto de checks)
var NoGruposCheck = new Array(new Array(false, true),
					          new Array(false),
							  new Array(false));
// Color del check de cada grupo (coherente con el color de los elementos de la capa (vectorial))
var ColorGrupo = new Array(new Array('#ffff00', '#ffffff'),
					       new Array('#ffff00'),
						   new Array('#ffffff', '#ffff00'));

var GrupoVisible = new Array(new Array(false, true),
							 new Array(true),
							 new Array(true, false));

// Capas ArcIMS
//	[0]: Servicio
//	[1]: Grupos del servicio
//	[2]: Capas del grupo
var Capas = new Array(/* Servicio Mapa Callejero */
					  new Array(new Array('MUNL', 'MUNS'),
								new Array('ic_ptos')),
			          /* Servicio OrtoExpress */
					  new Array(new Array('MUNL', 'MUNS')),
					  /* Fincas Registrales */
					  new Array(new Array('fincars'),
								new Array('MUNL')));

// Registros de la propiedad
var Registro = new Array(new Array("ARRECIFE", "LZ - Registro de la Prop. de Arrecife"),
						 new Array("TIAS", "LZ - Registro de la Prop. de Tías"),
						 new Array("TEGUISE", "TF - Registro de la Prop. de Teguise"),
						 new Array("CORRALEJO", "FV - Registro de la Prop. de Corralejo"),
						 new Array("PTOROS1", "FV - Registro de la Prop. de Pto. Rosario 1"),
						 new Array("PTOROS2", "FV - Registro de la Prop. de Pto. Rosario 2"),
						 new Array("PALMAS1", "GC - Registro de la Prop. de Las Palmas 1"),
						 new Array("PALMAS2", "GC - Registro de la Prop. de Las Palmas 2"),
						 new Array("PALMAS3", "GC - Registro de la Prop. de Las Palmas 3"),
						 new Array("PALMAS4", "GC - Registro de la Prop. de Las Palmas 4"),
						 new Array("PALMAS5", "GC - Registro de la Prop. de Las Palmas 5"),
						 new Array("PALMAS6", "GC - Registro de la Prop. de Las Palmas 6"),
						 new Array("MOGAN", "GC - Registro de la Prop. de Mogán"),
						 new Array("SBARTOL1", "GC - Registro de la Prop. de San Bartolomé 1"),
						 new Array("SBARTOL2", "GC - Registro de la Prop. de San Bartolomé 2"),
						 new Array("STALUCIA", "TF - Registro de la Prop. de Sta. Lucía de T."),
						 new Array("STAMGUIA", "GC - Registro de la Prop. de Sta. Mª Guía"),
						 new Array("TELDE1", "GC - Registro de la Prop. de Telde 1"),
						 new Array("TELDE2", "GC - Registro de la Prop. de Telde 2"),
						 new Array("ADEJE", "TF - Registro de la Prop. de Adeje"),
						 new Array("ARONA", "TF - Registro de la Prop. de Arona"),
						 new Array("GRANADILLA", "TF - Registro de la Prop. de Granadilla"),
						 new Array("GUIMAR", "TF - Registro de la Prop. de Güimar"),
						 new Array("ICOD", "TF - Registro de la Prop. de Icod de los Vinos"),
						 new Array("LAGUNA1", "TF - Registro de la Prop. de La Laguna 1"),
						 new Array("LAGUNA2", "TF - Registro de la Prop. de La Laguna 2"),
						 new Array("SMIGUEL", "TF - Registro de la Prop. de S. Miguel Abona"),
						 new Array("OROTAVA", "TF - Registro de la Prop. de La Orotava"),
						 new Array("PUERTOCRUZ", "TF - Registro de la Prop. de Pto. de la Cruz"),
						 new Array("ROSARIO", "TF - Registro de la Prop. de El Rosario"),
						 new Array("STACRUZ1", "TF - Registro de la Prop. de S/C Tenerife 1"),
						 new Array("STACRUZ3", "TF - Registro de la Prop. de S/C Tenerife 3"),
						 new Array("STACRUZ4", "TF - Registro de la Prop. de S/C Tenerife 4"),
						 new Array("TACORONTE", "TF - Registro de la Prop. de Tacoronte"),
						 new Array("SSEBASTIAN", "LG - Registro de la Prop. de S.S. La Gomera"),
						 new Array("SCPALMA", "LP - Registro de la Prop. de Sta. Cruz Palma"),
						 new Array("HIERRO", "EH - Registro de la Prop. de Valverde")
						 );

// Indice del servicio activo, dentro del array de servicios
var idxServicio = 2;

// nombre de la capa de calles (en desuso)
var CapaCalles = 'Calles';
var CapaPortales = 'Portales';
// Fincas Registrales
var CapaFincars = "fincars"

// Servidor ArcIMS
var ArcIMSServer = Servicios[idxServicio][0];

// Nombre del servicio ArcIMS activo
var Servicio = Servicios[idxServicio][1];

// Variable que indica que estamos en el estado inicial (imagen precargada)
var Inicio = true;

// Variable que indica si vamos al extent inicial del servicio seleccionado
// o permanecemos en la extensión actual
var resetExtent = false;
// nos indica si la acción actual ha sido cambiar de servicio activo
var cambioServicio = false;

// Rutina que actualiza la información inicial para el servicio activo
function ActualizarConexion(idxNewService) {
	idxServicio = idxNewService;
	ArcIMSServer = Servicios[idxServicio][0];
	Servicio = Servicios[idxServicio][1];
	parent.MapFrame.mapBackColor = Servicios[idxServicio][3];
	// filtros
	filtroCalle = '';
	filtroPortal = '';
	// Geometría VML
	if (limpiarGeometria) GeometriaVML="";
	// rutas conexión con el servidor
	imsURL = 'http://' + ArcIMSServer + '/servlet/com.esri.esrimap.Esrimap?ServiceName=' + Servicio;
	imsOVURL = 'http://' + ArcIMSServer + '/servlet/com.esri.esrimap.Esrimap?ServiceName=' + Servicio;
	imsQueryURL= imsURL + "&CustomService=Query";
	imsGeocodeURL= imsURL + "&CustomService=Geocode";
	// extent inicial
	startLeft = ExtentIni[idxServicio][0];
	startBottom = ExtentIni[idxServicio][1];
	startRight = ExtentIni[idxServicio][2];
	startTop = ExtentIni[idxServicio][3];
	// Comprobamos si debemos resetear el Extent
	/*if (ecw[idxServicio] && (eLeft<startLeft||eRight>startRight||eTop>startTop||eBottom<startBottom))
		resetExtent = true;		
	else
		resetExtent = false;*/

	if (resetExtent) {
		eLeft = startLeft;
		eBottom = startBottom;
		eRight = startRight;
		eTop = startTop;
	}
	// extent máximo
	limitLeft = ExtentMax[idxServicio][0];
	limitBottom = ExtentMax[idxServicio][1];
	limitRight = ExtentMax[idxServicio][2];
	limitTop = ExtentMax[idxServicio][3];
	//window.status = '(' + startLeft + ', ' + startBottom + '; ' + startRight + ', ' + startTop + ')';
}

function isLegendVisible2() {
	if (parent.MapFrame.Inicio) return false;
	for (var idGrupo=0; idGrupo<NoGruposLeyenda[idxServicio].length; idGrupo++)
	{
		if (ecw[idxServicio])
			return (!NoGruposLeyenda[idxServicio][idGrupo] && GrupoVisible[idxServicio][idGrupo]);
		else
			return (!NoGruposLeyenda[idxServicio][idGrupo] && isGrupoVisible(idGrupo) && GrupoVisible[idxServicio][idGrupo]);
	}
	return false;
}
function isLegendVisible() {
	// Si estamos en la imagen inicial no se muestra el hipervínculo
	if (parent.MapFrame.Inicio) return false;
	// Si es nulo o cadena vacía, no se muestra el hipervínculo
	if (!validSvcLegend(idxServicio)) return false;
	for (var idGrupo=0; idGrupo<NoGruposLeyenda[idxServicio].length; idGrupo++)
	{
		if (ecw[idxServicio])
			if (ecw[idxServicio][1]) return true;
			else if (!NoGruposLeyenda[idxServicio][idGrupo] && GrupoVisible[idxServicio][idGrupo]) return true;
		else
			//if (!NoGruposLeyenda[idxServicio][idGrupo] && isGrupoVisible(idGrupo) && GrupoVisible[idxServicio][idGrupo]) return true;
			return true;
	}
	return false;
}
function validSvcLegend(idxSvc) {
	return (SvcLegend[idxSvc]!=null && SvcLegend[idxSvc]!="");
}

function getIdGrupo(lName) {
	/*
	 * Obtiene el id de grupo de una capa ArcIMS
	 */
	for (var idGrupo=0; idGrupo<Capas[idxServicio].length; idGrupo++)
		for (var idCapa=0; idCapa<Capas[idxServicio][idGrupo].length; idCapa++) {
			if (Capas[idxServicio][idGrupo][idCapa].toUpperCase() == lName.toUpperCase()) return idGrupo;
		}
	return -1; // no se encontró la capa!!!
}

function getIdxLayerAims(idCapa, idGrupo, idxService) {
	/*
	 * Obtiene la posición, dentro de los arrays de las capas ArcIMS del servicio activo, de la capa i-ésima
	 * del array del archivo de configuración de capas por grupo
	 */
	if (idxService==null) idxService = parent.MapFrame.idxServicio;
	var l = parent.MapFrame.Capas[idxService][idGrupo];
	// qué posición ocupa la capa en la colección de capas recuperadas por GET_SERVICE_INFO
	for (var k=0; k<parent.MapFrame.LayerName.length; k++) {
		//if (idCapa==0 && idGrupo==3)
		//alert("[aims] " + parent.MapFrame.LayerName[k].toUpperCase() + " vs [visor] " + l[idCapa].toUpperCase());
		if (parent.MapFrame.LayerName[k].toUpperCase() == l[idCapa].toUpperCase()) return k;
	}
	return -1;
}

function getIdxLayerCfg(idLayerAims) {
	/*
	 * Obtiene la posición, dentro de los arrays de las capas del archivo de configuración de capas por grupo,
	 * de la capa i-ésima del servicio ArcIMS activo
	 */
	var t = parent.MapFrame.Grupos[parent.MapFrame.idxServicio];
	
	for (var idGrupo=0; idGrupo<t.length; idGrupo++)
		for (var idCapa=0; idCapa<t[idGrupo].length; idCapa++)
			if (parent.MapFrame.LayerName[idLayerAims].toUpperCase()==t[idGrupo][idCapa].toUpperCase())
				return idCapa;

	return -1;
}

function isGrupoVisible(idxGrupo) {
	var k;
	// capas del grupo idxGrupo
	var l = parent.MapFrame.Capas[parent.MapFrame.idxServicio][idxGrupo];
	var t = parent.MapFrame;
	for (var i=0; i<l.length; i++) {
		// qué posición ocupa la capa en la colección de capas recuperadas por GET_SERVICE_INFO
		k = parent.MapFrame.getIdxLayerAims(i, idxGrupo);
		//alert(l[i] + ": " + t.mapScaleFactor + " vs (" + t.LayerMinScale[k] + "; " + t.LayerMaxScale[k] + ")");
		if (k==-1) {
			//alert(l[i] + ": " + t.mapScaleFactor + " vs (" + t.LayerMinScale[k] + "; " + t.LayerMaxScale[k] + ")");
			alert("[isGrupoVisible()] Error de configuración de capas");
			return false;
		} else if (t.mapScaleFactor>=t.LayerMinScale[k] && t.mapScaleFactor<=t.LayerMaxScale[k]) {
			return true;
		}
	}

	return false;
}

function setGrupoVisible(idGrupo, isVisible, idxService) {
	var t = parent.MapFrame;
	var idLayer;
	
	if (idxService==null) idxService = t.idxServicio;
	// flag de visibilidad del grupo
	t.GrupoVisible[idxService][idGrupo] = isVisible;

	for (var idCapa=0; idCapa<t.Capas[idxService][idGrupo].length; idCapa++) {
		if ((idLayer = getIdxLayerAims(idCapa, idGrupo, idxService))==-1) {
			alert("[setGrupoVisible()] Error de configuración de capas");
			return false;
		}
		t.LayerVisible[idLayer] = (isVisible)?1:0;
	}
}


// Selección del servicio en caso de invocación para situar un punto en un par de coordenadas
if (parent.parent.utmAimsService>-1)
{
	for (var i=0; i<Servicios.length; i++)
		if (parseInt(Servicios[i][6])==parent.parent.utmAimsService)
		{
			idxServicio = i;
			break;
		}
	if (i==Servicios.length) alert("El servicio especificado no existe")
}
// Personalización de usuario
if (parent.parent.idUsuario>0)
{
	parent.topFrame.logo.src = usr[parent.parent.idUsuario][1];
}

// Establecemos los valores iniciales para el servicio establecido como activo:
//	- Extensión inicial
//	- Extensión máxima
//	- Rutas de llamada al servlet connector
ActualizarConexion(idxServicio);
