
/********************************************************************** 
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

(C) 2008 Harald Kirsch (pifpafpuf at gmx dot de)
************************************************************************/
function updateScale(evt) {

	var z = map.getZoom();
	switchPOILayer();

  var scale = this.getScale();
/*  if( scale > 1000000 )
		scale = (scale / 1000000).toFixed(1) + "M";
  else if( scale > 50000 )
		scale = (scale / 1000).toFixed(0) + "k";
	else 
*/		scale = scale.toFixed(0)
		
  var e = document.getElementById('currentscale');
  e.innerHTML = scale + "  z" +this.getZoom();
  updateLocation.call(this, evt);
  
  updateRouteList();
}


function setPermaLink( target, base, lonlat, zoom, limit )
{
   var obj = document.getElementById(target);
   //document.getElementById(target).href = href;

   if( zoom >= limit )
	{
		var href = base
		+ "?lon="+lonlat.lon.toFixed(4)
		+ "&lat="+lonlat.lat.toFixed(4)
		+ "&zoom="+zoom;

		if( currentLang && (currentLang == 'en' || currentLang == 'it' ))
		{
			href = href + "&lang=" + currentLang;
		}
		obj.target="editor";
	}
	else
	{
		var href = "javascript: alert('Diese Funktion ist erst ab Zoomlevel " + limit + " verfügbar.' );";
		obj.target="_self";
	}
	
	obj.href = href;
}

function updateLocation(evt) {
  var lonlat = p2p(p900913, p4326, this.getCenter());
  var zoom = this.getZoom();
	
  //document.getElementById('permalink.topo').href = href;
  //location.url = href;
  setPermaLink( 'permalink.topo', "http://www.wanderreitkarte.de/index.php", lonlat, zoom, 4 );

  setPermaLink( 'permalink.editor', "http://www.wanderreitkarte.de/edit/edit.php", lonlat, zoom, 14 );

  setPermaLink( 'permalink.potlatch', "http://www.openstreetmap.org/edit", lonlat, zoom, 13 );
  setPermaLink( 'permalink.mapnik', "http://www.openstreetmap.org/", lonlat, zoom, 4 );
}

 

// main initialization

   //Eingrenzung auf Gegend
    var leftBottom = new OpenLayers.LonLat(-9.8,35.2) 
    .transform(
      new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
      new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
    )
    var rightTop = new OpenLayers.LonLat(23,58.1) 
    .transform(
      new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
      new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
    )
    var extent = new OpenLayers.Bounds(leftBottom.lon, leftBottom.lat, rightTop.lon, rightTop.lat);

var options = {
  projection : "EPSG:900913",
	numZoomLevels: 19,

  controls: [      new OpenLayers.Control.KeyboardDefaults(),  // keyboard must be first
			new OpenLayers.Control.MouseDefaults(),
//	     new OpenLayers.Control.LayerSwitcher(),
	     new OpenLayers.Control.PanZoomBar(),

      new OpenLayers.Control.ScaleLine({geodesic: true})
	     ]
};

var map = new OpenLayers.Map('map', options);
    map.restrictedExtent = extent;

            var base = new OpenLayers.Layer.Topo('base', [
				'http://base.wanderreitkarte.de/base/${z}/${x}/${y}.png',
				'http://base2.wanderreitkarte.de/base/${z}/${x}/${y}.png'],
				{isBaseLayer:true});
			map.addLayer(base);
			
            var hills = new OpenLayers.Layer.Contour("shade", [
				"http://wanderreitkarte.de/hills/${z}/${x}/${y}.png",
				'http://www.wanderreitkarte.de/hills/${z}/${x}/${y}.png'],
			{minZoomLevel: 9, maxZoomLevel: 19 , isBaseLayer:false });
            map.addLayer(hills); 
			
            var trails = new OpenLayers.Layer.Topo('topo', [
				'http://topo.wanderreitkarte.de/topo/${z}/${x}/${y}.png',
				'http://topo2.wanderreitkarte.de/topo/${z}/${x}/${y}.png'], 
				{isBaseLayer:false});
			map.addLayer(trails);

            var pois = new OpenLayers.Layer.Vector("POIs", {
                    strategies: [new OpenLayers.Strategy.BBOX({resFactor: 1.1})],
                    //protocol: new OpenLayers.Protocol.HTTP({
                    protocol: new POIRequestProtocol({
                        url: "http://www.wanderreitkarte.de/php/pois.php",
                        format: new OpenLayers.Format.Text()
                    })
                });
			map.addLayer(pois);

                // Interaction; not needed for initial display.
				overCallback = { over: featureOver, out: hideTooltip };
                selectControl = new OpenLayers.Control.SelectFeature(pois, { callbacks: overCallback });

                map.addControl(selectControl);
                selectControl.activate();
				
                pois.events.on({
                    'featureselected': onFeatureSelect,
                    'featureunselected': onFeatureUnselect
                });

