var karte;
var laySel = new Array();

function osmMap(formName)
{
  this.formName = formName;
  this.map;
  this.controls;
  this.tah;
  this.mapnik;
  this.vectors;
  this.gmap;
  this.kml;
  this.gpx;
  this.select;
  this.rssLayer;
  this.selcontrol;
//  this.selcontrol2;

  this.vector_marker = vector_marker;
  this.create_map = create_map;
  this.create_layers = create_layers;
  this.create_controls = create_controls;

  this.createPopup = createPopup;
  this.destroyPopup = destroyPopup;
  this.closePopup = closePopup
  this.set_map_values = set_map_values;
}

function create_map()
{
  this.map = new OpenLayers.Map(this.formName + '_osmMap', 
     { maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
       numZoomLevels: 19,
       maxResolution: 156543.0399,
       units: "m",
       projection: new OpenLayers.Projection("EPSG:900913"),
       displayProjection: new OpenLayers.Projection("EPSG:4326") 
     }
    );
}

function vector_marker(markerList, vectorLayer)
{
  for(var s =0; s < markerList.length; s++) {

    var markerData = markerList[s];
    var pos = new OpenLayers.LonLat( markerData['lon'],markerData['lat']).transform(new OpenLayers.Projection("EPSG:4326"), this.map.getProjectionObject());
    var iconName = markerPath + "/" + markerData['icon']

    var feature = new OpenLayers.Feature.Vector(
                  new OpenLayers.Geometry.Point(pos.lon,pos.lat),
                  {popupContent: markerData['popupContent']},
                  {externalGraphic: iconName, 
                  graphicHeight: markerData['iconHeight'], 
                  graphicWidth: markerData['iconWidth'], 
                  graphicXOffset: markerData['iconXOff'],
                  graphicYOffset:  markerData['iconYOff']                         
                  }
                );
    vectorLayer.addFeatures(feature);
  }
        
}


function create_layers()
{
  this.mapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
  this.tah =  new OpenLayers.Layer.OSM.Osmarender("Tiles@Home");
  this.map.addLayers([this.mapnik, this.tah]);
    
  if ( typeof osmLayer != "undefined") {
    var layerListe = osmLayer;

    for(var i =0; i < layerListe.length; i++) {
 	    var dd = layerListe[i];
	    var layer= eval('('+ dd +')');
      
      // Vector-Layers for Marker

    if(mapMarker != '1') {
      
      if(layer['layerDataType'] == 'vectorMarker') {
        var vectorLayer = new OpenLayers.Layer.Vector(layer['name'], {popupSize: new OpenLayers.Size(layer['popupWidth'],layer['popupHeight'])});
        this.vector_marker(layer['layerData'],vectorLayer);
        laySel.push(vectorLayer);
	      this.map.addLayer(vectorLayer);    
      }
    }  
      // GPX-Layers for waypoints and routes.
      if(layer['layerDataType'] == 'vectorGpx') {
        var gpxData = layer['layerData'];
        var gpxlayerURL = gpxFilePath + "/" + gpxData['gpxFile'];

		    var vectorLayer = new OpenLayers.Layer.Vector(layer['name'], {
          popupSize: new OpenLayers.Size(layer['popupWidth'],layer['popupHeight']),
		      protocol: new OpenLayers.Protocol.HTTP({
		        url: gpxlayerURL,
		        format: new OpenLayers.Format.GPX()
		      }),
          strategies: [new OpenLayers.Strategy.Fixed()],
		      style: {strokeColor: gpxData['gpxColor'], strokeWidth: gpxData['gpxWidth'], strokeOpacity: gpxData['gpxTransparency'], pointRadius: 5},  
	        projection: new OpenLayers.Projection("EPSG:4326")
		    });
        
        laySel.push(vectorLayer);
	      this.map.addLayer(vectorLayer);  
      }
      
      // Text-Layers for Marker
      if(layer['layerDataType'] == 'vectorTextMarker') {
        var markerData = layer['layerData'];
        var txtUrl = markerFilePath + "/" + markerData['textFile'];

         var vectorLayer = new OpenLayers.Layer.Vector(layer['name'],{
            popupSize: new OpenLayers.Size(layer['popupWidth'],layer['popupHeight']),
	          protocol: new OpenLayers.Protocol.HTTP({
                url: txtUrl,
                format: new OpenLayers.Format.Text()
            }),
	          strategies: [new OpenLayers.Strategy.Fixed()],
	          projection: new OpenLayers.Projection("EPSG:4326")
         });
        
        laySel.push(vectorLayer);
	      this.map.addLayer(vectorLayer);  
      }

      // GeoRSS-Layers for Marker.
      if(layer['layerDataType'] == 'vectorGeoRss') {
        var rssData = layer['layerData'];
        var pos1 = rssData['file'].lastIndexOf("/");
				var pos2 = rssData['file'].lastIndexOf("-");
        var name = rssData['file'].substring(0, pos2);
				var cacheName = rssData['file'].substring(pos1, 100);
        var rsslayerURL = installPath + "/local_rss.php?feed=" + cacheName + ".rss";;
				var iconName = markerPath + "/" + name + ".png"
				var icon= new OpenLayers.Icon(iconName, new OpenLayers.Size(rssData['graphicWidth'],rssData['graphicHeight']));
                                      
        var vectorLayer = new OpenLayers.Layer.Vector(layer['name'],{
          popupSize: new OpenLayers.Size(layer['popupWidth'],layer['popupHeight']),
	        protocol: new OpenLayers.Protocol.HTTP({
		        url: rsslayerURL,
		        format: new OpenLayers.Format.GeoRSS()
          }),
	        strategies: [new OpenLayers.Strategy.Fixed()],
	        projection: new OpenLayers.Projection("EPSG:4326"),
          styleMap: new OpenLayers.StyleMap({
                    "default": new OpenLayers.Style({
                               externalGraphic: iconName,
                               graphicHeight: rssData['graphicHeight'],
                               graphicWidth: rssData['graphicWidth'],
                               graphicXOffset: rssData['graphicXOffset'],
                               graphicYOffset: rssData['graphicYOffset']
                    }, OpenLayers.Feature.Vector.style["default"]),
                    "select": new OpenLayers.Style({
                        externalGraphic: iconName
                    })
          })
        });
        
        laySel.push(vectorLayer);
	      this.map.addLayer(vectorLayer);  
      }

            
    }
  }
  
  
 	// feature connects the click events
  this.selcontrol = new OpenLayers.Control.SelectFeature(laySel, {
	  onSelect: this.createPopup,
	  onUnselect: this.destroyPopup,
    toggle: false,
    hover:false,
  });
	   
	this.map.addControl(this.selcontrol);
  this.selcontrol.activate();				  
}


