//var selectControl, selectedFeature;

OpenLayersXeografiaFacade = function(map) {

	this.init(map);
}

jQuery.extend(OpenLayersXeografiaFacade.prototype, {
	
		map: null,
		
		layers: [],
		
		numLayers: 0,
		
		selectControl: null,
		
		selectedFeature: null,

		init: function(map){
	
			this.map = map;
		},
		
		obterEstiloPunto: function(){
			
			//Definimos un estilo para debuxar as 'features' sobre o mapa. 
			
			var style = new OpenLayers.Style({},{
				
		        context: {
				
	            image: function(feature) {
	    		
					if(feature.attributes.count > 1){
						
						//return "";
						
						if(feature.cluster[0].attributes.tipo == 'monumento') return './icons/brown.png';
		    			if(feature.cluster[0].attributes.tipo == 'museo') return './icons/blue.png';
		    			if(feature.cluster[0].attributes.tipo == 'balneario') return './icons/gray.png';
		    			if(feature.cluster[0].attributes.tipo == 'praia') return './icons/orange.png';
		    			if(feature.cluster[0].attributes.tipo == 'xacemento') return './icons/red.png';
					}
					else{
						
						if(feature.cluster[0].attributes.tipo != 'poboacion')
							return "./icons/"+feature.cluster[0].attributes.tipo+".png";
						else
							return "./icons/"+feature.cluster[0].attributes.tipo+feature.cluster[0].attributes.subtipo+".png";
					}
	    		},
	    		
	    		numeroElementos: function(feature) {
	    			
	    			if(feature.attributes.count>1){
	    				
	    				return "";
	    			}
	    			else{
	    				
	    				return "";
	    			}
	    		},
	    		
	    		cor: function(feature) {
	    			
//	    			if(feature.cluster[0].attributes.tipo == 'monumento') return '#6F4612';
//	    			if(feature.cluster[0].attributes.tipo == 'museo') return '#3D59D3';
//	    			if(feature.cluster[0].attributes.tipo == 'balneario') return '#BABABC';
//	    			if(feature.cluster[0].attributes.tipo == 'praia') return '#FF9D69';
//	    			if(feature.cluster[0].attributes.tipo == 'xacemento') return '#ED7878';

					if(feature.cluster[0].attributes.tipo == 'monumento') return './icons/brown.png';
	    			if(feature.cluster[0].attributes.tipo == 'museo') return './icons/blue.png';
	    			if(feature.cluster[0].attributes.tipo == 'balneario') return './icons/gray.png';
	    			if(feature.cluster[0].attributes.tipo == 'praia') return './icons/orange.png';
	    			if(feature.cluster[0].attributes.tipo == 'xacemento') return './icons/red.png';
	    		},

	    		title: function(feature){
	    			
	    			if(feature.attributes.count > 1){
	    				
	    				return "Prema para despregar "+feature.attributes.count+" puntos";
	    			}
	    			else{
	    				
	    				return feature.cluster[0].attributes.nome;
	    			}
	    		}
	    	}});

			var regraLonxe = new OpenLayers.Rule({
				
			
				  symbolizer: {
				
						pointRadius: 6,
				        //fillColor: "${cor}",
				        fillOpacity: 1,
				        //graphicName: "square",
				        externalGraphic: "${image}",
				        graphicTitle: "${title}",
				        strokeColor: "black",
				        strokeWidth: 1,
				        strokeOpacity: 1,
				        cursor: "pointer",
				        label: "${numeroElementos}",
				        fontSize: "9px",
				        fontWeight: "bold",
				        fontColor: "white"
				  }
			});

			style.addRules([regraLonxe]);
			
			return style;
		},
		
		obterEstiloEspacio: function(){
			
			//Definimos un estilo para debuxar as 'features' sobre o mapa. 
			
			var style = new OpenLayers.Style();

			var regraLonxe = new OpenLayers.Rule({

				  symbolizer: {
				
				        fillColor: "green",
				        fillOpacity: 0.3,
				        strokeColor: "black",
				        strokeWidth: 1,
				        strokeOpacity: 1,
				        cursor: "pointer"
				  }
			});

			style.addRules([regraLonxe]);
			
			return style;
		},
		
		obterEstiloRio: function(){
			
			//Definimos un estilo para debuxar as 'features' sobre o mapa. 
			
			var style = new OpenLayers.Style();

			var regraLonxe = new OpenLayers.Rule({

				  symbolizer: {
				
				        fillColor: "blue",
				        fillOpacity: 0.5,
				        strokeColor: "blue",
				        strokeWidth: 1,
				        strokeOpacity: 1,
				        cursor: "pointer"
				  }
			});

			style.addRules([regraLonxe]);
			
			return style;
		},
		
		obterCapaPunto: function(nome, requestUrl){
			
			var layer = new OpenLayers.Layer.Vector(nome, {
				
                strategies: [
                    new OpenLayers.Strategy.Fixed(),
                    new OpenLayers.Strategy.Cluster({distance:13})
                ],
                protocol: new OpenLayers.Protocol.HTTP({
                    url: requestUrl,
                    format: new OpenLayers.Format.GML({geometryName: "punto_geom"})
                }),
                styleMap: new OpenLayers.StyleMap({
		            "default": this.obterEstiloPunto()
		        }),
		        displayInLayerSwitcher: false,
		        preFeatureInsert: function(feature){
					
					if(feature.cluster[0].attributes.tipoxeometria == 'punto')
						feature.geometry.transform(new OpenLayers.Projection("EPSG:23029"),new OpenLayers.Projection("EPSG:900913"));
				}
			});
			
			return layer;
			
		},
		
		obterCapaEspacio: function(nome, requestUrl){
			
			var layer = new OpenLayers.Layer.Vector(nome, {
				
                strategies: [
                    new OpenLayers.Strategy.Fixed()
                ],
                protocol: new OpenLayers.Protocol.HTTP({
                    url: requestUrl,
                    format: new OpenLayers.Format.GML({geometryName: "poly_geom"})
                }),
                styleMap: new OpenLayers.StyleMap({
		            "default": this.obterEstiloEspacio()
		        }),
		        displayInLayerSwitcher: false
			});
			
			return layer;
		},
		
		obterCapaRio: function(nome, requestUrl){
			
			var layer = new OpenLayers.Layer.Vector(nome, {
				
                strategies: [
                    new OpenLayers.Strategy.Fixed()
                ],
                protocol: new OpenLayers.Protocol.HTTP({
                    url: requestUrl,
                    format: new OpenLayers.Format.GML({geometryName: "line_geom"})
                }),
                styleMap: new OpenLayers.StyleMap({
		            "default": this.obterEstiloRio()
		        }),
		        displayInLayerSwitcher: false
			});
			
			return layer;
		},

		buscar: function(palabraClave, tipo, subtipo, concello, nome){
			
			var layer = null;
			
			if(this.map.getLayersByName(nome).length == 0){
					
				requestUrl = '/geoserver/wfs?SERVICE=WFS&VERSION=1.0.0&REQUEST=getfeature&typename=patrimonio:vm_xeografia_tipo';
				
				if(palabraClave!='' || tipo!='' || concello!=''){
				
					requestUrl = requestUrl+'&Filter=<Filter><And>';
					
					if(palabraClave!=''){
						
						palabras = palabraClave.split(" ");
						requestUrl = requestUrl+"<And>";
						
						for(p in palabras){
							
							requestUrl = requestUrl+'<PropertyIsLike wildCard="*" singleChar="?" escapeChar="!"><PropertyName>nomebusca</PropertyName><Literal>*'+utf8Encode(palabras[p]).toUpperCase()+'*</Literal></PropertyIsLike>';
						}
						
						requestUrl = requestUrl+"</And>";
					}
					
					if(tipo!=''){
						
						tipos = tipo.split(",");
						requestUrl = requestUrl+"<Or>";
						
						for(t in tipos){
							
							requestUrl = requestUrl+'<PropertyIsEqualTo><PropertyName>tipo</PropertyName><Literal>'+utf8Encode(tipos[t])+'</Literal></PropertyIsEqualTo>';
						}
						
						requestUrl = requestUrl+"</Or>";	
						//requestUrl = requestUrl+'<PropertyIsEqualTo><PropertyName>tipo</PropertyName><Literal>'+utf8Encode(tipo)+'</Literal></PropertyIsEqualTo>';
					}
					
					if(subtipo!=''){
						
						requestUrl = requestUrl+'<PropertyIsEqualTo><PropertyName>subtipo</PropertyName><Literal>'+utf8Encode(subtipo)+'</Literal></PropertyIsEqualTo>';
					}
					
					if(concello!=''){
						
						requestUrl = requestUrl+'<PropertyIsLike wildCard="*" singleChar="?" escapeChar="!"><PropertyName>concello</PropertyName><Literal>*'+utf8Encode(concello)+'*</Literal></PropertyIsLike>';
					}
	
					requestUrl = requestUrl+'</And></Filter>';
				}
				
				if(tipo == 'espacio'){
					
					layer = this.obterCapaEspacio(nome, requestUrl);
				}
				else{
					
					if(tipo == 'rio'){
						
						layer = this.obterCapaRio(nome, requestUrl);
					}
					else{
						
						layer = this.obterCapaPunto(nome, requestUrl);
					}
				}
				
				this.map.addLayers([layer]);
				this.layers[this.numLayers] = layer;
				this.numLayers = this.numLayers+1;
				this.actualizarControl();
				
			}else{
				
				layer = this.map.getLayersByName(nome)[0];
				this.map.getLayersByName(nome)[0].setVisibility(true);
			}
			
			return layer;
		},
			
		engadirTipo: function(tipo, subtipo){
			
			//v.1
			this.buscar('', tipo, subtipo, '', tipo+subtipo);
			
			//v.2
//			this.borrarBusca('tipos');
//			this.buscar('', tipo, subtipo, '', 'tipos');
		},

		borrarTipo: function(tipo,subtipo){
			
			this.map.getLayersByName(tipo+subtipo)[0].setVisibility(false);
		},
		
		borrarBusca: function(nomeCapa){
			
			for(l in this.layers){
				
				if(this.layers[l].name == nomeCapa){
					
					this.layers[l].destroy();
				}

			}

			//this.map.setBaseLayer(this.map.getLayersByClass("OpenLayers.Layer.WMS")[0]);
			//this.map.zoomTo(0);
			this.actualizarControl();
		},
		
		borrarTodo: function(){
			
			for(l in this.layers){
				this.layers[l].destroy();
			}
			this.map.setBaseLayer(this.map.getLayersByClass("OpenLayers.Layer.WMS")[0]);
			this.map.zoomTo(0);
			this.actualizarControl();
		},
		
		engadirBusca: function(palabraClave, tipo, concello, subtipo){
			
			this.borrarBusca('resultadoBusca');
			var layer = this.buscar(palabraClave, tipo, subtipo, concello, 'resultadoBusca');
			
			layer.events.register("loadend",{"layer":layer,"map":this.map},function(){
				
				if(this.layer.features.length > 0){
					
					this.map.zoomToExtent(this.layer.getDataExtent());
					this.map.zoomToExtent(this.layer.getDataExtent());
					this.map.setBaseLayer(this.map.getLayersByClass("OpenLayers.Layer.Google")[0]);
					if(this.map.zoom > 5) this.map.zoomTo(5);
				}
				else{
					
					alert("Non se atoparon elementos");
				}
			});
			
			
			this.map.addLayers([layer]);
		},
		
		engadirCercanos: function(lon,lat,radio){
			
			ll = new OpenLayers.LonLat(lon,lat);
			ll.transform(new OpenLayers.Projection("WGS84"),
					     new OpenLayers.Projection("EPSG:900913"));
			this.map.setCenter(ll,4);

			var bbox = ""+this.map.getExtent().transform(new OpenLayers.Projection("EPSG:900913"),
			new OpenLayers.Projection("EPSG:23029")).toBBOX();
		    
			requestUrl = '/geoserver/wfs?SERVICE=WFS&VERSION=1.0.0&REQUEST=getfeature&typename=patrimonio:vm_xeografia_tipo';
			requestUrl = requestUrl+'&BBOX=' + bbox;
			layer = this.obterCapaPunto('resultadoBusca', requestUrl);
			
			this.map.addLayers([layer]);
			this.layers[this.numLayers] = layer;
			this.numLayers = this.numLayers+1;
			this.actualizarControl();
		},
		
		onPopupClose: function(evt) {
			
		    this.selectControl.unselect(this.selectedFeature);
		},
		
		desmarcarFeature: function() {
			
			if(this.selectControl && this.selectedFeature)
				this.selectControl.unselect(this.selectedFeature);
		},

		actualizarControl: function(){
			
			//Actualiza o control 'SelectFeature' cada vez que se engade ou elimina unha capa. Permite seleccionar unha feature de
			//calquera das capas que se amosan no mapa e non so de unha.

			this.map.removeControl(this.selectControl);
			
			//Capas visibles no mapa
			
			this.layers = [];
			
			for(l in this.map.layers){
				
				if(this.map.layers[l].CLASS_NAME == 'OpenLayers.Layer.Vector'){
					this.layers[this.layers.length] = this.map.layers[l];
				}
			}
			
			this.numLayers = this.layers.length;
			
			this.selectControl = new OpenLayers.Control.SelectFeature(this.layers,
					{scope:{"context":this,"map":this.map,"onPopupClose": this.onPopupClose} ,onSelect: this.onFeatureSelect, onUnselect: this.onFeatureUnselect});
			
			this.map.addControl(this.selectControl);
			this.selectControl.activate();
		},
		
		onFeatureSelect: function(feature) {

			//Evento que se lanza cada vez que se preme sobre unha feature.
			
			this.selectedFeature = feature;

			//Se prememos sobre un grupo onde existen mais de un elemento, amosarase unha lista cos elementos nese punto.
			
			if(this.selectedFeature.attributes.count > 1){
			
				var idElemento;
			    html = "<div class='titleBar'>Puntos de interese</div><div class='contentBar'>";
			    
			    for(f in feature.cluster){
			    	
			    	currentFeature = feature.cluster[f];
			    	var name = currentFeature.attributes.nome;
			    	
			    	idElemento = currentFeature.attributes.id;
			    	
			    	
			    	if(currentFeature.attributes.tipo == 'poboacion'){
			    		
			    		imaxe = currentFeature.attributes.tipo + currentFeature.attributes.subtipo+".png";
			    	}
			    	else{
			    		
			    		imaxe = currentFeature.attributes.tipo+".png";
			    	}
			    	
			    	html = html+"<div class='linea'><div class='izq'><b><a href='javascript:verElemento(\""+currentFeature.attributes.tipo+"\","+idElemento+");'>" + name +"</a></b><br /><i>" + currentFeature.attributes.tipo+"</i></div>"+
			        "<div class='der'><img src='./icons/"+imaxe+"'/></div><div class='clear'></div></div>";
			    }
	
			    html = html+"</div>";
			    
			    
			    if(this.map.size.w <= 300){
			    	
			    	ll = this.map.getLonLatFromPixel(new OpenLayers.Pixel(10,45));
			    }
			    else{
			    	
			    	ll = feature.geometry.getBounds().getCenterLonLat();
			    };
	
			    popup = new OpenLayers.Popup.Anchored("info", 
			                             ll,
			                             null, html,
			                             null, true, this.onPopupClose);
			    

			    popup.selectedFeature = this.selectedFeature;
			    popup.selectControl = this.context.selectControl;
	
			    feature.popup = popup;
			    this.map.addPopup(popup);
			    
			}
			else{
				
				//Se prememos sobre un so elemento abrirase unha ventana modal coa informacion do elemento empregando o
				//metodo 'verElemento' que se atopa en '/scripts/xeografiafacade/HTMLXeografiaFacade.js'
				
				this.context.selectedFeature = feature;
				
				if(this.selectedFeature.attributes.count){
					
					idElemento = this.selectedFeature.cluster[0].attributes.id;
					tipo = this.selectedFeature.cluster[0].attributes.tipo;
				}
				else{
					
					idElemento = this.selectedFeature.attributes.id;
					tipo = this.selectedFeature.attributes.tipo;
				}
					verElemento(tipo,idElemento);
			}
		},
		
		onFeatureUnselect: function(feature) {
			
			if(feature.popup != null){
				this.map.removePopup(feature.popup);
			}
		}
});