// have to figure out how this can be done automatically
Proj4js.defs["EPSG:54004"] = 
"+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs ";
Proj4js.defs["EPSG:54004"] = "+proj=merc +lat_ts=0 +lon_0=0 +k=1.000000 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m  no_defs"
Proj4js.defs["EPSG:900913"] = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs";

p54004 = new Proj4js.Proj("EPSG:54004");
p4326 = new Proj4js.Proj("EPSG:4326");
p900913 = new Proj4js.Proj("EPSG:900913");

/*
function sizeMap(deltaPx) { 
  var e = document.getElementById('map');
  var h = e.style.height;
  if( h=='' ) h = window.getComputedStyle(e, null).height;
  var height = parseInt(h)+deltaPx;
  if( height<100 ) return;
  e.style.height = ""+ height + 'px';
  map.updateSize();
};
*/
/**
 * convert from one projection to other. 
 * @param Proj4js.Proj pFrom input projection
 * @param Proj4js.Proj pTo output projection
 * @param OpenLayers.LonLat lonlat value to convert
 */
function p2p(pFrom, pTo, lonlat) {
  var xy = {x: lonlat.lon, y:lonlat.lat};
  xy = Proj4js.transform(pFrom, pTo, xy);
  return new OpenLayers.LonLat(xy.x, xy.y);  
};

function mapFullsize() {
  var maph = window.innerHeight;
  document.getElementById("map").style.height = maph+"px";
  map.updateSize();
}

// parse URL parameters for lat, lon and zoom
/*var floatreString = "([-]?[0-9]+([.][0-9]+)?)($|&)";
var paramDef = {
  lat : [new RegExp("[?&]lat="+floatreString), null],
  lon : [new RegExp("[?&]lon="+floatreString),  null],
  zoom : [new RegExp("[?&]zoom=([0-9]|1[0-9])($|&)"), null],
  //maph : [new RegExp("[?&]maph=([0-9][0-9][0-9][0-9]?)($|&)"), null],
  //layer : [new RegExp("[?&]layer=([A-Za-z]+)($|&)"), "Mapnik"],
  urlLang : [new RegExp("[?&]lang=(en|it)($|&)"), null]
};
var params = {};
for(key in paramDef) {
  var m = location.search.match(paramDef[key][0]);
  eval("var "+key+" = (m==null) ? paramDef[key][1] : m[1]");
 };
*/

// initialize the map coordinates, zoom, size and layer from the URL
// parameters or from defaults. For the coordinates we remember
// whether we used the default. If yes, a track just loaded is allowed
// to override the settings to zoom to its extend.
if( lat && lon ) {
  lonlatIsDefault = false;
  var lonlat = new OpenLayers.LonLat(lon, lat);
} else {
  lonlatIsDefault = true;
  var lonlat = new OpenLayers.LonLat(11.75,49);
}
lonlat = p2p(p4326, p900913, lonlat);

if( zoom ) {
  zoomIsDefault = false;
} else {
  zoomIsDefault = true;
  zoom = 5;
}

/*
if( maph ) {
  document.getElementById('map').style.height = ""+maph+"px";
  map.updateSize();
} else {
  mapFullsize();
}
*/
  mapFullsize();
//var l = map.getLayersByName("Reitkarte");
//if( l && l.length>0 ) map.setBaseLayer(l[0]);

map.events.register("zoomend", map, updateScale);
map.events.register("moveend", map, updateLocation);

// called at the end of the generated tail of index.html, just before
// the track points are created.
function initMapCoords(lonlat, zoom, map) {
  map.setCenter(lonlat, zoom, false, false);
  //updateScale.apply(map, null);
  d = document.getElementById('mapWrapper');
  d.style.width=window.innerWidth-250;

}

// TODO: Arrrgh, need to call map-center anyway so that GpxTrack, when
// initialized, can immediately register the popup with the map. Need
// to change this to lazy popup-initialization, but since Javascript
// does not have private members and compilation, this can become
// tedious.
//map.setCenter(lonlat, zoom, false, false);


