var layerMarkers;
var map, layer, popup;
var markers, feature, marker;
var pos;
var manual=false;
var LayerRuta;
var txt_ruta;
var popup;
var feature;
function crear_icona(url)
{
	var size = new OpenLayers.Size(21,25);
	var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
	var icon = new OpenLayers.Icon(url,size,offset);
}
function init(lat,lon,zoom,id,concerts,nomdiv,default_map,parkings,ruta,truta) 
{
	txt_ruta=truta;
	if(id=="0")
	{
		var url="./generate_kml.php";
	}
	else
	{
		var url="./generate_kml.php?id="+id+"&l=1";
	}
	var url_parkings="./generate_kml_parkings.php?lat="+lat+"&lon="+lon;
	if ((nomdiv=="map")|(nomdiv=="mapcomplert"))
	{
		map = new OpenLayers.Map (nomdiv, {controls:[
		new OpenLayers.Control.Navigation(),
		new OpenLayers.Control.PanZoomBar(),
		new OpenLayers.Control.LayerSwitcher(),
		new OpenLayers.Control.Attribution()],
		maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
		maxResolution: 156543.0399,
		numZoomLevels: 19,
		units: 'm',} );
		pois = new OpenLayers.Layer.Vector(concerts, {
		projection: map.displayProjection,
		strategies: [new OpenLayers.Strategy.Fixed()],
		protocol: new OpenLayers.Protocol.HTTP({url: url,format: new OpenLayers.Format.KML({
		extractStyles: true,
		extractAttributes: true
		})})});
		parkings = new OpenLayers.Layer.Vector(parkings, {
		projection: map.displayProjection,
		strategies: [new OpenLayers.Strategy.Fixed()],
		protocol: new OpenLayers.Protocol.HTTP({url: url_parkings,format: new OpenLayers.Format.KML({
		extractStyles: true,
		extractAttributes: true
		})})});
		OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
		defaultHandlerOptions: {
			'single': true,
			'pixelTolerance': 0
			},
			initialize: function(options) {
				this.handlerOptions = OpenLayers.Util.extend(
				{}, this.defaultHandlerOptions);
				OpenLayers.Control.prototype.initialize.apply(this, arguments); 
				this.handler = new OpenLayers.Handler.Click(this, {'click': this.onClick,}, this.handlerOptions);
				},
					onClick: function(evt) {
					if(typeof(marker)!="undefined")
					{
						marker.destroy();
					}
					if(manual)
					{
						var l=map.getLonLatFromViewPortPx(evt.xy);
						l.transform(map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
						var point = map.getLonLatFromViewPortPx(evt.xy);
						var proj = new OpenLayers.Projection("EPSG:4326");
						var icon=crear_icona('../img/marker_red.png');
						
						marker=new OpenLayers.Marker(point,icon);
						var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
						layer_style.fillOpacity = 0.2;
						layer_style.graphicOpacity = 1;
						var style_blue = OpenLayers.Util.extend({}, layer_style);
						style_blue.strokeColor = "green";
						style_blue.fillColor = "green";
						style_blue.graphicName = "star";
						style_blue.pointRadius = 10;
						style_blue.strokeWidth = 3;
						style_blue.rotation = 45;
						style_blue.strokeLinecap = "butt";
						if(map.getNumLayers()>5)
						{
							map.removeLayer(LayerRuta);
						}
						r=new OpenLayers.Protocol.HTTP({
                    				url:"proxyyour.php?flat="+l.lat.toFixed(5)+"&flon="+l.lon.toFixed(5)+"&tlat="+lat.toFixed(5)+"&tlon="+lon.toFixed(5),
                    				format: new OpenLayers.Format.KML({
                        			extractStyles: false,
	                        		extractAttributes: false,
        	            			})});
						LayerRuta = new OpenLayers.Layer.Vector(ruta, {
                				projection: proj,
                				strategies: [new OpenLayers.Strategy.Fixed()],
                				protocol: r,
						style:style_blue});
						map.addLayer(LayerRuta);
						bounds = new OpenLayers.Bounds();
						bounds.extend(new OpenLayers.LonLat(l.lon,l.lat));
						bounds.extend(new OpenLayers.LonLat(lon,lat));
						map.panTo(bounds.getCenterLonLat().transform(new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject()));
	
						bounds2 = new OpenLayers.Bounds();
						bounds2.extend(new OpenLayers.LonLat(l.lon,l.lat).transform(new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject()));
						bounds2.extend(new OpenLayers.LonLat(lon,lat).transform(new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject()));
						map.zoomTo(map.getZoomForExtent(bounds2,true));
						manual=false;
					}
				}
		});
		select = new OpenLayers.Control.SelectFeature([pois,parkings]);
		pois.events.on({
		"featureselected": onFeatureSelect,
		"featureunselected": onFeatureUnselect
		});
		parkings.events.on({
		"featureselected": onFeatureSelect,
		"featureunselected": onFeatureUnselect
		});

		var click = new OpenLayers.Control.Click();
		map.addControl(click);
		click.activate();	

		map.addLayer(pois);
		map.addLayer(parkings);

		map.addControl(select);
		select.activate();
	}
	if(nomdiv=="map_small")
	{
		OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
		defaultHandlerOptions: 
		{
			'single': true,
			'pixelTolerance': 0
		},
		initialize: function(options) 
		{
			this.handlerOptions = OpenLayers.Util.extend(
			{}, this.defaultHandlerOptions);
			OpenLayers.Control.prototype.initialize.apply(this, arguments); 
			this.handler = new OpenLayers.Handler.Click(this, {'click': this.onClick,}, this.handlerOptions);
		},
		onClick: function(evt) 
		{
			if(typeof(marker)!="undefined")
			{
				marker.destroy();
			}
			var l=map.getLonLatFromViewPortPx(evt.xy);
			l.transform(map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
 			var point = map.getLonLatFromViewPortPx(evt.xy);
			var proj = new OpenLayers.Projection("EPSG:4326");
			var icon=crear_icona('../img/marker_red.png');
			marker=new OpenLayers.Marker(point,icon);	
 			layerMarkers.addMarker(marker);
			map.panTo(point);
			document.getElementsByName('lat')[0].value=l.lat;
			document.getElementsByName('lng')[0].value=l.lon;
		}
		});
		map = new OpenLayers.Map ('map_small', {
		maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
		maxResolution: 156543.0399,
		numZoomLevels: 19,
		units: 'm',} );

		map.addControl(new OpenLayers.Control.LayerSwitcher());
		layerMarkers = new OpenLayers.Layer.Markers( concerts );
            	map.addLayer(layerMarkers);
		
		var click = new OpenLayers.Control.Click();
		map.addControl(click);
		click.activate();	

	}
	var gmap = new OpenLayers.Layer.Google("Google", {sphericalMercator:true});
	layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik-OpenStreetMaps");
	if(default_map=="OSM")
	{
		map.addLayer(layerMapnik);
		map.addLayer(gmap);
	}
	else
	{
		map.addLayer(gmap);
		map.addLayer(layerMapnik);
	}
	var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
	map.setCenter (lonLat, zoom);	
}
function onPopupClose(evt) 
{
	select.unselectAll();
}
function onFeatureSelect(event) 
{
	feature = event.feature;
	var selectedFeature = feature;
	popup = new OpenLayers.Popup.FramedCloud("chicken", 
	feature.geometry.getBounds().getCenterLonLat(),
	new OpenLayers.Size(100,100),
	"<h2>"+feature.attributes.name + "</h2>" + feature.attributes.description,
	null, true, onPopupClose
	);
	feature.popup = popup;
	map.addPopup(popup);
}
function onFeatureUnselect(event) 
{
	feature = event.feature;
	if(feature.popup) {
		map.removePopup(feature.popup);
		alert(feature.popup);
		feature.popup.destroy();
		delete feature.popup;
	}
}
function addclose()
{
	setTimeout("map.popups[0].addCloseBox()",200);
	var evt;
	map.events.triggerEvent("mouseup",evt);
}
function mode_manual()
{
	if(typeof(m)!="undefined")
	{
		m.destroy();
	}
	manual=true;
}
function afegir_gpx()
{
	map.removePopup(popup);
 	feature.popup.destroy();
 	delete feature.popup;
	setTimeout("mode_manual();",500);
}