var map, layer, positionArray, generaZoom, esQuery, urlQuery,lineFeature;
var distanciatotal = 0;
var popupQuery=null;
var capasPop = [];
var eess; //Capa que se representa comienza siendo la de estaciones// Capa de estaciones de servicio
var capa_embarcaciones; // Capa de embarcaciones
var capa_estaciones;
var markerEuro; //capa con estaciones más baratas
//var ultimaPosicion=0;
var features_gml = '';

//Guarda la url de la consulta WFS para el pintado algoritmico, sin el combustible
var urlOrigen;
var tipoCarburante;

//Variables para la barra de progreso de carga
var contador=1;
var direccion = true;
var id;

//internacionalizacion del mousetoolbar
var altbuttons = new Array();

//internacionalizacion de la busqueda de EESS
var tituloBusqueda = new Array();
//tituloBusqueda[28]
//capas base
var ignBaseLayer = new OpenLayers.Layer.WMS( ignNombre,ignbase, {layers: ignlayers, visibility: false});

var cartociudad = new OpenLayers.Layer.WMS( 'Cartociudad',
	                    'http://www.cartociudad.es/wms/CARTOCIUDAD/CARTOCIUDAD',
	                    {layers: 'DivisionTerritorial,FondoUrbano,Vial,Portal,Toponimo', visibility: false});

function addEvent(elemento,evento,funcion)
{
	if (elemento!=null)
	{
		if (elemento.addEventListener){
			elemento.addEventListener(evento, funcion, false);
		} else {
			elemento.attachEvent("on"+evento, funcion);
		}
	}
}

function inicio(tipoComb, tipoBusqueda, prnt, maplonlat,paltbuttons,ptituloBusqueda){


	// internacionalizacion del mousetoolbar
	altbuttons = paltbuttons.split('|');

	//internacionalizacion de la busqueda de EESS
	tituloBusqueda = ptituloBusqueda.split('|');

	addEvent(document.getElementById('numero'),"keypress",function(e){
	numbersonly(e);});

	addEvent(document.getElementById('botonBuscar'),"click",function(){
	buscaEntidades();});

	addEvent(document.getElementById('mostrarAlfanumerica'),"click",function(){
	mostrarAlfanumerica();});

	addEvent(document.getElementById('mostrarGrafica'),"click",function(){
	mostrarGrafica();});

	addEvent(document.getElementById('desplegarOverwiewMap'),"click",function(){
	desplegar('overviewmap');});

	addEvent(document.getElementById('desplegarCapas'),"click",function(){
	desplegar('listacapas');});

	addEvent(document.getElementById('desplegarOrtofotos'),"click",function(){
	desplegar('listaortofotos');});

	/*addEvent(document.getElementById('buscarEESS_check'),"click",function(){
	habilitarCampos();});*/

	addEvent(document.getElementById('icooeste'),"click",function(){
	moverMapa(document.getElementById('icooeste'));});

	addEvent(document.getElementById('iconorte'),"click",function(){
	moverMapa(document.getElementById('iconorte'));});

	addEvent(document.getElementById('icosur'),"click",function(){
	moverMapa(document.getElementById('icosur'));});

	addEvent(document.getElementById('icoeste'),"click",function(){
	moverMapa(document.getElementById('icoeste'));});

	addEvent(document.getElementById('imgAyuda'),"click",function(){
	window.open('ayuda.html');});

	addEvent(document.getElementById('imgImprimir'),"click",function(){
	imprimir();});

	addEvent(document.getElementById('imgEmail'),"click",function(){
	sendEmail();});

	addEvent(document.getElementById('imgAyuda2'),"click",function(){
	window.open('ayuda.html');});

	addEvent(document.getElementById('imgImprimir2'),"click",function(){
	imprimir();});

	addEvent(document.getElementById('imgEmail2'),"click",function(){
	sendEmail();});

	/*addEvent(document.getElementById('peninsulaBaleares'),"click",function(){
	cargaProvincia();});*/

	addEvent(document.getElementById('linkTodaEspaña'),"click",function(){
	descargarExcel(1);});

	addEvent(document.getElementById('linkPeninsulaBaleares'),"click",function(){
	descargarExcel(2);});


	if (!prnt && avisoON){
		//deshabilita los scroll para Mozilla
		if(navigator.userAgent.indexOf("MSIE")== -1){
			document.documentElement.style.overflow = 'hidden';
		}

		document.getElementById('aviso').style.visibility = 'visible';
		var aviso = document.getElementById("aviso");
		aviso.style.width = window.screen.width;
		aviso.style.height = window.screen.height;

		aviso.innerHTML = "<div id='popup' class='mensajeAviso'>"+
   			"<h1 class='h1fondoceleste'>Nuevo portal de hidrocarburos (Versi&oacute;n Beta)</h1>"+
   			"<p>Se pone en conocimiento de los usuarios, que se ha producido"+
   			" una mejora en el servicio del portal de hidrocarburos, a&ntilde;adiendo"+
   			" como nuevas funcionalidades, la b&uacute;squeda de Estaciones de Servicio"+
   			" georreferenciadas en la geograf&iacute;a espa&ntilde;ola, haciendo uso de"+
   			" tecnolog&iacute;as est&aacute;ndar de la OGC (WMS y WFS).</p>"+
			"<p>Queda a disposicion del usuario una ayuda sobre el funcionamiento del geoportal,"+
			" a la que puede accederse mediante el bot&oacute;n "+
			"<img src='../img/button_help_2.png' alt='Bot&oacute;n de ayuda' width='20' height='20' longdesc='Botón de ayuda del geoportal'/>"+
			" colocado en la parte inferior del mapa principal de la pantalla.</p>"+
			"<p>Si desea acceder al anterior portal de hidrocarburos pulse sobre el siguiente icono "+
			"<img src='images/ico_carburantes.jpg' width='37' height='20' alt='Acceso a la aplicaci&#243;n de precios de carburantes en ventana nueva'/> "+
			"situado en la parte inferior izquierda de la pantalla principal del portal"+
			"<p>As&iacute; mismo para conocer mas informaci&oacute;n sobre una estaci&oacute;n"+
			" de servicio, pulse sobre el bot&oacute;n "+
			"<img src='../img/button_query_2.png' alt='Bot&oacute;n de informaci&oacute;n' width='20' height='20' longdesc='Botón de informaci&oacute;n sobre la ee.ss.'/>"+
			" y posteriormente pulse sobre la estaci&oacute;n sobre la que quiere conocer mas informaci&oacute;n</p>"+
   			"<img id='cerrar' class='cerrar' src='images/cerrar.jpg'/></div>";


		var popup = document.getElementById("popup");
		popup.style.top= (window.screen.height/2)-230+"px";
		popup.style.left= (window.screen.width/2)-289+"px";

		addEvent(document.getElementById('cerrar'),"click",function(){
		document.getElementById('aviso').style.visibility = 'hidden';
		document.getElementById('buscarEESS_check').disabled = false;
	 	document.getElementById('tiposcombustible_select_id').disabled = false;
	 	document.getElementById('provincias_select_id').disabled = false;
	 	document.getElementById('municipios_select_id').disabled = false;
	 	//Habilita nuevamente los scroll
	 	if(navigator.userAgent.indexOf("MSIE")== -1){
	 		document.documentElement.style.overflow = 'visible';
	 	}
	 	});
		addEvent(document.getElementById('cerrar'),"mouseover",function(){
		document.getElementById('cerrar').src = "images/cerrar_claro.jpg";});
		addEvent(document.getElementById('cerrar'),"mouseout",function(){
		document.getElementById('cerrar').src = "images/cerrar.jpg";});

		document.getElementById('buscarEESS_check').disabled = true;
		document.getElementById('tiposcombustible_select_id').disabled = true;
	 	document.getElementById('provincias_select_id').disabled = true;
	 	document.getElementById('municipios_select_id').disabled = true;

	}

	init(tipoComb, tipoBusqueda, prnt, maplonlat);

	loadDataForm();
}

