/**
 * cadelayers.js: several utilities for layer manipulation, etc. for
 *                the CadeMET project, using the OpenLayers library.
 *
 * by Eduardo Hernando Izcara. Copyright 2009 agroGEX.
 */
// ------------------------------------------------------------------------

// Make sure we haven't already been loaded
var CadeLayers;
if (CadeLayers && (typeof CadeLayers != "object" || CadeLayers.NAME))
{
	throw new Error("Namespace 'CadeLayers' already exists");
}

// Create our namespace, and specify some meta-information
CadeLayers = {};
CadeLayers.NAME = "CadeLayers";    // The name of this namespace
CadeLayers.VERSION = 1.0;          // The version of this namespace


// Algunas variables globales del namespace:
CadeLayers.map = null;
CadeLayers.stations = {};
CadeLayers.layer_MapServerExample = null;
CadeLayers.layer_Ortofoto = null;
CadeLayers.layer_Catastro = null;
CadeLayers.layer_MDT25m = null;

CadeLayers.map_options = {
	maxExtent: new OpenLayers.Bounds(450000, 4724000, 468000, 4738000),
	//maxExtent: new OpenLayers.Bounds(455000, 4726000, 465000, 4736000),
	maxResolution: 'auto',
	projection:"EPSG:23030",
	//projection:"EPSG:25830",
	units: "meters",
	numZoomLevels: 8,
	tileSize: new OpenLayers.Size(420/4, 320/4),
	//theme: null,
	//theme: "http://openlayers.org/api/theme/default/style.css",
	controls: [] };

CadeLayers.selectStation = null;
CadeLayers.selectedStation = null;
//var selectStation, selectedStation;

CadeLayers.selectClick = null;

// ------------------------------------------------------------------------

CadeLayers.clickMapa = function(e)
{
	if (CadeLayers.selectedStation)
	{
		Rutinas.clsMenus('stations-link');
		//CadeLayers.onStationUnselect(CadeLayers.selectedStation);
		CadeStations.render_station(CadeLayers.selectedStation.attributes);
		CadeLayers.centerStation(CadeLayers.selectedStation.geometry.x, CadeLayers.selectedStation.geometry.y);
	}
}
// ------------------------------------------------------------------------

CadeLayers.onPopupClose = function(evt)
{
	//CadeLayers.selectStation.unselect(CadeLayers.selectedStation);
}
// ------------------------------------------------------------------------

CadeLayers.onStationSelect = function(feature)
{
	CadeLayers.selectedStation = feature;

	var humedad_hojas;
	if (feature.attributes.hf >= 0 && feature.attributes.hf <= 65)
		humedad_hojas = "Mojado";
	else if (feature.attributes.hf > 65 && feature.attributes.hf <= 150)
		humedad_hojas = "Húmedo";
	else if (feature.attributes.hf > 150 && feature.attributes.hf <= 255)
		humedad_hojas = "Seco";
	else
		humedad_hojas = "Indefinido";

	// Se comprueba valores nulos o no disponibles (-9999) para resto de parámetros:
	if (feature.attributes.temp == -9999) feature.attributes.temp = 'NA';
	if (feature.attributes.pp == -9999) feature.attributes.pp = 'NA';
	if (feature.attributes.hr == -9999) feature.attributes.hr = 'NA';
	if (feature.attributes.vel == -9999) feature.attributes.vel = 'NA';

	var information = "<div id='info_mapa'>Últimos datos <b>" + feature.attributes.nombre + "</b>";
	information += "<br />(" + feature.attributes.time + ")";
	information += "<br /><b>Temperatura del aire: </b>" + feature.attributes.temp + " ºC";
	information += "<br /><b>Precipitación: </b>" + feature.attributes.pp + " mm";
	information += "<br /><b>Humedad relativa: </b>" + feature.attributes.hr + "%";
	information += "<br /><b>Velocidad del viento: </b>" + feature.attributes.vel + " km/h";
	information += "<br /><b>Estado de las hojas: </b>" + humedad_hojas + "</div>";

	var popup = new OpenLayers.Popup.Anchored("chicken", 
						feature.geometry.getBounds().getCenterLonLat(),
						new OpenLayers.Size(220,110),
						information,
						null, false, CadeLayers.onPopupClose);
	feature.popup = popup;
	CadeLayers.map.addPopup(popup);

	var infomapa = document.getElementById('info_mapa');
	infomapa.parentNode.style.background = '#eae3bb';
	//infomapa.parentNode.style.margin = '8px';
	//infomapa.parentNode.style.padding = '2px';
	infomapa.parentNode.style.border = '1px solid #ccc';

	YAHOO.util.Event.addListener(infomapa.parentNode, 'click', CadeLayers.clickMapa);
}
// ------------------------------------------------------------------------