// popup window
function createPopup(feature) {
	this.selectedFeature = feature;
  if ( typeof feature.layer.options.popupSize	!= "undefined") {
    var csize = feature.layer.options.popupSize;
  }
  else {
    var csize = new OpenLayers.Size(230,180);
  }
    
  var out = '';
	var lonlat = feature.geometry.getBounds().getCenterLonLat().clone();
  lonlat.transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
  
  if ( typeof feature.attributes.name	!= "undefined") {
    out = '<div><h1>' + feature.attributes.name + '</h1><p>' + feature.attributes.desc + '</p></div>';
  }
   else	  if ( typeof feature.attributes.title	!= "undefined") {
    if ( typeof feature.attributes.link	!= "undefined") 
      out = '<div><h1><a target="_blank" href="'+feature.attributes.link+'" class="link">'+feature.attributes.title+'</a></h1><p>' + feature.attributes.description + '</p></div>';
    else
      out = '<div><h1>' + feature.attributes.title + '</h1><p>' + feature.attributes.description + '</p></div>';
  }
  else if ( typeof feature.attributes.desc	!= "undefined") {
    out = '<div><p>' + feature.attributes.desc + '</p></div>';
  }
   else	  if ( typeof feature.attributes.description	!= "undefined") {
    out = '<div><p>' + feature.attributes.description + '</p></div>';
  }
   else	  if ( typeof feature.attributes.popupContent	!= "undefined") {
    out = '<div><p>' + feature.attributes.popupContent + '</p></div>';
  }
  
    if ( out.length > 0) {
     
		feature.popup = new OpenLayers.Popup.AnchoredBubble("geo",
    		feature.geometry.getBounds().getCenterLonLat(),
		    csize,
				out,
				null,
				true,
				closePopup //global Function !!
		);

		this.map.addPopup(feature.popup);
  }
  else
  	karte.selcontrol.unselectAll()
}
 
// destroys the popup when feature unselected
function destroyPopup(feature) {
  feature.popup.destroy();
  feature.popup = null;
}
 
function create_controls()
{
    if(mapScale != '1')
      this.map.addControl(new OpenLayers.Control.Scale());
      
    if(mapScaleLine != '1')
      this.map.addControl(new OpenLayers.Control.ScaleLine());
      
    if(mapPanZoomBar != '1')
      this.map.addControl(new OpenLayers.Control.PanZoomBar());
      
    if(mapLayerSwitcher != '1')
      this.map.addControl(new OpenLayers.Control.LayerSwitcher());
 
    if(mapZoomWheel != '1') { 
      var controls = this.map.getControlsByClass('OpenLayers.Control.Navigation');
      for(var i = 0; i<controls.length; ++i){
        controls[i].disableZoomWheel();
      }
    }
    
    var controls = this.map.getControlsByClass('OpenLayers.Control.PanZoom');

    for(var i = 0; i<controls.length; ++i){
        controls[i].destroy();
    }

    if(mapMousePosition != '0')
      this.map.addControl(new OpenLayers.Control.MousePosition());

    if(mapPanZoom != '0') 
      this.map.addControl(new OpenLayers.Control.PanZoom());
    
}


function set_map_values() 
{
  if ( typeof minLon != "undefined") {
    this.map.zoomToExtent( new OpenLayers.Bounds(minLon,minLat,maxLon,maxLat). transform(
                    this.map.displayProjection,  
                    this.map.projection));   
  }else if ( typeof glbLon != "undefined") {
   var posCenter = new OpenLayers.LonLat(glbLon,glbLat).transform(new OpenLayers.Projection("EPSG:4326"), this.map.getProjectionObject());
   karte.map.setCenter(posCenter,glbZoom);
  }
  

}

function closePopup(evt) {
	karte.selcontrol.unselectAll()
}

function showMap(formName)
{
  karte = new osmMap(formName)
  karte.create_map();
  karte.create_layers();
  karte.create_controls();
  karte.set_map_values();
}