function init(tipoComb, tipoBusqueda, prnt, maplonlat){

	if (maplonlat || prnt){
		mapaNormal = false;
	}

	if (tipoComb==null)
		tipoComb =1;

	tipoCarburante = tipoComb;

	resolucion(prnt||maplonlat);


	if(!prnt && !maplonlat)
	{
		mostrarGrafica();
		cargarInicio(tipoComb,tipoBusqueda);
	}

    /*
    //Para BCN25000 no caheada
	var mapOptions = {  maxResolution: 'auto',
						numZoomLevels: 17,
                  		controls: [],
						maxExtent: new OpenLayers.Bounds(-18.865234375,25.892578125,4.865234375,46.107421875),
                 		projection: proyeccion,
                  		reproject:false
    };
    */

    //Para BCN25000 cacheada
    var mapOptions = {maxResolution:0.0439453125,
                resolutions:[	0.0439453125,
				0.02197265625,
				0.010986328125,
				0.0054931640625,
				0.00274658203125,
				0.001373291015625,
				0.0006866455078125,
				0.00034332275390625,
				0.000171661376953125,
				0.0000858306884765625,
				0.00004291534423828125,
				0.000021457672119140625,
				0.0000107288360595703125,
				0.00000536441802978515625,
				0.000002682209014892578125,
				0.0000013411045074462890625],
           		controls: [],
				maxExtent: new OpenLayers.Bounds(-45,0,45,67.5),
           		projection: proyeccion,
           		reproject:false
	};

	map = new OpenLayers.Map('map', mapOptions );
	positionArray = -1;
	generaZoom = 0;

	/*
	//Para BCN25000 no cacheada
	var graphicOptions = {
  		maxExtent: new OpenLayers.Bounds(-18.865234375,25.892578125,4.865234375,46.107421875),
		projection: proyeccion
	};
	*/

	//Para BCN25000 cacheada
  	var graphicOptions = {
		maxExtent: new OpenLayers.Bounds(-45,0,45,67.5),
		projection: proyeccion
	};


	//Mapa guia con la capa no cacheada
	var graphic = new OpenLayers.Layer.WMS( ignNombre,
	              "http://www.idee.es/wms/IDEE-Base/IDEE-Base?", {layers: ignlayers});

	/*
	//Mapa guia con la misma capa que mapa general
	var graphic = new OpenLayers.Layer.WMS( ignNombre,
	              ignbase, {layers: ignlayers});
	*/

	/*
	//Mapa guia sea una imagen estatica
	var graphic = new OpenLayers.Layer.Image('MapaGuia',
		imageUrl,
		new OpenLayers.Bounds(-18.865234375,25.892578125,4.865234375,46.107421875),
		new OpenLayers.Size(321,274),
		graphicOptions);
	*/


  	var overviewOptions = {
 		mapOptions: {numZoomLevels: 1, //Para que el mapa guía no se redimensione
			 		projection: proyeccion,
			 		tileSize: new OpenLayers.Size(256,256),
			 		//maxResolution:0.17578125//cacheada
			 		maxExtent: new OpenLayers.Bounds(-18.865234375,25.892578125,4.865234375,46.107421875)//Sin cachear
		},
 		layers: [graphic],
	    div: $('overviewmap'),
	    ovMap: map,
	    'size': new OpenLayers.Size(155,140)
	    };


	if(!prnt)
	{
		map.addControl(new OpenLayers.Control.PanZoomBar());
		map.addControl(new OpenLayers.Control.MousePosition());

		if(!maplonlat){
			map.addControl(new OpenLayers.Control.MouseToolbar({div: $('toolbarMain'),tipo: 1,'altbuttons': altbuttons}));
		} else {
			map.addControl(new OpenLayers.Control.MouseToolbar({div: $('toolbarMain'),tipo: 2,'altbuttons': altbuttons}));
		}

	}
	var myScaleBar = new OpenLayers.Control.ScaleBar();
    myScaleBar.displaySystem = 'metric';
	myScaleBar.abbreviateLabel = true;
	myScaleBar.singleLine = false;
    map.addControl(myScaleBar);

	if(!prnt && !maplonlat)
	{
		map.addLayer(ignBaseLayer);
	}
	else
	{
		if(prnt){
			if (tipoBusqueda == 0){
				addUserWMSLayers('listacapas', capasWMSPrint, capasHabilitadasPrint, false,prnt);
			} else {
				addUserWMSLayers('listacapas', capasWMSPrintEmbarcaciones, capasHabilitadasPrint, false,prnt);
			}
		}
		if(maplonlat){
			addUserWMSLayers('listacapas', capasWMSFijasLonlat, capasWMSFijasHabilitadasLonlat, false,true);

			//Capa de Catastro
			var capa = new OpenLayers.Layer.WMS(capasWMSSeleccionablesLonlat[0][0], capasWMSSeleccionablesLonlat[0][1],
							{layers: capasWMSSeleccionablesLonlat[0][2], format: capasWMSSeleccionablesLonlat[0][3],
									transparent: capasWMSSeleccionablesLonlat[0][4],
									isQuery:capasWMSSeleccionablesLonlat[0][5],
									SRS:proyeccion,
									exceptions: capasWMSSeleccionablesLonlat[0][6]
							},
							//{tileSize: new OpenLayers.Size(400,400), buffer: 1 });
							{tileSize: new OpenLayers.Size(256,256), buffer: 1, gutter: 15 });

			map.addLayer(capa);

			//Capa de Ortofotos PNOA

			capa = new OpenLayers.Layer.WMS(capasWMSSeleccionablesLonlat[1][0], capasWMSSeleccionablesLonlat[1][1],
							{layers: capasWMSSeleccionablesLonlat[1][2], format: capasWMSSeleccionablesLonlat[1][3],
									transparent: capasWMSSeleccionablesLonlat[1][4],
									isQuery:capasWMSSeleccionablesLonlat[1][5],
									SRS:proyeccion,
									exceptions: capasWMSSeleccionablesLonlat[1][6]
							},
							//{tileSize: new OpenLayers.Size(400,400), buffer: 1 });
							{tileSize: new OpenLayers.Size(256,256), buffer: 1, gutter: 15 });

			map.addLayer(capa);
		}
	}

	if(!prnt && !maplonlat)
	{
		//añade ortofotos
		addUserWMSLayers('listaortofotos', ortofotosWMS, ortofotosHabilitadas, true);

		//añade el resto de capas
		if (tipoBusqueda == 0){
			addUserWMSLayers('listacapas', capasWMS, capasHabilitadas, false);
		} else {
			addUserWMSLayers('listacapas', capaWMSembarcaciones, capasHabilitadas, false);
		}
		map.addLayer(cartociudad);
		//map.addLayer(metacarta);

		var vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry");
		map.addLayer(vectorLayer);

  	}

	var ovControl = new OpenLayers.Control.OverviewMap(overviewOptions);
	ovControl.isSuitableOverview = function() {
      		return true;
  		};
  	map.addControl(ovControl);

	if (!prnt)
	{

		var lon = Number(getURLParam("lon"));
		var lat = Number(getURLParam("lat"));

		if ((lon)&& (lat))
		{
			if ((lon != null) && (lat != null))
			{
				/*var bounds = new OpenLayers.Bounds (lon-resolCentrado, lat-resolCentrado, lon+resolCentrado, lat+resolCentrado);
				map.zoomToExtentAndView(bounds);*/
				var lonlat = new OpenLayers.LonLat(lon,lat);
				map.setCenter(lonlat, zoomCentrado);
			}
		}
		else
		{
			var a = getURLParam("minx");
			var b = getURLParam("miny");
			var c = getURLParam("maxx");
			var d = getURLParam("maxy");

			if ((a)&&(b)&&(c)&&(d))
			{
				if ((a != null) && (b != null) && (c != null) && (d != null))
				{
					var bounds = new OpenLayers.Bounds(a, b, c, d);
					var zoomEsp = getURLParam("nivzoom");
					map.zoomToExtent(bounds, zoomEsp);
				}
			}
			else
			{
				map.zoomToMaxExtent();
			}
		}
	}
	else
	{
		var minx = document.forms[0].minx.value;
		var miny = document.forms[0].miny.value;
		var maxx = document.forms[0].maxx.value;
		var maxy = document.forms[0].maxy.value;
		var zoomEsp = getURLParam("nivzoom");

		var bounds = new OpenLayers.Bounds(minx, miny, maxx, maxy);
		map.zoomToExtent(bounds, zoomEsp);
	}

	//GetFeatureInfo

	map.events.register('click', map, function (e) {
				for(var i = 0;i < map.controls.length;i++){
					var control = map.controls[i];
					if(control.displayClass && control.displayClass=="olControlMouseDefaults"){
						if(control.mode=="radio"){
							var lonlat = map.getLonLatFromViewPortPx(e.xy);
			 			    var vradio = document.getElementById('radio').value / "113.3";
							var bbox = new OpenLayers.Bounds(lonlat.lon-vradio,
							lonlat.lat-vradio,
							lonlat.lon+vradio,
							lonlat.lat+vradio);
							map.zoomToExtent(bbox);

                    		var pointList = [];
                    		var i = 0;
                    		var rad = 0;
                    		while (i < 360){
                    			rad = i * Math.PI / 180;
                    			pointList.push(new OpenLayers.Geometry.Point(lonlat.lon+(vradio*Math.cos(rad)),lonlat.lat-(vradio*Math.sin(rad))));
                    			i = i + 10;
                    		}
							var lyrV = layerVector();
							map.layers[lyrV].destroyFeatures();
                    		lineFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LinearRing(pointList));
							map.layers[lyrV].addFeatures([lineFeature]);

                    		getfeatureWFS(bbox,getCombustible());
						}
					}
				}

				Event.stop(e);
	  });

	map.events.register('mouseover', map, function (e) {

			//oculto info
			for(x=0;x<capasPop.length;x++)
			{
				capasPop[x].style.visibility="hidden";
			}
			/*capaPop.style.visibility="hidden";
		    capasPop.push(capaPop);*/

	  });

	//Código para ocultar el mapa guía cuando se entra en la página
	//if (!prnt)
	//{
	desplegarLista('overviewmap',"none");
	if (!prnt)
	{
		desplegarLista('listacapas',"none");

		if(!maplonlat){
			desplegarLista('listaortofotos',"none");
		}
		//}
		var menu = document.getElementById('overviewmap');

		menu.firstChild.firstChild.className = "ocultar_menu";
		menu.className = "ocultar_menu";
	}
	//}

	if (maplonlat)
	{
		inicioComprobarLonLat();
	}

	/*if (!prnt)
	{
		var lon = Number(getURLParam("lon"));
		var lat = Number(getURLParam("lat"));

		if (!((lon)&& (lat)))
		{
			this.map.setCenter(new OpenLayers.LonLat(-7, 35.5), this.map.zoom);
		}
	}*/

	if (!prnt && tipoBusqueda){
		document.getElementById('buscarEESS_check').options[tipoBusqueda].selected = true;
		cambioTipoBusqueda(tipoComb);
		//cambioTipoBusqueda(null);
		//document.getElementById('tiposcombustible_select_id').options[tipoComb].selected = true;
	}
}

function desplegar(categoria){
	var menu = document.getElementById(categoria);
	if(menu.style.display == "none" || menu.style.display == ""){
		return desplegarLista(categoria,"block");
	}else{
		return desplegarLista(categoria,"none");
	}
}
function desplegarLista(categoria,estado){

	var menu = document.getElementById(categoria);
	if(estado == "none"){
		if (categoria == "listacapas" || categoria=="listaortofotos")
		{
			document.getElementById("li"+categoria).className = categoria+"off";
			document.getElementById("li"+categoria).style.height = '0px';
		}
		menu.style.display = "none";
		if (menu.firstChild){
			var submenu = menu.firstChild;
			if (submenu.firstChild){
				submenu.firstChild.style.display = "none";
			}
		}
	}
	else{
		menu.style.display = "block";

		if (categoria == "listacapas" || categoria=="listaortofotos")
		{
			document.getElementById("li"+categoria).className = categoria+"on";

			//Por defecto, 80 px
			var altura = '50';
			var padre = document.getElementById(categoria);
			var hijos = getChildren(padre, "div");
			var numChildren = hijos.length;

			if (numChildren != 1 && hijos[0].clientHeight)
				altura = hijos[0].clientHeight;

			altura=altura*numChildren;
			document.getElementById("li"+categoria).style.height = altura+'px';
			//var altura2 = document.getElementById("li"+categoria).offsetHeight;
			document.getElementById("li"+categoria).style.offsetHeight = altura+'px';
		}

		if (menu.firstChild){
			var submenu = menu.firstChild;
			if (submenu.firstChild){
				submenu.firstChild.style.display = "block";
			}
		}
	}
}