CadeLayers.onStationUnselect = function(feature)
{
	YAHOO.util.Event.purgeElement(document.getElementById('info_mapa').parentNode);

	CadeLayers.map.removePopup(feature.popup);
	feature.popup.destroy();
	feature.popup = null;

	CadeLayers.selectedStation = null;
}    
// ------------------------------------------------------------------------

CadeLayers.init = function(map_div)
{
	//CadeLayers.map = new OpenLayers.Map('map');
	CadeLayers.map = new OpenLayers.Map(map_div, CadeLayers.map_options);

	//CadeLayers.map.addControl(new OpenLayers.Control.LayerSwitcher());
	CadeLayers.map.addControl(new OpenLayers.Control.PanPanel());
	CadeLayers.map.addControl(new OpenLayers.Control.ZoomPanel());
	CadeLayers.map.addControl(new OpenLayers.Control.Navigation());
	CadeLayers.map.addControl(new OpenLayers.Control.MousePosition());
	//CadeLayers.map.addControl(new OpenLayers.Control.KeyboardDefaults());

	/*
	CadeLayers.layer_MapServerExample = new OpenLayers.Layer.MapServer( "OpenLayers WMS", "http://cademet.ibersig.net/cgi-bin/mapserv",
				{
					map_transparent: 'ON',
					map: '/var/www/fanegawebs/public_html/cademet.ibersig.net/world_factbk/qproy.map',
					layers: 'arena provincia'
				}, { singleTile: true, opacity: 0.5, isBaseLayer: false } );
	CadeLayers.layer_MapServerExample = new OpenLayers.Layer.MapServer( "OpenLayers WMS", "http://cademet.ibersig.net/cgi-bin/mapserv",
				{
					map_transparent: 'ON',
					map: '/var/www/fanegawebs/public_html/cademet.ibersig.net/qproy.map',
					layers: 'arena'
				}, { singleTile: true } );
	*/
	//CadeLayers.layer_Ortofoto = new OpenLayers.Layer.WMS( "Ortofoto", "http://wms.itacyl.es/Server/SgdWms.dll/WMS",
	CadeLayers.layer_Ortofoto = new OpenLayers.Layer.WMS( "Ortofoto", "http://orto.wms.itacyl.es/Server/SgdWms.dll/WMS",
				{
					//layers: 'PNOA_CYL_COLOR',
					layers: 'Ortofoto_CyL',
					//srs: 'epsg:25830',
					format: 'image/jpeg'
				}, { singleTile: true, gutter: 2, isBaseLayer: true, displayOutsideMaxExtent: true, transitionEffect: 'resize' } );
	/*
	CadeLayers.layer_Catastro = new OpenLayers.Layer.WMS( "Catastro", "http://ovc.catastro.meh.es/Cartografia/WMS/ServidorWMS.aspx",
				{
					layers: 'Catastro',
					//srs: 'epsg:25830',
					format: 'image/png',
					transparent: 'true'
				}, { gutter: 2, isBaseLayer: false } );

	CadeLayers.layer_MDT25m = new OpenLayers.Layer.WMS( "MDT25m", "http://www.sitcyl.jcyl.es:80/wms/com.esri.wms.Esrimap/ImagenesRaster",
				{
					layers: '82',
					//srs: 'epsg:25830',
					format: 'image/jpeg'
				}, { gutter: 2, isBaseLayer: true } );
	*/
	//CadeLayers.map.addLayers([CadeLayers.layer_MapServerExample, CadeLayers.layer_Ortofoto, CadeLayers.layer_Catastro, CadeLayers.layer_MDT25m]);
	//CadeLayers.map.addLayer(CadeLayers.layer_MapServerExample);
	CadeLayers.map.addLayer(CadeLayers.layer_Ortofoto);
	//CadeLayers.map.addLayer(CadeLayers.layer_Catastro);

	CadeLayers.stations = new OpenLayers.Layer.Vector("Estaciones", {
			styleMap: new OpenLayers.StyleMap({
				"default": new OpenLayers.Style(OpenLayers.Util.applyDefaults({
					externalGraphic: "http://www.openlayers.org/api/img/marker-gold.png",
					//externalGraphic: "img/punto_oro.png",
					graphicOpacity: 1,
					//rotation: -30,
					pointRadius: 10,
					//cursor: "hand"
					cursor: "pointer"
				}, OpenLayers.Feature.Vector.style["default"])),
				"select": new OpenLayers.Style({
					//externalGraphic: "http://www.openlayers.org/api/img/marker-blue.png"
					pointRadius: 12,
					cursor: "pointer"
				})
			})
	});

	CadeLayers.map.addLayer(CadeLayers.stations);

	/*
	NOMBRE		   X	   Y
	Salas B.	461150	4727147
	Rucandio	456119	4732241
	Madrid C.	455155	4735681
	Oña			463223	4731213
	*/
	var data_salas = document.getElementsByName('data_salas')[0].value.split("|");
	var data_rucandio = document.getElementsByName('data_rucandio')[0].value.split("|");
	var data_madrid = document.getElementsByName('data_madrid')[0].value.split("|");
	var data_bentretea = document.getElementsByName('data_bentretea')[0].value.split("|");

	CadeLayers.stations.addFeatures([
		new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Point(461150, 4727147), {
				cod:	data_salas[0],
				nombre:	data_salas[1],
				time:	data_salas[2],
				temp:	data_salas[3],
				pp:		data_salas[4],
				hr:		data_salas[5],
				vel:	data_salas[6],
				hf:		data_salas[7]
			}),
		new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Point(456119, 4732241), {
				cod:	data_rucandio[0],
				nombre:	data_rucandio[1],
				time:	data_rucandio[2],
				temp:	data_rucandio[3],
				pp:		data_rucandio[4],
				hr:		data_rucandio[5],
				vel:	data_rucandio[6],
				hf:		data_rucandio[7]
			}),
		new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Point(455155, 4735681), {
				cod:	data_madrid[0],
				nombre:	data_madrid[1],
				time:	data_madrid[2],
				temp:	data_madrid[3],
				pp:		data_madrid[4],
				hr:		data_madrid[5],
				vel:	data_madrid[6],
				hf:		data_madrid[7]
			}),
		new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Point(463223, 4731213), {
				cod:	data_bentretea[0],
				nombre:	data_bentretea[1],
				time:	data_bentretea[2],
				temp:	data_bentretea[3],
				pp:		data_bentretea[4],
				hr:		data_bentretea[5],
				vel:	data_bentretea[6],
				hf:		data_bentretea[7]
			})
	]);

	CadeLayers.selectStation = new OpenLayers.Control.SelectFeature(CadeLayers.stations,{
										multiple: false, hover: true,
										toggleKey: "ctrlKey",  // ctrl key removes from selection
										multipleKey: "shiftKey",  // shift key adds to selection
										onSelect: CadeLayers.onStationSelect,
										onUnselect: CadeLayers.onStationUnselect
									});
	CadeLayers.map.addControl(CadeLayers.selectStation);
	CadeLayers.selectStation.activate();

	CadeLayers.map.zoomToMaxExtent();

	YAHOO.util.Event.addListener("mapa", 'click', CadeLayers.clickMapa);
}
// ------------------------------------------------------------------------

CadeLayers.centerStation = function(x, y)
{
	CadeLayers.map.setCenter(new OpenLayers.LonLat(x,y), 5);
}
// ------------------------------------------------------------------------