function mostrarCentrado(categoria, mostrar){
	var menu = document.getElementById(categoria);

	if (!mostrar)
		menu.className = "ocultar_menu";
	else
	{
		if(menu.className == "ver_menu_centrado"){
			menu.className = "ocultar_menu";
		}
		else{
			menu.className = "ver_menu_centrado";
		}
	}
}

function mostrarAlfanumerica(){
	document.getElementById('ContenidoPagina').style.display ='none';
	desplegarLista('overviewmap','none');
	document.getElementById('ContenidoPaginaTexto').style.display = 'block';
	document.getElementById('datosAmpliados').style.display = 'none';
	document.getElementById('Menu_2_liTitular').style.display='none';
	document.getElementById('Menu_3_liTitular').style.display='none';
	document.getElementById('Menu_4_liTitular').style.display='none';
	document.getElementById('Menu_5_liTitular').style.display='none';
	document.getElementById('toolbarMain').style.display='none';
	//document.getElementById('resultseess').style.display='none';
	desplegarLista('listacapas','none');
	desplegarLista('listaortofotos','none');

	var tabCabecera = document.getElementById('cabecera');
	if (tabCabecera!=null && document.getElementById('listaResultados')!=null)
	{
		document.getElementById('listaResultados').style.width=
			tabCabecera.width;
		document.getElementById('listaResultados').style.offsetWidth=
			tabCabecera.offsetWidth;
	}

	//Con nuevos estilos
	if (document.getElementById('desplegable')){
		document.getElementById('desplegable').style.display='none';
	}


}

function mostrarGrafica(){
	document.getElementById('ContenidoPaginaTexto').style.display = 'none';
	document.getElementById('datosAmpliados').style.display = 'none';
	document.getElementById('ContenidoPagina').style.display ='block';
	desplegarLista('overviewmap','none');
	document.getElementById('Menu_2_liTitular').style.display='block';
	document.getElementById('Menu_3_liTitular').style.display='block';
	document.getElementById('Menu_4_liTitular').style.display='block';
	document.getElementById('Menu_5_liTitular').style.display='block';
	document.getElementById('toolbarMain').style.display='block';
	//document.getElementById('resultseess').style.display='block';
	desplegarLista('listacapas','none');
	desplegarLista('listaortofotos','none');

	//Con nuevos estilos
	if (document.getElementById('desplegable')){
		document.getElementById('desplegable').style.display='block';
	}
	//Esta comprobacion esta para evitar que se visualice el link de mostrar datos
	//alfanumericos, si con la busqueda no se han obtenido datos alfanumericos
/*	if(document.getElementById('objbox') != null){
		document.getElementById('mostrarAlfanumerica').style.display='block';
	}else{
		document.getElementById('mostrarAlfanumerica').style.display='none';
	}*/

}

function mostrarDatosAmpliados(){
	document.getElementById('ContenidoPaginaTexto').style.display ='none';
	document.getElementById('datosAmpliados').style.display = 'block';

}

function cambioTipoBusqueda(tipoComb){
	habilitarCampos();
	if (document.getElementById('buscarEESS_check').selectedIndex != 2){
		cargaCombustible(tipoComb);
		document.getElementById('provincias_select_id').options[0].selected = true;
		//cargaMunicipio(document.getElementById('provincias_select_id').selectedIndex);
		document.getElementById('municipios_select_id').options.length=0;
		document.getElementById('municipios_select_id').options[0] = new Option('(Seleccione Población)',-1)
		document.getElementById('excel').style.display='block';
	} else {
		document.getElementById('excel').style.display='none';
	}
	//Borramos las medidas y el circulo del radio si los hay
	var lyrV = layerVector();
	this.map.layers[lyrV].destroyFeatures();
	//Borramos los datos de la tabla
	clearWFSResults();
	document.getElementById('resultadosBusqueda').innerHTML = "";
	document.getElementById('criteriosBusqueda').innerHTML = "";
	document.getElementById('numResultados').innerHTML = "";
	document.getElementById('criteriosOrdenacion').innerHTML = "";
	mostrarGrafica();
	for (i = 0; i < map.controls.length; i++){
		var control = map.controls[i];
		if(control.displayClass && control.displayClass=="olControlMouseDefaults"){
			control.switchModeTo("pan");
		}
	}
	if (document.getElementById('buscarEESS_check').selectedIndex == 0){
		document.getElementById('linkTodaEspaña').childNodes[0].nodeValue = "Descarga de estaciones de servicio de toda España";
		document.getElementById('linkPeninsulaBaleares').childNodes[0].nodeValue = "Descarga de estaciones de servicio de Peninsula y Baleares";
		document.getElementById('leyendaEESS').style.display = 'block';
		document.getElementById('leyendaPostes').style.display = 'none';
	}
	if (document.getElementById('buscarEESS_check').selectedIndex == 1){
		document.getElementById('linkTodaEspaña').childNodes[0].nodeValue = "Descarga de postes marinos de toda España";
		document.getElementById('linkPeninsulaBaleares').childNodes[0].nodeValue = "Descarga de postes marinos de Peninsula y Baleares";
		document.getElementById('leyendaEESS').style.display = 'none';
		document.getElementById('leyendaPostes').style.display = 'block';
	}
}

function habilitarCampos(){
	//if (document.getElementById('buscarEESS_check').checked){
	if (document.getElementById('buscarEESS_check').selectedIndex != 2 ){
		//Aquí activamos los elementos input
		document.getElementById('recuadro_tipocarburante').style.display = 'block';
		document.getElementById('separador_tipo_carburante').style.display = 'block';
		if (getCombustible() != 0){
			document.getElementById('economica').style.display = 'block';
			document.getElementById('venta').style.display = 'block';
		}
		document.getElementById('codigo_postal').style.display = 'block';
		//Aqui cambiamos a la etiqueta rotulo
		//document.getElementById('texto_nombre').style.display = 'none';
		document.getElementById('texto_rotulo').style.display = 'block';
		//Aqui habilitamos el boton de radio
		if (document.getElementById('OpenLayers_Control_MouseToolbar_radio_innerImage')!=null)
			document.getElementById('OpenLayers_Control_MouseToolbar_radio_innerImage').src = "../img/button_radio_2.png";
	} else {
		//Aquí desactivamos los elementos input
		document.getElementById('recuadro_tipocarburante').style.display = 'none';
		document.getElementById('separador_tipo_carburante').style.display = 'none';
		document.getElementById('economica').style.display = 'none';
		document.getElementById('venta').style.display = 'none';
		document.getElementById('codigo_postal').style.display = 'none';
		//Aqui cambiamos a la etiqueta nombre
		document.getElementById('texto_rotulo').style.display = 'none';
		//document.getElementById('texto_nombre').style.display = 'block';
		//Aqui deshabilitamos el boton de radio
		if (document.getElementById('OpenLayers_Control_MouseToolbar_radio_innerImage')!=null)
			document.getElementById('OpenLayers_Control_MouseToolbar_radio_innerImage').src = "../img/button_radio_4.png";
	}
}

function moverMapa(origen){
	var id = origen.id;
	switch (id) {
            case "iconorte":
                this.map.pan(0, -50);
                break;
            case "icosur":
                this.map.pan(0, 50);
                break;
            case "icooeste":
                this.map.pan(-50, 0);
                break;
            case "icoeste":
                this.map.pan(50, 0);
                break;
        }
}

function centrar (lon, lat, zoom){
	clearWFSResults();
	mostrarGrafica();
	var centro = new OpenLayers.LonLat(lon,lat);
	//coordenada central y zoom desde la misma (cuanto mayor zoom, más cerca del punto central)
	map.setCenter(centro, zoom);
	ponerMarca(centro);
}

function ponerMarca(centro){
	borrarMarca();
	var markers = new OpenLayers.Layer.Markers("centrar");
	map.addLayer(markers);
	var size = new OpenLayers.Size(35,35);
    var offset = new OpenLayers.Pixel(-20, -20);
    var icon = new OpenLayers.Icon('../img/circulo.gif',size,offset);
	markers.addMarker(new OpenLayers.Marker(centro,icon));
}

function borrarMarca(){
	if (map!=null){
		for( var i = 0; i < map.layers.length; i++){
			if (map.layers[i].name=="centrar"){
	    		map.layers[i].destroy();
			}
		}
	}
}

function habilitarCapas (i,check)
{
	if (i == posicionEESS+ortofotosWMS.length){
		map.layers[i].setVisibility(document.getElementById(check.id).checked, false);
		for (x=0;x<map.layers.length;x++){
			if (map.layers[x].name == "Localizacion" || map.layers[x].name == "Euro"){
				map.layers[x].setVisibility(document.getElementById(check.id).checked, false);
			}
		}
		/*this.map.layers[6].setVisibility(document.getElementById(check.id).checked, false);
		this.map.layers[7].setVisibility(document.getElementById(check.id).checked, false);*/
	} else {
		map.layers[i].setVisibility(document.getElementById(check.id).checked, false);
	}
}



function getEconomica(url, tipoComb)
{

	if (tipoComb != 0){
		urlOrigen = url;
		url = url+"&tipoCarburante="+tipoComb;
		var esOk;

		//Borramos los PopUp
		while (map.popups.length > 0){
			map.removePopup(map.popups[0]);
		}
		//Borramos la capa con las marcas
		for (x = 0; x < map.layers.length; x++){
			if (map.layers[x].name == "Localizacion"){
				map.removeLayer(map.layers[x]);
				break;
			}
		}

		YCM.successEvent.unsubscribe();
		YCM.successEvent.subscribe(
			function(type, args){
				ocultarEspera();
		        if(args[0].responseText !== undefined){
		        	var xmldoc = args[0].responseXML.documentElement;
					//Borramos los PopUp
					while (map.popups.length > 0){
						map.removePopup(map.popups[0]);
					}
					/*if (map.getLayer("Localizacion")!=null){
							map.removeLayer("Localizacion");
					}*/
					//Borramos la capa con las marcas
					for (x = 0; x < map.layers.length; x++){
						if (map.layers[x].name == "Localizacion"){
							map.removeLayer(map.layers[x]);
							break;
						}
					}

					var markers = new OpenLayers.Layer.Markers("Localizacion");
					map.addLayer(markers);
					var elemento = xmldoc.getElementsByTagName('elemento');
					for (n = 0; n < elemento.length; n ++)
					{
						var childNodesRotulo = elemento[n].getElementsByTagName('rotulo').item(0).firstChild.data;
						var childNodePrecio = elemento[n].getElementsByTagName('precio').item(0).firstChild.data;
						var childNodeX = elemento[n].getElementsByTagName('x').item(0).firstChild.data;
						var childNodeY = elemento[n].getElementsByTagName('y').item(0).firstChild.data;
						try
				        {
				        	if (document.getElementById("infoQuery_"+n) != null){
								var el = document.getElementById("infoQuery_"+n);
								var padre = el.parentNode;
								padre.removeChild(el);
							}
				        	popupQuery = new OpenLayers.Popup("infoQuery_"+n,
										new OpenLayers.LonLat(childNodeX,childNodeY),
			                            new OpenLayers.Size(popUpX, popUpY),
			                            "",
			                            false);

			                popupQuery.div.style.visibility="hidden";

			                map.addPopup(popupQuery);

							var unidadesPrecio;
							var txtitulo = textoTitulo;
							if(document.getElementById('buscarEESS_check').selectedIndex == 0){
								unidadesPrecio = unescape("%u20AC/litro");//"&euro/litro";
								txtitulo = textoTitulo;
							} else if(document.getElementById('buscarEESS_check').selectedIndex == 1) {
								txtitulo = textoTituloEmbarcaciones;
								if (document.getElementById('tiposcombustible_select_id').value == 6 ||
									document.getElementById('tiposcombustible_select_id').value == 11){
									unidadesPrecio = unescape("%u20AC/1000litros");//"&euro/1000litros";
								} else {
									unidadesPrecio = unescape("%u20AC/litro");//"&euro/litro";
								}
							}

			                var capaPop = document.getElementById("infoQuery_"+n);
			                capaPop.innerHTML = "<table class='infoServer'><tr><td class='resaltado'>"+txtitulo+"</td></tr><tr><td>"+
			                					childNodesRotulo +"</td></tr><tr><td> "+
			                					childNodePrecio + " " + unidadesPrecio + "</td></tr></table>";
			                capasPop.push(capaPop);

			                var size = new OpenLayers.Size(35,35);
	            			var offset = new OpenLayers.Pixel(-20, -20);
	            			var icon = new OpenLayers.Icon('../img/feature.png',size,offset);
	            			markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(childNodeX,childNodeY),icon));
			          	}
			          	catch(e)
			          	{
			          	}
					}
					if (markers!=null && markers.div!=null)
				        markers.events.register('mouseover',  markers, function (e)
			        	{
		        			var capaVa;
		        			for (r=0;r<markers.div.childNodes.length;r++)
		        			{
		        				try
		        				{
		        					if(!(navigator.appName=="Microsoft Internet Explorer"))
		        					{
				        				if (e.target.parentNode.id==markers.div.childNodes[r].id)
				        				{
				        					capaVa = document.getElementById("infoQuery_"+r);
				        					if(capaVa!=null)
					        					capaVa.style.visibility="visible";
				        				}
				        				else
				        				{
				        					capaVa = document.getElementById("infoQuery_"+r);
				        					if(capaVa!=null)
					        					capaVa.style.visibility="hidden";
				        				}
				        			}
				        			else
				        			{
				        				if (e.srcElement.parentNode.id==markers.div.childNodes[r].id)
				        				{
				        					capaVa = document.getElementById("infoQuery_"+r);
				        					if(capaVa!=null)
					        					capaVa.style.visibility="visible";
				        				}
				        				else
				        				{
				        					capaVa = document.getElementById("infoQuery_"+r);
				        					if(capaVa!=null)
					        					capaVa.style.visibility="hidden";
				        				}
				        			}

		        				}
		        				catch(ex)
		        				{
		        				}
		        			}
		        		});
		        }
		    }
		);
		var tipoBusqueda = document.getElementById('buscarEESS_check').selectedIndex;

		var request = YAHOO.util.Connect.asyncRequest('GET', "queryPopUp.do?urlValor="+url
						+"&tipoBusqueda="+tipoBusqueda);

	} else {
		for (x=0;x<map.popups.length;x++)
		{
			map.removePopup(map.popups[x]);
		}
	}

}

function getUserParameters(feature){

	var newLine = '';
	try{
		for (var i=0;i<popUpParameters.length; i++)
		{
			newLine=newLine+ feature.attributes[popUpParameters[i]]+"</td></tr><tr><td> ";
		}
	}
	catch (e)
	{
		return '';
	}
	return newLine
}

function getResult(center,tipoCombustible)
{
	var queryres = 0.05;
	var xmin=center.lon-queryres;
	var xmax=center.lon+queryres;
	var ymin=center.lat-queryres;
	var ymax=center.lat+queryres;
	YCM.successEvent.unsubscribe();
	YCM.successEvent.subscribe(
		function(type, args){
			ocultarEspera();
			if(args[0].responseText !== undefined){
				var texto = args[0].responseText;
	        	texto = jsstr(texto);

	        	if((texto == null)||(trim(texto)==""))
		        {
			    		borrarMarca();
			    		document.getElementById('resultseess').style.display='block';
			    		document.getElementById('resultseess').innerHTML=tituloBusqueda[26];
			    }
			    else
			    {
			    	try
			    	{
		    			var valorTexto = args[0].responseText;
		    			document.getElementById('resultseess').style.display='block';
		    			document.getElementById('resultseess').innerHTML = valorTexto;
						ponerMarca(center);

						//Controla que los campos Rotulo, direccion y localidad
						//expuestos que tengan una longitud de mas de 14
						//letras se pongan en dos filas.
						var rotuloCell = document.getElementById('rotuloCell').firstChild.nodeValue;
						var direccionCell = document.getElementById('direccionCell').firstChild.nodeValue;
						var localidadCell = document.getElementById('localidadCell').firstChild.nodeValue;

						rotuloCell = trim(rotuloCell);
						if (rotuloCell.length > 12){
							if(rotuloCell.indexOf(".")!=-1||rotuloCell.indexOf("/")!=-1||rotuloCell.indexOf(",")!=-1||rotuloCell.indexOf("-")!=-1){
								rotuloCell = rotuloCell.replace(".",". ");
								rotuloCell = rotuloCell.replace("/","/ ");
								rotuloCell = rotuloCell.replace(",",", ");
								rotuloCell = rotuloCell.replace("-"," - ");
							}
							else{
								if(rotuloCell.indexOf(" ")==-1){
									rotuloCell = rotuloCell.substring(0,12)+' '+rotuloCell.substring(12,rotuloCell.length);
								}
							}
							document.getElementById('rotuloCell').firstChild.nodeValue = trim(rotuloCell);
						}
						direccionCell = trim(direccionCell);
						if (direccionCell.length > 12){
							if(direccionCell.indexOf(".")!=-1||direccionCell.indexOf("/")!=-1||direccionCell.indexOf(",")!=-1||direccionCell.indexOf("-")!=-1){
								direccionCell = direccionCell.replace(".",". ");
								direccionCell = direccionCell.replace("/","/ ");
								direccionCell = direccionCell.replace(",",", ");
								direccionCell = direccionCell.replace("-"," - ");
							}
							else{
								if(direccionCell.indexOf(" ")==-1){
									direccionCell = direccionCell.substring(0,12)+' '+direccionCell.substring(12,direccionCell.length);
								}
							}
							document.getElementById('direccionCell').firstChild.nodeValue = trim(direccionCell);
						}
						localidadCell = trim(localidadCell);
						if (localidadCell.length > 12){
							if(localidadCell.indexOf(".")!=-1||localidadCell.indexOf("/")!=-1||localidadCell.indexOf(",")!=-1||localidadCell.indexOf("-")!=-1){
								localidadCell = localidadCell.replace(".",". ");
								localidadCell = localidadCell.replace("/","/ ");
								localidadCell = localidadCell.replace(",",", ");
								localidadCell = localidadCell.replace("-"," - ");
							}
							else{
								if(localidadCell.indexOf(" ")==-1){
									localidadCell = localidadCell.substring(0,12)+' '+localidadCell.substring(12,localidadCell.length);
								}
							}
							document.getElementById('localidadCell').firstChild.nodeValue = trim(localidadCell);
						}

		    			//Elimina los segundos de la hora
						if (document.getElementById('horaCell') != null){
							var hora = document.getElementById('horaCell').firstChild.nodeValue;
							if (hora !=null && hora.length>5)
							{
								hora= hora.substring(0, 5);
							}
							document.getElementById('horaCell').firstChild.nodeValue=hora;
						}
						//Pone las unidades al precio
						var unidadesPrecio;

						if(document.getElementById('buscarEESS_check').selectedIndex == 0){
							unidadesPrecio = unescape("%u20AC/litro");
						} else if(document.getElementById('buscarEESS_check').selectedIndex == 1) {
							if (document.getElementById('tiposcombustible_select_id').value == 6 ||
								document.getElementById('tiposcombustible_select_id').value == 11){
								unidadesPrecio = unescape("%u20AC/1000litros");
							} else {
								unidadesPrecio = unescape("%u20AC/litro");
							}
						}
						document.getElementById('precioCell').firstChild.nodeValue =
							document.getElementById('precioCell').firstChild.nodeValue +' '+ unidadesPrecio;

						//Formatea la latitud y la longitud de º ' '' a º ''
						var longitud = document.getElementById('longitudCell').firstChild.nodeValue;
						var latitud = document.getElementById('latitudCell').firstChild.nodeValue;
				        var longrados = parseInt(Math.abs(longitud));
				        var latgrados = parseInt(Math.abs(latitud));
				        var lonminutos = parseInt(Math.abs(longitud - parseInt(longitud))*60);
						var latminutos = parseInt(Math.abs(latitud - parseInt(latitud))*60);
						var lonsegundos = Math.abs(((longitud - longrados)*60) - parseInt((longitud - longrados)*60))*60;
						var latsegundos = Math.abs(((latitud - latgrados)*60) - parseInt((latitud - latgrados)*60))*60;
						var separator = ' ';
						var suffix = '';
						var digits = parseInt(numCoor);

						if (coordType==0)
       					{
					        //Para sacar las coordenadas en grados decimales
  								document.getElementById('longitudCell').firstChild.nodeValue=
  									longitud.toFixed(digits).replace('.',',');
							document.getElementById('latitudCell').firstChild.nodeValue=
								latitud.toFixed(digits).replace('.',',');

				        }
				        else if (coordType==1)
				        {
			                //Para sacar las coordenadas en grados minutos y segundos
				         	if (longitud < 0){ //Este(+) y Oeste(-)
				         		separator = 'W';
				         	}else{
				         		separator = 'E';
				         	}

				         	if (latitud < 0){//Norte(+) y sur(-)
				         		suffix = 'S';
				         	}else{
				         		suffix = 'N';
					       	}

							document.getElementById('longitudCell').firstChild.nodeValue=
								longrados + "º " + lonminutos + "' " + lonsegundos.toFixed(digits).replace('.',',') + "''" + separator;
							document.getElementById('latitudCell').firstChild.nodeValue=
								latgrados + "º " + latminutos + "' " + latsegundos.toFixed(digits).replace('.',',') + "''" + suffix;

						}
						else if (coordType==2)
						{
							//Para sacar las coordenadas en grados y segundos
				         	if (longitud < 0){ //Este(+) y Oeste(-)
				         		separator = 'W';
				         	}else{
				         		separator = 'E';
				         	}
				         	if (latitud < 0){//Norte(+) y sur(-)
				         		suffix = 'S';
				         	}else{
				         		suffix = 'N';
				         	}

							var lonseg = Math.abs(longitud - parseInt(longitud))*3600;
					        var latseg = Math.abs(latitud - parseInt(latitud))*3600;

					        if (longrados < 10 ){
								longrados = ("0").concat(longrados);
							}
							if (lonseg <10){
								separator = separator + "000";
							} else if (lonseg <100){
								separator = separator + "00";
							} else if (lonseg <1000){
								separator = separator + "0";
							}

							if (latgrados < 10 ){
								latgrados = ("0").concat(latgrados);
							}
							if (latseg <10){
								suffix = suffix + "000";
							} else if (latseg <100){
								suffix = suffix + "00";
							} else if (latseg <1000){
								suffix = suffix + "0";
							}

			         		document.getElementById('longitudCell').firstChild.nodeValue=
			         			longrados + separator + lonseg.toFixed(digits).replace('.',',');
			         		document.getElementById('latitudCell').firstChild.nodeValue=
			         			latgrados + suffix + latseg.toFixed(digits).replace('.',',');

						}
						else if (coordType==3)
						{
							//Para sacar GGLMMSS.S
				         	if (longitud < 0){ //Este(+) y Oeste(-)
				         		separator = 'W';
				         	}else{
				         		separator = 'E';
				         	}
				         	if (latitud < 0){//Norte(+) y sur(-)
				         		suffix = 'S';
				         	}else{
				         		suffix = 'N';
				         	}

				         	if (longrados < 10 ){
								longrados = ("0").concat(longrados);
							}
							if (lonminutos < 10 ){
								lonminutos = ("0").concat(lonminutos);
							}
							if (latgrados < 10 ){
								latgrados = ("0").concat(latgrados);
							}
							if (latminutos < 10 ){
								latminutos = ("0").concat(latminutos);
							}

							var lonseg = lonsegundos.toFixed(digits);
							var latseg = latsegundos.toFixed(digits);

							if (lonseg < 10 ){
								lonseg = ("0").concat(lonseg);
							}
							if (latseg < 10 ){
								latseg = ("0").concat(latseg);
							}

				        	document.getElementById('longitudCell').firstChild.nodeValue=
					            longrados + separator + lonminutos + lonseg.replace('.',',');
							document.getElementById('latitudCell').firstChild.nodeValue=
					            latgrados + suffix + latminutos + latseg.replace('.',',');

						}
				    }
				    catch(e)
				    {
				    }
			    }
			}
			else
			{
			}
		}
	);

	var tipoBusqueda = document.getElementById('buscarEESS_check').selectedIndex;

	var request = YAHOO.util.Connect.asyncRequest('GET', "queryResults.do?tipoCarburante="+tipoCombustible
				+"&BBOX="+xmin+","+xmax+","+ymin+","+ymax+"&CENTER="+center.lon+","+center.lat
				+"&tipoBusqueda="+tipoBusqueda);
}

function sendMail()
{

	if (document.forms[0].destinatario.value=="")
	{
		alert("Escriba su nombre");
	}
	else if(document.forms[0].email.value=="")
	{
		alert("Escriba su dirección de correo electrónico");
	}
	else if(document.forms[0].emailDestino.value=="")
	{
		alert("Escriba la dirección de correo electrónico a la cual desea enviar el mapa");
	}
	else if(document.forms[0].asunto.value=="")
	{
		alert("Escriba el asunto del mensaje");
	}
	else
	{
		document.forms[0].submit();
	}

}
/*
function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1].toUpperCase();
        break;
      }
    }
  }
  return unescape(strReturn);
}
*/

function layerVector()
	{

	 	for( var i = 0; i < map.layers.length; i++)
		{
	    	var currentLayer = this.map.layers[i];
	    	if (currentLayer.isVector)
	    	{
	    		return i;
	    	}
		}
	}

function delMeasure()
{
	for(i=0;i<map.controls.length;i++)
	{
		if (map.controls[i].displayClass == "olControlMouseDefaults")
		{
			if (map.controls[i].measureDivs.length > 0)
			{
				var lyrV = layerVector();

				this.map.layers[lyrV].destroyFeatures();
                for(var x = 0; x < map.controls[i].measureDivs.length; x++)
                {
                    if (map.controls[i].measureDivs[x]) {
                        map.layerContainerDiv.removeChild(map.controls[i].measureDivs[x]);
                    }
                }

                  map.controls[i].measureDivs = [];
                  map.controls[i].measureStart = null;
			}
			break;
		}
	}

}
function imprimir()
{
	var b = map.getExtent();
	var tipoBusqueda = document.getElementById('buscarEESS_check').selectedIndex;
	window.open("printMain.jsp?tipoCarburante="+getCombustible()+"&tipoBusqueda="
				+tipoBusqueda+"&minx="+b.left+"&miny="+b.bottom+"&maxx="+b.right
				+"&maxy="+b.top+"&nivzoom="+map.zoom,null,
   				"height=600,width=750,status=yes,toolbar=no,menubar=no,location=no");


}

function sendEmail()
{
	var b = map.getExtent();
	var tipoBusqueda = document.getElementById('buscarEESS_check').selectedIndex;
	window.open ("sendMail.jsp?tipoCarburante="+getCombustible()+"&tipoBusqueda="+tipoBusqueda+"&minx="+b.left+"&miny="+b.bottom+"&maxx="+b.right+"&maxy="+b.top+"&nivzoom="+map.zoom,"E_mail", "width=450px,height=550px,scrollbar=yes");
}

//function getfeatureWFS(bbox,vradio,lonlat,tipocombustible){
function getfeatureWFS(bbox,tipocombustible){
	var tipoBusqueda = document.getElementById('buscarEESS_check').selectedIndex;
	var indexCarburante = document.getElementById('tiposcombustible_select_id').selectedIndex;
	var divResultados = document.getElementById('resultadosBusqueda');
	document.getElementById('mostrarAlfanumerica').style.display='block';
	YCM.successEvent.unsubscribe();
	YAHOO.example.XHR_XML = function() {
        var formatUrlButton = function(elCell, oRecord, oColumn, sData) {
        	//if(oRecord.getData('X')!= "" && oRecord.getData('Y') != ""){
		if(oRecord.getData('X')!= "" && oRecord.getData('X')!= null && oRecord.getData('Y') != "" && oRecord.getData('Y') != null){
	            elCell.innerHTML = "<img title='"+tituloBusqueda[16]+"' " +
	            "style='cursor: pointer;' src='../img/button_recenter_tb.png' " +
	            "alt='"+tituloBusqueda[16]+"'onClick='centrar(" + oRecord.getData('X') + "," + oRecord.getData('Y') +
	            ",ZOOM_EESS)'></img>";
	        } else {
	        	elCell.innerHTML = "<img title='"+tituloBusqueda[17]+"' " +
	            "style='cursor: pointer;' src='../img/button_recenter_tb.png' " +
	            "alt='"+tituloBusqueda[17]+"'" +
	            "onClick='alert('"+tituloBusqueda[17]+"')'></img>"
	        }
        };

        var myColumnDefs = [
	            {key:"Provincia", label:tituloBusqueda[2], width:60, sortable:true},
	            {key:"Localidad", label:tituloBusqueda[3], width:60, sortable:true},
	            {key:"Direccion", label:tituloBusqueda[4], width:70, sortable:true},
	            {key:"Fecha", label:tituloBusqueda[5], width:50, sortable:true},//, formatter:YAHOO.widget.DataTable.formatDate},
	            {key:"Precio", label:tituloBusqueda[6], width:40, sortable:true},
	            {key:"Rotulo", label:tituloBusqueda[7], width:50, sortable:true},
	            {key:"TVenta", label:tituloBusqueda[8], width:55, sortable:true},
	            {key:"Remision", label:tituloBusqueda[9], width:30, sortable:true},
	            {key:"Horario", label:tituloBusqueda[10], width:90, sortable:true},
	            {key:"Centrar", label:tituloBusqueda[11], width:50, formatter:formatUrlButton}
	        ];

        var myDataSource = new YAHOO.util.DataSource("filtergasolineras.do?");
        myDataSource.connMethodPost = true;
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_XML;
        myDataSource.responseSchema = {
            resultNode: "Result",
            fields: ["Provincia","Localidad","Direccion","Fecha","Rotulo","TVenta","Remision","Horario","Precio",{key:"X",parser:"number"},{key:"Y",parser:"number"}]
        };

		var myConfigs = {
            paginator: new YAHOO.widget.Paginator({
                rowsPerPage: 10,
                pageLinks: 20
            }),
            initialRequest:"yui=true&tipoCarburante="+ tipocombustible +
			"&FILTER="+bbox.left+","+bbox.right+","+bbox.bottom+","+bbox.top+
			"&tipoBusqueda="+tipoBusqueda+
			"&textoCarburante="+document.getElementById('tiposcombustible_select_id')[indexCarburante].text + ""
        }

        var myDataTable = new YAHOO.widget.DataTable("resultadosBusqueda", myColumnDefs,
                myDataSource, myConfigs);

		var dataReturn = function(Arg0) {
			//Mostrar el numero de resultados encontrados
			document.getElementById('numResultados').innerHTML = Arg0.response.results.length;
			//Mostrar criterios de busqueda
			var busqueda = document.getElementById('criteriosBusqueda');
			busqueda.innerHTML = "Radio";
			//Mostrar criterios de ordenacion
			document.getElementById('criteriosOrdenacion').innerHTML = ordenacionResultados;
		}

		var dataSort = function(Arg0) {

			//Mostrar criterios de ordenacion
			if (Arg0.column.label == 'Precio'){
				document.getElementById('criteriosOrdenacion').innerHTML = tituloBusqueda[0];
			} else {
				document.getElementById('criteriosOrdenacion').innerHTML = tituloBusqueda[1] + Arg0.column.label +" )";
			}
		}

		myDataTable.subscribe("dataReturnEvent", dataReturn);

		myDataTable.subscribe("columnSortEvent", dataSort);

        return {
            oDS: myDataSource,
            oDT: myDataTable
        };
    }();
	/*YCM.successEvent.subscribe(
		function(type, args){
			ocultarEspera();
			if(args[0].responseText !== undefined){
				if((args[0].responseText == null)||(trim(args[0].responseText)==""))
			    {
			    	alert('Hubo problemas en la comunicación con el servidor.');
			    }
			    else
			    {
			    	try
			    	{
			    		var xmldoc = args[0].responseText;
			    		divResultados.innerHTML=xmldoc;

			    		//paginacion
						if (document.getElementsByName("DgLista").length>0)
							cargarGrid('DgLista', false)

						mostrarGrafica();
					}
				    catch(e)
				    {
				    	alert(e.message);
				    }
				}
			} else {
				alert('Hubo problemas en la comunicación con el servidor.');
			}

		}
	);

	var tipoBusqueda = document.getElementById('buscarEESS_check').selectedIndex;

	var request = YAHOO.util.Connect.asyncRequest('GET', "filtergasolineras.do?tipoCarburante="+ tipocombustible +
			"&FILTER="+bbox.left+","+bbox.right+","+bbox.bottom+","+bbox.top+
			"&tipoBusqueda="+tipoBusqueda);*/

}

function ordenacion(x,y) {
	if ( x < y ) return -1;
	if ( x > y ) return 1;
	return 0;
}




function queryFeature(center,valorX,valorY,isOver)
{

	var layers = map.layers.slice();
	var selectedFeature=null;
	for( var i = 0; i < layers.length; i++)
	{
    	var layer = layers[i];

    	if ((!layer.isBaseLayer)&&(layer.params))
    	{

    	if (layer.params.ISQUERY == "1")
		{

			if (layer.getVisibility())
			{
				if (layer.params.ISQUERY == "1")
				{
					/*var url =  layer.getFullRequestString({
       				REQUEST: "GetFeatureInfo",
			        EXCEPTIONS: "application/vnd.ogc.se_xml",
			        BBOX: layer.map.getExtent().toBBOX(),
			        X: valorX,
			        Y: valorY,
		        	INFO_FORMAT: 'text/html',
        			QUERY_LAYERS: layer.params.LAYERS,
			        WIDTH: layer.map.size.w,
			        HEIGHT: layer.map.size.h,
			        tipoCarburante: getCombustible()});

	                getResult('infoQuery',center,url,isOver);*/
					getResult(center,getCombustible());
				}
			}
        }
     }
	}

}

function jsstr(s) {
s = s.replace(/\r\n|\r/g, '');
/*s = s.replace(/\\/g, '\\\\');
s = s.replace(/'/g, '\\\'');
s = s.replace(/\n/g, '\\n');
return '\'' + s + '\'';*/
return s;
}


function getCombustible(){

	var selectcombustible = document.getElementById('tiposcombustible_select_id');
	if (selectcombustible==null)
		return tipoCarburante;

	var tipocombustible = selectcombustible.value;
	if (tipocombustible == "")
	{
		//si no hay combustible seleccionado, se selecciona Gasolina 95
		tipocombustible = "1";
		try{
			selectcombustible.options[1].selected = true;
		}catch(ex){

		}
	}
	return tipocombustible;
}

function setCombustible(tipoComb){
	if (tipoComb==null)
		tipoComb=1;
	var selectcombustible = document.getElementById('tiposcombustible_select_id');
	if (selectcombustible!=null)
		selectcombustible.options[tipoComb].selected = true;
}


function resolucion(peque){

	if (!peque){
		//Geoportal
		var anchomapa = resolucionX-484;
		var altomapa = resolucionY-308;

		document.getElementById("ContenidoPagina").style.width=anchomapa+22+'px';

		if(navigator.appName == "Netscape"){
			//Mozilla
			document.getElementById("ContenidoPagina").style.height=altomapa+22+'px';
		} else {
			//IE
			document.getElementById("ContenidoPagina").style.height=altomapa+27+'px';
		}
	} else {
	//Imprimir
		var anchomapa = 440;//480;
		var altomapa = 360;//400;

		document.getElementById("ContenidoPaginaImprimir").style.width=anchomapa+22+'px';

		if(navigator.appName == "Netscape"){
			//Mozilla
			document.getElementById("ContenidoPaginaImprimir").style.height=altomapa+22+'px';
		} else {
			//IE
			document.getElementById("ContenidoPaginaImprimir").style.height=altomapa+27+'px';
		}
	}

	document.getElementById("map").style.width=anchomapa+'px';
	document.getElementById("map").style.height=altomapa+'px';

	if (!peque)
	{
		document.getElementById("btnnorte").style.left = (anchomapa/2)-35+'px';
		document.getElementById("btnsur").style.left = (anchomapa/2)-35+'px';
		document.getElementById("btneste").style.left = anchomapa+12+'px';//232+'px';
		document.getElementById("btneste").style.top = (altomapa/2)-35+11+'px';//81+'px';
		document.getElementById("btnoeste").style.top = (altomapa/2)-35+11+'px';//81+'px';
//		document.getElementById("enlacealfa").style.left = resolucionX-784+'px';
	} else {
		document.getElementById("map").style.position='absolute';
		document.getElementById("map").style.left=10+'px';
		document.getElementById("map").style.top=10+'px';
	}

}

//Recarga la capa con las estaciones de servicio del tipo especificado en el desplegable
function layerReload()
{
	var visible = this.map.layers[posicionEESS+ortofotosWMS.length].getVisibility();

	map.removeLayer(eess);

	mostrarElementosFormulario();

	//funcionalidad eliminada correspondia a la capa de censo
	/*if(getCombustible() == 0){
		eess = new OpenLayers.Layer.WMS("Estaciones de servicio", msLocation,
				{layers: "censo", transparent: "true", format: "image/png", isQuery:"1"},
					{tileSize: new OpenLayers.Size(400,400), buffer: 1 });
		ocultarElementosFormulario();

	} else {
		eess = new OpenLayers.Layer.WMS("Estaciones de servicio", msLocation+"?tipoCarburante="+getCombustible(),
				{layers: "estaciones_servicio", transparent: "true", format: "image/png", isQuery:"1"},
				{tileSize: new OpenLayers.Size(400,400), buffer: 1 });
	}*/

	if (document.getElementById('buscarEESS_check').selectedIndex == 0){

		eess = new OpenLayers.Layer.WMS.Untiled(capasWMS[posicionEESS-1][0], capasWMS[posicionEESS-1][1]+"?tipoCarburante="+getCombustible(),
									{layers: capasWMS[posicionEESS-1][2], format: capasWMS[posicionEESS-1][3],
									transparent: capasWMS[posicionEESS-1][4],
									isQuery:capasWMS[posicionEESS-1][5],
									SRS:proyeccion,
									exceptions:capasWMS[posicionEESS-1][6]
									},
									//{tileSize: new OpenLayers.Size(256,256), buffer: 1, gutter: 15 });
									{singleTile: true, buffer: 1});

	} else if (document.getElementById('buscarEESS_check').selectedIndex == 1){

		eess = new OpenLayers.Layer.WMS.Untiled(capaWMSembarcaciones[posicionEESS-1][0], capaWMSembarcaciones[posicionEESS-1][1]+"?tipoCarburante="+getCombustible(),
									{layers: capaWMSembarcaciones[posicionEESS-1][2], format: capaWMSembarcaciones[posicionEESS-1][3],
									transparent: capaWMSembarcaciones[posicionEESS-1][4],
									isQuery:capaWMSembarcaciones[posicionEESS-1][5],
									SRS:proyeccion,
									exceptions:capaWMSembarcaciones[posicionEESS-1][6]
									},
									//{tileSize: new OpenLayers.Size(256,256), buffer: 1, gutter: 15 });
									{singleTile: true, buffer: 1});
	}

	map.addLayer(eess);
	//Se coloca en la posición donde estaba inicialmente porque el addLayer la pone al final.
	map.setLayerIndex(eess,posicionEESS+ortofotosWMS.length);

	this.map.layers[posicionEESS+ortofotosWMS.length].setVisibility(visible, false);

	//Borramos los pop-up

	for (x=0;x<map.popups.length;x++)
	{
		map.removePopup(map.popups[x]);
	}

	//limpia la capa
	if (markerEuro!=null)
		map.removeLayer(markerEuro);

	//Repintado algoritmico de las mas económica
	if (map.getScale() <= minScale && mapaNormal)
		getEconomica(urlOrigen, getCombustible());

	clearWFSResults();
}

function clearWFSResults(){
	if (document.getElementById('resultseess'))	{
		document.getElementById('resultseess').style.display='none';
		var result = document.getElementById("resultseess");
		if (result!=null)
			result.innerHTML="";

		borrarMarca();
	}
}

function popup_escala(i){
	var pop = document.getElementById('popup_escala');
	if (i){
		pop.style.visibility="visible";
	}else{
		pop.style.visibility="hidden";
	}
}

function borrar_marcas_economicas(){
	for( var i = 0; i < map.layers.length; i++){
		if (map.layers[i]!=null && map.layers[i].name=="Localizacion"){
    		map.layers[i].destroy();
    	}
    	if (map.layers[i]!=null && map.layers[i].name=="Euro") {
    		map.layers[i].destroy();
    	}
	}
    for( var i = 0; i < map.popups.length; i++){
        map.popups[i].destroy();
	}
}

function addUserWMSLayers(elemento, capasToLoad, habilitadas, isOrtof,prnt)
{
	var offsetLayers = 1;//Contamos con la capa base
	var ultimaPosicion = 0;
	if(!isOrtof){
		offsetLayers = ortofotosWMS.length+1;//Contamos las ortofotos introducidas y le sumamos 1 por la capa base
		ultimaPosicion = ortofotosWMS.length;
	}

  	//añade capas WMS dadas de alta por el administrador
  	if (capasToLoad !=null)
  	{
  		var html='';
  		var listaCapas=[];

  		for (var n=0; n<capasToLoad.length; n++)
  		{
  			var locat=capasToLoad[n][1];
  			var capa;
  			if (n == posicionEESS-1 && !isOrtof && !prnt){

  				locat=locat+"?tipoCarburante="+tipoCarburante;

  				capa = new OpenLayers.Layer.WMS.Untiled(capasToLoad[n][0], locat,
								{layers: capasToLoad[n][2], format: capasToLoad[n][3],
										 transparent: capasToLoad[n][4],
										 isQuery:capasToLoad[n][5],
										 SRS:proyeccion,
										 exceptions: capasToLoad[n][6]
								},
								//{tileSize: new OpenLayers.Size(400,400), buffer: 1 });
								//{tileSize: new OpenLayers.Size(256,256), buffer: 1, gutter: 15});
								{singleTile: true, buffer: 1});
			} else {
				capa = new OpenLayers.Layer.WMS(capasToLoad[n][0], locat,
								{layers: capasToLoad[n][2], format: capasToLoad[n][3],
										 transparent: capasToLoad[n][4],
										 isQuery:capasToLoad[n][5],
										 SRS:proyeccion,
										 exceptions: capasToLoad[n][6]
								},
								//{tileSize: new OpenLayers.Size(400,400), buffer: 1 });
								//{tileSize: new OpenLayers.Size(256,256), buffer: 1, gutter: 15});
								{tileSize: new OpenLayers.Size(256,256), buffer: 1, gutter: 15});
			}


			if (n == posicionEESS-1)
				eess = capa;

			listaCapas[n]=capa;

			//se suma 1 para situar la posicion de la capa como la siguiente a la ultima introducida.
			var pos = n+ultimaPosicion+1;

			html = html + '<div class="listdcha"><label for="'+capasToLoad[n][0].replace(/ /g,'_') +'"><input id="'+capasToLoad[n][0].replace(/ /g,'_') +'" class="inputAzul" type="checkbox" posicion='+ pos+'  alt="'+capasToLoad[n][0]+'"';

			if (habilitadas[n])
				html = html +' checked="checked" ';

			html = html +'/>&nbsp;'+capasToLoad[n][0]+"</label></div>";

  		}


  		for (var i=0; i<listaCapas.length; i++)
  		{
			//se suma offsetLayers para saber en que posicion comenzamos a introducir las nuevas capas
			var pos = i+offsetLayers;
			map.addLayer(listaCapas[i]);
			if (!prnt)
			{
				map.layers[pos].setVisibility(habilitadas[i], false);
			}

			//alert (listaCapas[i].getFullRequestString());
  		}

  		if (!prnt)
			{
	  		var lista = document.getElementById(elemento);
	  		var contLista = lista.innerHTML;

			if (lista!=null)
				lista.innerHTML=contLista+html;

			for (var n=0; n<capasToLoad.length; n++)
	  		{
	  			//Añade eventos onclick
	  			var elem=document.getElementById(capasToLoad[n][0].replace(/ /g,'_'));
				addEvent(elem,"click",function(event)
					{
						if(document.all){
							habilitarCapas(event.srcElement.attributes['posicion'].value, event.srcElement);
						}else{
							habilitarCapas(this.getAttribute('posicion'),this);
						}
					});
	  		}
	  	}
  	}
}

function getPosicion(oElem){

	var oAttribs = oElem.attributes;

    // Iterate through the collection.
    for (var i = 0; i < oAttribs.length; i++)
    {
        var oAttrib = oAttribs[i];

        // Print the name and value of the attribute.
        // Additionally print whether or not the attribute was specified
        // in HTML or script.
       alert(oAttrib.nodeName + '=' +
            oAttrib.nodeValue + ' (' + oAttrib.specified );
    }


}

function cargarGrid(idTable, bRecenter)
{
	if (idTable!=null)
	{
		//Para que el datagrid se aplique bien, es necesario estar en mostrarAlfanumerica
		mostrarAlfanumerica();
		var datagrid = new dhtmlXGridFromTable(idTable);
		try{

			if (datagrid!=null)
			{
				datagrid.enablePaging(true,TAM_TABLA,TAM_LISTA,'cuadroPaginacion', true,'cuadroPaginacion');
				//datagrid.enableBuffering(10);
				//datagrid.setSkin();
				datagrid.enableAlterCss('impar', 'par');
				datagrid._fixAlterCss();

				if(bRecenter){
					//datagrid.cellWidthPX=new Array(80,80,180,50,50,120,40,40);
//					datagrid.cellWidthPX=new Array(80,80,180,60,50,120,40,40);
					datagrid.cellWidthPX=new Array(90,90,140,60,40,110,40,40,160);
				}else{
					datagrid.cellWidthPX=new Array(270,270,50,50);
				}
				/*datagrid.cellWidthPX[1]=77;
				datagrid.cellWidthPX[2]=155;
				datagrid.cellWidthPX[5]=25;*/
				datagrid.changePage(1);



				var objbox = document.getElementById('objbox');
				var cabecera = document.getElementById('cabecera');
				//valor por defecto
				var tamgrid = 400;
				var anchogrid = 500;
				if (objbox!=null && cabecera!=null)
				{
					tamgrid = eval (objbox.firstChild.firstChild.clientHeight + cabecera.clientHeight);
					anchogrid = objbox.firstChild.firstChild.clientWidth;
					objbox.style.height=objbox.parentNode.parentNode.parentNode.parentNode.parentNode.clientHeight+'px';
				}

				var entbox = datagrid.entBox;
				if (entbox!=null)
				{
					entbox.style.height=eval(tamgrid+40)+'px';
					entbox.style.offsetHeight=eval(tamgrid+40)+'px';
//					entbox.style.width=eval(anchogrid+10)+'px';
					entbox.style.width=eval(anchogrid+20)+'px';
					entbox.style.offsetHeight=eval(anchogrid+10)+'px';
				}

				//Se centra en el resultado de la búsqueda si solo hay una y se viene de
				//una búsqueda mediante Buscar, no mediante Radio.
				if (bRecenter)
				{
					if (document.getElementsByTagAndClassName('tr', 'par').length==0)
					{
						var filasImpares = document.getElementsByTagAndClassName('tr', 'impar');
						if (filasImpares.length==1)
						{
							var funcOnClic = filasImpares[0].getAttribute('ejecutar');
							if (funcOnClic.indexOf('mostrarMensaje') == -1){
								eval(funcOnClic);
								mostrarGrafica();
							}
						}


					}
				}
			}
		}catch(e){
		}
	}


}
/*function mostrarBarraProgreso(){
	if (document.getElementById('barra')!=null)
		document.getElementById('barra').style.display = 'block';
}

function ocultarBarraProgreso(){
	if (document.getElementById('barra')!=null)
		document.getElementById('barra').style.display = 'none';
}*/

function changeBlyr(lyrName) {

for(a=0;a<map.layers.length;a++)
{
	if (map.layers[a].name == lyrName)
	{
		map.setBaseLayer(map.layers[a], true);
	}
}


}

function inicioMail() {
	addEvent(document.getElementById('botonEnviar'),"click",function(){
	sendMail();});
}

function inicioPrintMain() {
	if (document.getElementById('imprimir') != null) {
		addEvent(document.getElementById('imprimir'),"click",function(){
		//Metodo a implementar para imprimir la pantalla cuando no se acepten frame
		});
	}
}

function inicioPrint(tipoCarburante,tipoBusqueda) {

	if (document.getElementById('desplegarOverwiewMap') != null) {
		addEvent(document.getElementById('desplegarOverwiewMap'),"click",function(){
		desplegar('overviewmap');});
	}

	if (document.getElementById('listaCapasFijas') != null) {
		addEvent(document.getElementById('listaCapasFijas'),"click",function(){
		desplegar('listacapas');});
	}

	if (document.getElementById('capaIGN') != null) {
		addEvent(document.getElementById('capaIGN'),"click",function(){
		changeBlyr('IDEE');});
	}

	if (document.getElementById('capaCatastro') != null) {
		addEvent(document.getElementById('capaCatastro'),"click",function(){
		changeBlyr('Catastro');});
	}

	init(tipoCarburante,tipoBusqueda,'true');
}

function printBar(){

	if (document.getElementById('imprimir') != null) {
		addEvent(document.getElementById('imprimir'),"click",function(){
		framePrint('mainFrame');});
	}

	if (document.getElementById('cerrar') != null) {
		addEvent(document.getElementById('cerrar'),"click",function(){
		window.parent.close();});
	}
}

function numbersonly(e)
{
	var key;
	var keychar;

	if (window.event)
		key = window.event.keyCode;
	else if (e)
		key = e.which;
	else
		return true;

	keychar = String.fromCharCode(key);

	// control keys
	if ((key==null) || (key==0) || (key==8) ||
          (key==9) || (key==13) || (key==27) )
	{
          return;
	}
    // numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	{
		return;
	}
	else
    {
		//IE - detiene la propagacion del evento
		e.cancelBubble = true;
		E.returnValue = false;

		//Firefox - detiene la propagacion del evento
		if (e.stopPropagation) {
			e.stopPropagation();
			e.preventDefault();
		}
	}
}

function inicioComprobarLonLat()
{
	addEvent(document.getElementById('icooeste'),"click",function(){
	moverMapa(document.getElementById('icooeste'));});

	addEvent(document.getElementById('iconorte'),"click",function(){
	moverMapa(document.getElementById('iconorte'));});

	addEvent(document.getElementById('icosur'),"click",function(){
	moverMapa(document.getElementById('icosur'));});

	addEvent(document.getElementById('icoeste'),"click",function(){
	moverMapa(document.getElementById('icoeste'));});

	if (document.getElementById('capaIGN') != null) {
		addEvent(document.getElementById('capaIGN'),"click",function(){
		changeBlyr('IDEE');});
	}

	if (document.getElementById('capaCarto') != null) {
		addEvent(document.getElementById('capaCarto'),"click",function(){
		changeBlyr('Cartociudad');});
	}

	if (document.getElementById('capaCatastro') != null) {
		addEvent(document.getElementById('capaCatastro'),"click",function(){
		var capa;
		for( var i = 0; i < map.layers.length; i++)
		{
	    	if (map.layers[i].name=='Catastro')
	    	{
	    		capa = map.layers[i];
	    	}
    	}
		capa.setVisibility(document.getElementById('capaCatastro').checked, false);});
	}

	if (document.getElementById('capaPnoa') != null) {
		addEvent(document.getElementById('capaPnoa'),"click",function(){
		var capa;
		for( var i = 0; i < map.layers.length; i++)
		{
	    	if (map.layers[i].name=='Pnoa')
	    	{
	    		capa = map.layers[i];
	    	}
    	}
		capa.setVisibility(document.getElementById('capaPnoa').checked, false);});
	}

	var lon = new Number(getURLParam(nomLon));
	var lat = new Number(getURLParam(nomLat));

	if(!lon || !lat || lon == "" || lat == ""){
		//Si no pasamos una longitud y una latitud no se pueden cargar las capas
		//En el proyecto de hidrocarburos no existe esta pagina
		//window.location = webLocation + "/error.html" + "?param="+nomLon+","+nomLat;
	} else {

		inicializarFormulariosLonLat(lon,lat);

		//Añadimos los controles al mapa
		OpenLayers.Control.MouseToolbar.X = 0;
		OpenLayers.Control.MouseToolbar.Y = 50;

		//TODO: hacer el equivalente para hidrocarburos
		//addControlMap('buttonRight','vertical',2);

		//Añadimos la brujula
		//addBrujula();

		//Centramos en el punto que nos han dado
		//map.setCenter( new OpenLayers.LonLat(lon, lat), 7);

		//Añadimos la capa virtual con la Estacion de Comunicaciones
		markers = new OpenLayers.Layer.Markers("Estaciones");
		map.addLayer(markers);
		markers.displayInLayerSwitcher = false;

		size = new OpenLayers.Size(16,16);
		//(-20, -20);
		offset = new OpenLayers.Pixel(-8,-8);
		icon = new OpenLayers.Icon(this.urlIcon,size,offset);
		markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(lon,lat),icon));

		//consultaProvincia();

		addEvent(document.getElementById('aceptar'),"click",function(){
		aceptarCambio();});

		addEvent(document.getElementById('cancelar'),"click",function(){
		cancelarCambio();});
	}
}

function moverEstacion(evt){

	var posicion = this.map.getLonLatFromViewPortPx( evt.xy );
	var longrados = parseInt(Math.abs(posicion.lon));
	var latgrados = parseInt(Math.abs(posicion.lat));
	var lonminutos = parseInt(Math.abs(posicion.lon - parseInt(posicion.lon))*60);
	var latminutos = parseInt(Math.abs(posicion.lat - parseInt(posicion.lat))*60);
	var lonsegundos = Math.abs(((posicion.lon - longrados)*60) - parseInt((posicion.lon - longrados)*60))*60;
	var latsegundos = Math.abs(((posicion.lat - latgrados)*60) - parseInt((posicion.lat - latgrados)*60))*60;
	var separator = ' ';
	var suffix = '';
	var digits = parseInt(numCoor);

	this.getLayerByName('Estaciones').clearMarkers();
	this.getLayerByName('Estaciones').addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(posicion.lon,posicion.lat),icon));

	//Formateamos la salida en formato GGLMMSS.S

	if (posicion.lon < 0){ //Este(+) y Oeste(-)
		separator = 'W';
	}else{
		separator = 'E';
	}
	if (posicion.lat < 0){//Norte(+) y sur(-)
		suffix = 'S';
	}else{
		suffix = 'N';
	}

	if (longrados < 10 ){
		longrados = ("0").concat(longrados);
	}
	if (lonminutos < 10 ){
		lonminutos = ("0").concat(lonminutos);
	}
	if (latgrados < 10 ){
		latgrados = ("0").concat(latgrados);
	}
	if (latminutos < 10 ){
		latminutos = ("0").concat(latminutos);
	}

	var lonseg = lonsegundos.toFixed(digits);
	var latseg = latsegundos.toFixed(digits);

	if (lonseg < 10 ){
		lonseg = ("0").concat(lonseg);
	}
	if (latseg < 10 ){
		latseg = ("0").concat(latseg);
	}


	//Actualizamos la informacion del formulario
	//document.getElementById("latitud").value = posicion.lat;
	//document.getElementById("longitud").value = posicion.lon;
	document.getElementById("latitud").value = latgrados + suffix + latminutos + latseg.replace('.',',');
	document.getElementById("longitud").value = longrados + separator + lonminutos + lonseg.replace('.',',');

	document.getElementById("latitud_oculto").value = posicion.lat;
	document.getElementById("longitud_oculto").value = posicion.lon;

}

function getLayerByName(nombre){
	for( var i = 0; i < map.layers.length; i++)
	{
    	if (map.layers[i].name==nombre)
    	{
    		return map.layers[i];
    	}
    }
}

function inicializarFormulariosLonLat(lon,lat)
{
	var longrados = parseInt(Math.abs(lon));
	var latgrados = parseInt(Math.abs(lat));
	var lonminutos = parseInt(Math.abs(lon - parseInt(lon))*60);
	var latminutos = parseInt(Math.abs(lat - parseInt(lat))*60);
	var lonsegundos = Math.abs(((lon - longrados)*60) - parseInt((lon - longrados)*60))*60;
	var latsegundos = Math.abs(((lat - latgrados)*60) - parseInt((lat - latgrados)*60))*60;
	var separator = ' ';
	var suffix = '';
	var digits = parseInt(numCoor);

	if (lon < 0){ //Este(+) y Oeste(-)
		separator = 'W';
	}else{
		separator = 'E';
	}
	if (lat < 0){//Norte(+) y sur(-)
		suffix = 'S';
	}else{
		suffix = 'N';
	}

	if (longrados < 10 ){
		longrados = ("0").concat(longrados);
	}
	if (lonminutos < 10 ){
		lonminutos = ("0").concat(lonminutos);
	}
	if (latgrados < 10 ){
		latgrados = ("0").concat(latgrados);
	}
	if (latminutos < 10 ){
		latminutos = ("0").concat(latminutos);
	}

	var lonseg = lonsegundos.toFixed(digits);
	var latseg = latsegundos.toFixed(digits);

	if (lonseg < 10 ){
		lonseg = ("0").concat(lonseg);
	}
	if (latseg < 10 ){
		latseg = ("0").concat(latseg);
	}


	//Actualizamos la informacion del formulario
	//document.getElementById("latitud").value = posicion.lat;
	//document.getElementById("longitud").value = posicion.lon;
	document.getElementById("latitud").value = latgrados + suffix + latminutos + latseg.replace('.',',');
	document.getElementById("longitud").value = longrados + separator + lonminutos + lonseg.replace('.',',');

	document.getElementById("latitud_oculto").value = lat;
	document.getElementById("longitud_oculto").value = lon;

}

function aceptarCambio(){
	window.parent.opener.document.getElementById(nomLon).value = document.getElementById("longitud_oculto").value;
	window.parent.opener.document.getElementById(nomLat).value = document.getElementById("latitud_oculto").value;
	window.parent.close();
}

function cancelarCambio(){
	window.parent.close();
}

function inicioError(){
	var strReturn= "";
	//La siguiente linea necesita "window.parent" en vez de "window" porque trabajamos con Frames
	var strHref = window.location.href;
	if ( strHref.indexOf("?") > -1 ){
		var strQueryString = strHref.substr(strHref.indexOf("?"));//.toLowerCase();
		var aQueryString = strQueryString.split("&");
		for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
			if (aQueryString[iParam].indexOf("param".toLowerCase() + "=") > -1 ){
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];//.toUpperCase();
				if(strReturn.indexOf("#")>-1)
					strReturn = strReturn.substr(0, strReturn.indexOf("#"));
        		break;
        	}
        }
	}
	document.getElementById("mensaje").innerHTML = "ERROR, se necesitan los parametros (" + strReturn + ")</br>";
}

function changeBaseLayer(layer) {
	map.setBaseLayer(layer);
}