Proj4js.defs["EPSG:31467"] = "+proj=tmerc +lat_0=0 +lon_0=9 +k=1 +x_0=3500000 +y_0=0 +ellps=bessel +datum=potsdam +units=m +no_defs";

//projection: new OpenLayers.Projection("EPSG:900913"),,900913

// JavaScript Document

//<script type="text/javascript" src="http://www.openlayers.org/api/OpenLayers.js">
//<script type="text/javascript" src="http://proj4js.org/lib/proj4js-compressed.js"></script>
        
   //Version 4.5.0 25-Jan-2012 Systematic Finance plc - www.system.co.uk or www.financial-models.com
   //Uses API to find and centre placenames on a BKG and other maps
   //All mapping subject to end user licence agreements - not to be used for commercial purposes
   //See http://topo.fabrik.de for the Wanderkarte and Relief
   // Multitouch from https://github.com/andyet/OpenLayers-Multitouch

// Variables for markers
		myMap = null;
		var taille;
		var decalage;
		var icone;
		var position;
		var cmarqueur;
		var marqueur ;
		var gpsmarqueur;
		var pos;
		var coucheMarqueurs;
		
		var ClickControl;
		var OpenLayers;
		
		var t=0;
        gpsLat = 0;
	    gpsLng = 0;
	    galt = 0;
	    gspeed = 0;
	    ghead= 0;
	    gtime = 0;
	    gsat = 0;
		gpsposition = "Current GPS Position: n/a";
		var trackingon = 0;
		
		var mapselection;
		var mapname = "TGF";
		var bl;
		var zoomlevel =14;
		
		var cumalt=0;
        var alt = 0;
        var lastalt = 0;
		var wikiMarker=new Array(20); 
		var mapdisplay=2;
		var initialloadbkg=1;
		var initialloadtopo=1;
		var timeoutput ="Time Zone: No time data available";
		var geooutput = "Geocoding Address: n/a";
		
		lat = 0; 
	    long = 0;
		lat1 = 0;
	    long1 = 0;
		
		var weather;
		
		var clicklat;
        var clicklon;
		
		var emailalert = "off";
	   var clickstatus = "n/a";
	   var msg1 = "n/a";
	   var galt = "n/a";
	   var gspeed = "n/a";
	   var ghead = "n/a";
	   var gtime = "n/a";
	   var gsat = "n/a";
	   var pos = "n/a";
	   var cmclickpermalink;
	   var cmcentrepermalink;
	   var smclickpermalink;
	   var smcentrepermalink;
	   var clickposition1;
	   
	   var LatDegrees;
	   var LatMinutes;
	   var LatDecMinutes;
	   
	   var LonDegrees;
	   var LonMinutes;
	   var LonDecMinutes;
	   
	    var plat = 0;
		var plon = 0;
		var palt = 0;
		var paccuracy = 0;
		var paltaccuracy = 0;
		var pheading = 0;
		var pspeed = 0;
		var timeValue;
		var place = "London";
	   
Map.addBaseLayers = function () {
	
	  mapselection = document.getElementById('mapselection').value;
      mapname = mapselection;
	  //alert("Initial Name1: " + mapname + " : Selection: " + mapselection + "Map display: " + mapdisplay);
	  
	//alert("Initial Import1: " + lat + " : " + long);
   //(1) Try Permalink Import
	if (lat  + long == 0 )
	{
	try{
		locate1 = window.location;
		document.getElementById('window').innerHTML= locate1;
		text1 = document.getElementById('window').innerHTML;
	
		function delineatelat(str)
		{
		theleft = str.indexOf("lat=") + 4;
		theright = str.lastIndexOf("lon=");
		return(str.substring(theleft, theright));
		}
		
		function delineatelng(str)
		{
		point1 = str.indexOf("lon=")+4;
		point2 = str.lastIndexOf("layers=");
		return(str.substring(point1,point2));
		}
		
		if (text1 !="http://www.sysmaps.co.uk/sysmaps_bkg.html")
		{
		lat = delineatelat(text1);
	    long = delineatelng(text1);
		long1 = long;   
		lat1 = lat;
		}
		
		}
		  catch(err){
			}	
	 }
	//alert("Permalink Import2: " + lat + " : " + long);
   
    //(2) Try SysMaps Import
   if (lat  + long ==0 || lat == "htt")
	{
	  try{
		locate1 = window.location;
		document.getElementById('window').innerHTML= locate1;
		text1 = document.getElementById('window').innerHTML;
	
		function delineate(str)
		{
		theleft = str.indexOf("!") + 1;
		theright = str.lastIndexOf("~");
		return(str.substring(theleft, theright));
		}
		
		function delineate2(str)
		{
		point = str.lastIndexOf("~");
		return(str.substring(point+1,str.length));
		}
		
		if (text1 !="http://www.sysmaps.co.uk/sysmaps_bkg.html")
		{
		lat = delineate(text1);
	    long = delineate2(text1);
		long1 = long;   
		lat1 = lat;
		}
		
		}
		  catch(err){
			}
	}
	//alert("SysMaps Import3: " + lat + " : " + long);
	
	//Default positions in Augsburg
	if (lat==undefined)
	{
	//These are default positions near Versailles
		lat = 48.374;  //Jesuitengasse
	    long = 10.8953;
	    //lat1 = 48.3645;  // Hbf Augsburg
	    //long1 = 10.8848;
		lat1 = 48.3693;  // Rathaus Augsburg
	    long1 = 10.895867;
	}
	
	if (lat==0)
	{
		lat = 48.374;  //Jesuitengasse
	    long = 10.8953;
	    //lat1 = 48.3645;  // Hbf Augsburg
	    //long1 = 10.8848;
		lat1 = 48.3693;  // Rathaus Augsburg
	    long1 = 10.8967;
	}
	
	//Set default click marker position
	ptlat=lat;
	ptlon = long;
	gpsLng = long; //London
	gpsLat = lat;
	gpsLng2 = long;
	gpsLat2 = lat;
	clicklon = long;
	clicklat = lat;
	//alert(lat + " : " + long + " : " + lat1 + " : " + long1);
	
	/**
     * Method: stopObservingElement
     * Given the id of an element to stop observing, cycle through the
     *   element's cached observers, calling stopObserving on each one,
     *   skipping those entries which can no longer be removed.
     *
     * parameters:
     * elementParam - {DOMElement || String}
     */
    OpenLayers.Event.stopObservingElement= function(elementParam) {
        var element = OpenLayers.Util.getElement(elementParam);
        if (element) {
            var cacheID = element._eventCacheID;

            if (cacheID) {
                this._removeElementObservers(OpenLayers.Event.observers[cacheID]);
            }
        }
    };
	  
	  //Override selection if TGF selected
	  if(mapname!="TGF")
	  {
	  mapdisplay=1; 
	  }
	  else
	  {
	  mapdisplay=2; 
	  }	  
		  
	  //alert("Initial Name2: " + mapname + " : Selection: " + mapselection + "Map display: " + mapdisplay);

if (mapdisplay==1)
{
	this.map.displayProjection = this.wgs84;
	displayProj = this.map.displayProjection;
	this.map.projection = "EPSG:31467";
	 this.map.maxExtent = new OpenLayers.Bounds(3278000, 5229000, 3950000, 6130200);
	//this.map.projection = new OpenLayers.Projection("EPSG:900913");
	this.map.scales = [1500000,750000,500000,300000,200000,100000,50000,25000,15000,10000];
    this.map.units = 'm';
	
	this.map.numZoomLevels= 10;
	this.defaultZoom = 6;
	
	//this.map.baseLayer.projection=new OpenLayers.Projection("EPSG:31467");
    //this.map.projection = new OpenLayers.Projection("EPSG:900913");
   
  
	//this.map.maxExtent =  new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34);
   // this.map.maxResolution = 156543.0399;
	
	this.mapTypes = ['DTK1000','DTK1000','DTK1000','DTK500-V','DTK500-V','DTK200-V','DTK200-V','dlm_50','dlm_50','dlm_50'];
    this.map.resolutions = [900,450,225,120,50,25,10,4.5,3,2,1,0.5];
   
	//Remove marker if possible
			 try{
		       r = this.map.removeLayer(coucheMarqueurs);
		     	}
		      catch(err){
		   	  }	
   
   mapselection = document.getElementById('mapselection').value;
   //alert(mapselection);
   mapname = mapselection;
   //alert("Initial Name: " + mapname + " : Selection: " + mapselection);
  
 if (mapname=="dlm_50")
		{
		     //mapname = 'dlm_50';	
			 this.server = {
			 bkg: "http://gdz1.leipzig.ifag.de:80/servlet/com.esri.wms.Esrimap?servicename=dtk200_500_1000_a10_gk3_wms",
			  dlm: "http://www.gis5.nrw.de/cgi-bin/dlm_50?"
				};
			 this.attribution = {
			bkg: 'Topo maps &copy; <a href="http://www.bkg.bund.de/EN/">BKG</a>',
			dlm: 'Topo maps: Digitales Landschaftsmodell from <a href="http://www.gis3.nrw.de/DienstelisteInternet/">NRW geoserver</a>'
			 };
		}
		
	 else if (mapname=="TGF")
		{
		
		}	
		
		
	else if (mapname=="TK50")
		{
		 //mapname = 'TK50';
			   this.server = {
			 bkg: "http://gdz1.leipzig.ifag.de:80/servlet/com.esri.wms.Esrimap?servicename=dtk200_500_1000_a10_gk3_wms",
			 dlm: "http://www.geodaten.bayern.de/ogc/getogc.cgi/TK50?"
			   };
			 this.attribution = {
				bkg: 'Topo maps &copy; <a href="http://www.bkg.bund.de/EN/">BKG</a>',
				dlm: 'Topographische Karten from <a href="http://www.geodaten.bayern.de/">Bayern geoserver</a>'
				 };   
         }
		 
	else if (mapname=="DOP")
		{
		  //mapname = 'DOP'; 
			  this.server = {
			 bkg: "http://gdz1.leipzig.ifag.de:80/servlet/com.esri.wms.Esrimap?servicename=dtk200_500_1000_a10_gk3_wms",
			 dlm: "http://www.geodaten.bayern.de/ogc/getogc.cgi/DOP?"
			  };
			 this.attribution = {
				bkg: 'Topo maps &copy; <a href="http://www.bkg.bund.de/EN/">BKG</a>',
				dlm: 'Luftbilder from <a href="http://www.geodaten.bayern.de/">Bayern geoserver</a>'
				 };    
		}
		
		else if (mapname=="DTK25Vf")
		{
		 //mapname = 'TK25';
			   this.server = {
			 bkg: "http://gdz1.leipzig.ifag.de:80/servlet/com.esri.wms.Esrimap?servicename=dtk200_500_1000_a10_gk3_wms",
			 dlm: "http://www.gaia-mv.de/dienste/DTK25Vf?"
			   };
			 this.attribution = {
				bkg: 'Topo maps &copy; <a href="http://www.bkg.bund.de/EN/">BKG</a>',
				dlm: 'Topographische Karten from <a href="www.gaia-mv.de/">Mecklenburg-Vorpommern geoserver</a>'
				 };   
         }	 
		 
		 else if (mapname=="DNM25")
		{
		 //mapname = 'TK25';
			   this.server = {
			 bkg: "http://gdz1.leipzig.ifag.de:80/servlet/com.esri.wms.Esrimap?servicename=dtk200_500_1000_a10_gk3_wms",
			 dlm: "http://geoservice.geobasis-bb.de/ows/dnm25.php?"
			   };
			 this.attribution = {
				bkg: 'Topo maps &copy; <a href="http://www.bkg.bund.de/EN/">BKG</a>',
				dlm: 'Topographische Karten from <a href="http://gdi.berlin-brandenburg.de/">Brandenburg geoserver</a>'
				 };   
         }	 
		
		else
		{
		 alert("No map selected!");
		}

   //alert("Name after IF statement: " + mapname + " : Selection: " + mapselection);
  
  this.mapTypes = ['DTK1000','DTK1000','DTK1000','DTK500-V','DTK500-V','DTK200-V','DTK200-V',mapname,mapname,mapname];
   
  if (initialloadbkg==1)
  {
  
  this.map.addLayer(new OpenLayers.Layer.WMS( "BKG_Maps",
        this.server.bkg,
        {layers: 'DTK200-V'},
        { buffer: 0, attribution: this.attribution.bkg }
     ));
  
   //create a vector layer for drawing
	    var  vector = new OpenLayers.Layer.Vector("Lines_&_Polygons");
		this.map.addLayer(vector);
   
initialloadbkg=2;
   }
    //this.defaultLonglat = new OpenLayers.LonLat(13.4, 52.516); // Berlin

}
else
{
				this.map.displayProjection = this.wgs84;
	            displayProj = this.map.displayProjection;
	            this.map.projection = "EPSG:31467";
				//this.map.fractionalZoom = true;
				//this.map.projection = new OpenLayers.Projection("EPSG:900913");
	            //this.map.scales = [3000000,2500000,2250000,2000000,1750000,1500000,750000,500000,300000,200000,100000,50000,25000,15000,12500,10000,8000,6000,5000,4000,3000];
				
				if (mapdisplay==2)
					{
					var osmar = new OpenLayers.Layer.OSM.Osmarender("Osmarender");
					var options = {layers: [osmar]};
					this.map.addControl(new OpenLayers.Control.OverviewMap(options));
					}
				
				//this.map.scales="";
                this.map.units = 'm';
	
	            this.map.numZoomLevels= 20;
	            this.defaultZoom = 14;
				this.map.maxExtent =  new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34);
				//this.map.maxResolution = 156543.0399;
				//this.map.fractionalZoom = true;
				
		//Remove marker if possible
			 try{
		       r = this.map.removeLayer(coucheMarqueurs);
		    	}
		      catch(err){
		   	  }	
   
              mapselection = document.getElementById('mapselection').value;
             //alert(mapselection);
              mapname = mapselection;
			  
		  if (initialloadtopo==1)
		  {
			  
			var	layerCycleMap = new OpenLayers.Layer.OSM.CycleMap("CycleMap",{numZoomLevels: 20});
			var layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik",{numZoomLevels: 20});
			var layerTilesAtHome = new OpenLayers.Layer.OSM.Osmarender("Osmarender",{numZoomLevels: 20});
			
			
			  var openpiste = new OpenLayers.Layer.OSM("OpenPisteMap", "http://tiles.openpistemap.org/contours/${z}/${x}/${y}.png",{minZoomLevel: 3, maxZoomLevel: 18, numZoomLevels: 18, isBaseLayer:true, transitionEffect:null, attribution: "Map data licensed <a href=http://creativecommons.org/licenses/by-sa/2.0/>CC-BY-SA</a> <a href=http://www.openstreetmap.org>OpenStreetMap</a> (OpenStreetMap Foundation and contributors) <a href=http://www.openpistemap.org>OpenPisteMap</a>" });
			    
			     //var opm = new OpenLayers.Layer.OSM("OPM (No Contours)", "http://tiles.openpistemap.org/nocontours/${z}/${x}/${y}.png", {minZoomLevel: 3, maxZoomLevel: 18, numZoomLevels: 18, isBaseLayer:true, transitionEffect:null, attribution: "Map data licensed <a href=http://creativecommons.org/licenses/by-sa/2.0/>CC-BY-SA</a> <a href=http://www.openstreetmap.org>OpenStreetMap</a> (OpenStreetMap Foundation and contributors) <a href=http://www.openpistemap.org>OpenPisteMap</a>" });
				 
			//var osmb = new OpenLayers.Layer.OSM("OpenStreetBrowser", "http://www.openstreetbrowser.org/tiles/base/${z}/${x}/${y}.png", {minZoomLevel: 3, maxZoomLevel: 18, numZoomLevels: 18, isBaseLayer:true, transitionEffect:null, attribution: "Map data licensed <a href=http://creativecommons.org/licenses/by-sa/2.0/>CC-BY-SA</a> <a href=http://www.openstreetmap.org>OpenStreetMap</a> (OpenStreetMap Foundation and contributors) <a href=http://www.openstreetbrowser.org>OpenStreetBrowser</a>" });
				 
			var osmb = new OpenLayers.Layer.OSM("OpenStreetBrowser", "http://tiles-base.openstreetbrowser.org/tiles/basemap_base/${z}/${x}/${y}.png", {minZoomLevel: 3, maxZoomLevel: 18, numZoomLevels: 18, isBaseLayer:true, transitionEffect:null, attribution: "Map data licensed <a href=http://creativecommons.org/licenses/by-sa/2.0/>CC-BY-SA</a> <a href=http://www.openstreetmap.org>OpenStreetMap</a> (OpenStreetMap Foundation and contributors) <a href=http://www.openstreetbrowser.org>OpenStreetBrowser</a>" });
			//var osmb = new OpenLayers.Layer.OSM("OpenStreetBrowser", "http://www.openstreetbrowser.org/skunk/tiles/base/", {numZoomLevels: 19});
						
			var hikebike = new OpenLayers.Layer.OSM("Hike &amp; Bike", "http://toolserver.org/tiles/hikebike/${z}/${x}/${y}.png", {minZoomLevel: 3, maxZoomLevel: 18, numZoomLevels: 18, isBaseLayer:true, transitionEffect:null, attribution: "Map data licensed <a href=http://creativecommons.org/licenses/by-sa/2.0/>CC-BY-SA</a> <a href=http://www.openstreetmap.org>OpenStreetMap</a> (OpenStreetMap Foundation and contributors) <a href=http://hikebikemap.de>Hike &amp; Bike Map</a>" });
			
			var gphy = new OpenLayers.Layer.Google("Google Physical", {"sphericalMercator": true,type: G_PHYSICAL_MAP, numZoomLevels: 20});
            var gmap = new OpenLayers.Layer.Google("Google Streets", {"sphericalMercator": true,numZoomLevels: 20});
            var ghyb = new OpenLayers.Layer.Google("Google Hybrid", {"sphericalMercator": true,type: G_HYBRID_MAP, numZoomLevels: 20});
            var gsat = new OpenLayers.Layer.Google("Google Satellite", {"sphericalMercator": true,type: G_SATELLITE_MAP, numZoomLevels: 20});
			
			var bing = new OpenLayers.Layer.VirtualEarth("VE Road",{type: VEMapStyle.Road,"sphericalMercator": true,numZoomLevels: 20});
			var shaded = new OpenLayers.Layer.VirtualEarth("VE Shaded",{type: VEMapStyle.Shaded,"sphericalMercator": true,numZoomLevels: 20});
            var hybrid = new OpenLayers.Layer.VirtualEarth("VE Hybrid",{type: VEMapStyle.Hybrid,"sphericalMercator": true,numZoomLevels: 20});
            var aerial = new OpenLayers.Layer.VirtualEarth("VE Aerial",{type: VEMapStyle.Aerial,"sphericalMercator": true,numZoomLevels: 20});
			
			var apiKey = "AnYmTj-T1MQ78h7W0aI5xoHTJsH0qsQmxd_a6HygDkR3TgbcULmVxq9Qelx9_n5U";
			var bingroad = new OpenLayers.Layer.Bing({name: "Bing Road",key: apiKey,type: "Road"});
            var binghybrid = new OpenLayers.Layer.Bing({name: "Bing Hybrid", key: apiKey, type: "AerialWithLabels"});
            var bingaerial = new OpenLayers.Layer.Bing({name: "Bing Aerial",key: apiKey,type: "Aerial"});
			//var birdseye = new OpenLayers.Layer.VirtualEarth("VE Bird's Eye",{type: VEMapStyle.BirdseyeHybrid,"sphericalMercator": true,numZoomLevels: 20});
			
			//Removed 5-nov-2011 as I cannot get it to work
			//options.maxExtent = new OpenLayers.Bounds(0, 0, 800000, 1300000);
           // if (options.type === undefined){
           //options.type = "png";
           // }
		   //var oslayer = new OpenLayers.Layer.UKOrdnanceSurvey(name, options);
			
			var mm_map = new OpenLayers.Layer.MultiMap("Multimap Roads",{'sphericalMercator': true});
			
			//var meta_wms = new OpenLayers.Layer.WMS( "Metacarta","http://labs.metacarta.com/wms/vmap0",{"sphericalMercator": true,layers: 'basic'});
            //layer1 = new OpenLayers.Layer.WMS( "Blue Marble","http://labs.metacarta.com/wms-c/Basic.py?", {'sphericalMercator': true,layers: 'satellite' } );
	       
			try{
		       var yahoo = new OpenLayers.Layer.Yahoo("Yahoo",{'type': YAHOO_MAP_REG, numZoomLevels: 17, "sphericalMercator": true});
		    	}
		      catch(err){
		   	  }	
			
			//var yahoosat = new OpenLayers.Layer.Yahoo("Yahoo Satellite",{'type': YAHOO_MAP_SAT, numZoomLevels: 17, "sphericalMercator": true,isBaseLayer:true, transitionEffect:null,});
 	        //var yahoohyb = new OpenLayers.Layer.Yahoo("Yahoo Hybrid",{'type': YAHOO_MAP_HYB, numZoomLevels: 17, "sphericalMercator": true, isBaseLayer:true, transitionEffect:null,});
			
			//var mapsurferroad = new OpenLayers.Layer.cdauth.OSM.MapSurfer.Road(OpenLayers.i18n("MapSurfer Road"),{"sphericalMercator": true});
			//var mapsurferroad = new FacilMap.Layer.OSM.MapSurfer.Road("MapSurfer Road");
			//var mapsurfertopo = new OpenLayers.Layer.cdauth.OSM.MapSurfer.Topographic(OpenLayers.i18n("MapSurfer Topographic"),{"sphericalMercator": true});
			//var mapsurfertopo = new FacilMap.Layer.OSM.MapSurfer.Topographic("MapSurfer Topographic");
			
    		 //var hills = new OpenLayers.Layer.OSM("Relief/Contours", "http://topo.gvf.ve.it/cont/${z}/${x}/${y}.png",                 {minZoomLevel: 3, maxZoomLevel: 15, numZoomLevels: 20, isBaseLayer:true, transitionEffect:null, attribution: "DEM by <a href='http://srtm.csi.cgiar.org'>CIAT</a>" });
			 
			 var hills = new OpenLayers.Layer.OSM("Relief/Contours", "http://wanderreitkarte.de/hills/${z}/${x}/${y}.png",
                {minZoomLevel: 3, maxZoomLevel: 15, numZoomLevels: 20, isBaseLayer:false, opacity: 0.4,transitionEffect:null, attribution: "DEM by <a href='http://srtm.csi.cgiar.org'>CIAT</a>" });
				hills.setVisibility(false);
						
						pubtrans=new OpenLayers.Layer.XYZ("Public Transport (EU only)","http://tile.xn--pnvkarte-m4a.de/tilegen/${z}/${x}/${y}.png",{minZoomLevel: 1, maxZoomLevel: 19 ,"sphericalMercator": true,numZoomLevels: 20, isBaseLayer:true, transitionEffect:null, attribution: "Map by <a href='http://www.xn--pnvkarte-m4a.de/'>ÖPNV</a>"});  //Amended as below 21-Aug-2010
						 var usrelief = new OpenLayers.Layer.OSM("US Topo Relief", "http://tile.stamen.com/terrain-background/${z}/${x}/${y}.jpg",
                {minZoomLevel: 1, maxZoomLevel: 19, numZoomLevels: 20, isBaseLayer:true,transitionEffect:null, attribution: "Map data licensed <a href=http://creativecommons.org/licenses/by-sa/2.0/>CC-BY-SA</a> <a href=http://openstreetmap.org/>OpenStreetMap</a> (OpenStreetMap Foundation and contributors) <a href=http://mike.teczno.com>Michal Migurski OpenStreetMap maps</a>" });
				usrelief.setVisibility(false);
				
	  //These layers need ooc.js - added 6-Nov-2011
	  var npe = new OpenLayers.Layer.NPE("OS NPE (Eng/Wales) 1945", {isBaseLayer:true, transitionEffect:null, attribution: "Note - some UK data incomplete: map data licensed <a href=http://creativecommons.org/licenses/by-sa/2.0/>CC-BY-SA</a> <a href=http://ooc.openstreetmap.org/>OpenStreetMap</a> (OpenStreetMap Foundation and contributors) <a href=http://ooc.openstreetmap.org>OpenStreetMap Out-of-copyright maps</a>" });
      var os7 = new OpenLayers.Layer.OS7("OS 7th Series 1947", {isBaseLayer:true, transitionEffect:null, attribution: "Note - some UK data incomplete: map data licensed <a href=http://creativecommons.org/licenses/by-sa/2.0/>CC-BY-SA</a> <a href=http://ooc.openstreetmap.org/>OpenStreetMap</a> (OpenStreetMap Foundation and contributors) <a href=http://ooc.openstreetmap.org>OpenStreetMap Out-of-copyright maps</a>" });
      var os1 = new OpenLayers.Layer.OS1("OS 1st Ed. 1946 (1:25k)", {isBaseLayer:true, transitionEffect:null, attribution: "Note - some UK data incomplete: map data licensed <a href=http://creativecommons.org/licenses/by-sa/2.0/>CC-BY-SA</a> <a href=http://ooc.openstreetmap.org/>OpenStreetMap</a> (OpenStreetMap Foundation and contributors) <a href=http://ooc.openstreetmap.org>OpenStreetMap Out-of-copyright maps</a>" });
	  
	  // Define the XYZ-based layer for NLS Map
		OpenLayers.Layer.NLS = OpenLayers.Class(OpenLayers.Layer.XYZ, {
		name: "NLS Maps API",
		attribution: 'Historical maps from <a href="http://geo.nls.uk/maps/api/" target="_blank">NLS Maps API<\/a>',
		getURL: NLSTileUrlOS,
		sphericalMercator: true,
		transitionEffect: 'resize',
		CLASS_NAME: "OpenLayers.Layer.NLS"
		});
		nlslayer = new OpenLayers.Layer.NLS( "Historic UK OS");
		
		streetview = new OpenLayers.Layer.StreetView("OS StreetView (1:10000)",{isBaseLayer: true,transparent: true, "visibility": false});
		
				//pubtrans=new OpenLayers.Layer.XYZ("Public Transport (EU only)","http://88.198.69.143/tilegen/${z}/${x}/${y}.png",{minZoomLevel: 1, maxZoomLevel: 19 ,"sphericalMercator": true,numZoomLevels: 20, isBaseLayer:true, transitionEffect:null, attribution: "Map by <a href='http://www.xn--pnvkarte-m4a.de/'>ÖPNV</a>"});
			   
	//Layers - Address changed 6-Feb-2010 - previous below as a comment===========================	
		 
		 var trails = new OpenLayers.Layer.OSM('Wanderkarte', 'http://topo.wanderreitkarte.de/topo/${z}/${x}/${y}.png', {minZoomLevel: 3,maxZoomLevel: 15 , numZoomLevels: 20, isBaseLayer:false, transparent: true,transitionEffect:null, attribution: "Data by <a href='http://openstreetmap.org/'>OSM</a> and <a href='http://www.wanderreitkarte.de/'>Wanderreitkarte</a>"});
		 trails.setVisibility(false);
		 
		  var base2 = new OpenLayers.Layer.OSM("Wanderkarte Base", "http://base2.wanderreitkarte.de/base/${z}/${x}/${y}.png",{minZoomLevel: 3,maxZoomLevel: 15 , numZoomLevels: 20, isBaseLayer:true, transitionEffect:null, attribution: "Data by <a href='http://openstreetmap.org/'>OSM</a> and <a href='http://www.wanderreitkarte.de/'>Wanderreitkarte</a>"});
		 base2.setVisibility(false);
		
		osmMapnik = new OpenLayers.Layer.OSM.Mapnik("OSM Mapnik",{minZoomLevel: 1, maxZoomLevel: 19, numZoomLevels: 20, isBaseLayer:false, opacity: 0.3, transparent: true, transitionEffect:null}); 
		osmMapnik.setVisibility(false);

       var pt2 = new OpenLayers.Layer.OSM("Public Transport","http://openptmap.org/tiles/${z}/${x}/${y}.png", { minZoomLevel: 3, maxZoomLevel: 17, numZoomLevels: 18, isBaseLayer:false, transparent: true, transitionEffect:null, attribution: "Data by <a href='http://http://openptmap.de//'>OpenPT</a>" });
	   pt2.setVisibility(false);
	   
		  var relief = new OpenLayers.Layer.XYZ("Relief","http://maps-for-free.com/layer/relief/z${z}/row${y}/${z}_${x}-${y}.jpg",{buffer: 0, sphericalMercator: true, minZoomLevel: 9, maxZoomLevel: 20, numZoomLevels: 11, isBaseLayer:true,  transitionEffect:null, attribution: 'SRTM large scale relief (zoom 9-20) maps from <a target="_blank" href="http://maps-for-free.com/">maps-for-free.com</a>'});
		  
// Specify the OpenStreetBugs API server
  try{
		       var osblayer = new OpenLayers.Layer.OpenStreetBugs("OpenStreetBugs", {serverURL : "http://openstreetbugs.schokokeks.org/api/0.1/",iconOpen : new OpenLayers.Icon("http://openstreetbugs.schokokeks.org/client/open_bug_marker.png", new OpenLayers.Size(22, 22), new OpenLayers.Pixel(-11, -11)),iconClosed : new OpenLayers.Icon("http://openstreetbugs.schokokeks.org/client/closed_bug_marker.png",new OpenLayers.Size(22, 22), new OpenLayers.Pixel(-11, -11)), readonly : true, visibility: false});
		    	}
		      catch(err)
              {
              }
	
var ch = new OpenLayers.Layer.OSM("Cycle &amp; Hiking", "http://www.openstreetbrowser.org/tiles/overlay_ch/${z}/${x}/${y}.png", {numZoomLevels: 19, isBaseLayer: false, visibility: false });
 var pt = new OpenLayers.Layer.OSM("Public Transport", "http://www.openstreetbrowser.org/tiles/overlay_pt/${z}/${x}/${y}.png", {numZoomLevels: 19, isBaseLayer: false, visibility: false });
var car =new OpenLayers.Layer.OSM("Fuel &amp; Transport","http://www.openstreetbrowser.org/tiles/overlay_car/${z}/${x}/${y}.png", {numZoomLevels: 19, isBaseLayer: false, visibility: false });
var food = new OpenLayers.Layer.OSM("Food &amp; Drink", "http://www.openstreetbrowser.org/tiles/overlay_food/${z}/${x}/${y}.png", {numZoomLevels: 19, isBaseLayer: false, visibility: false });
var culture = new OpenLayers.Layer.OSM("Culture &amp; Tourism", "http://www.openstreetbrowser.org/tiles/overlay_culture/${z}/${x}/${y}.png", {numZoomLevels: 19, isBaseLayer: false, visibility: false });
var services = new OpenLayers.Layer.OSM("Services", "http://www.openstreetbrowser.org/tiles/overlay_services/${z}/${x}/${y}.png", {numZoomLevels: 19, isBaseLayer: false, visibility: false });
var shop = new OpenLayers.Layer.OSM("Shops", "http://www.openstreetbrowser.org/tiles/shop/${z}/${x}/${y}.png", {numZoomLevels: 19, isBaseLayer: false, visibility: false });
var agri_ind = new OpenLayers.Layer.OSM("Agriculture &amp; Industry", "http://www.openstreetbrowser.org/tiles/agri_ind/${z}/${x}/${y}.png", {numZoomLevels: 19, isBaseLayer: false, visibility: false });
	
            //var trails = new OpenLayers.Layer.OSM("Wanderkarte", "http://topo.geofabrik.de/trails/${z}/${x}/${y}.png",                 {minZoomLevel: 3, maxZoomLevel: 15 , numZoomLevels: 20, isBaseLayer:false, transitionEffect:null, attribution: "Data by <a href='http://openstreetmap.org/'>OSM</a> and <a href='http://topo.geofabrik.de/'>OSMC</a>"}); 
	//=============================================================================================		
						
			var nexrad_wms = new OpenLayers.Layer.WMS( "Nexrad","http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
		{layers: 'nexrad-n0r-m45m',
		exceptions:"application/vnd.ogc.se_xml",
		transparent: "true", format: "image/png"},
		{ tileSize: new OpenLayers.Size(256,256),
		buffer: 1 } );

        nexrad_wms.setVisibility(false);
		
		//oalayer = new OpenLayers.Layer.WMS("Oxford Archaeology", "http://geoserver.thehumanjourney.net:80/geoserver/wms?",                            {layers: 'oadigi:oasites', transparent: true, format: 'image/png', buffer:0},                             {isBaseLayer: false});
		//oalayer.setVisibility(false);
		
		function osm_getTileURL(bounds) {
            var res = this.map.getResolution();
            var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
            var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
            var z = this.map.getZoom();
            var limit = Math.pow(2, z);
 
            if (y < 0 || y >= limit) {
                return OpenLayers.Util.getImagesLocation() + "404.png";
            } else {
                x = ((x % limit) + limit) % limit;
                return this.url + z + "/" + x + "/" + y + "." + this.type;
            }
        }

      
		lonvia = new OpenLayers.Layer.TMS("Lonvia's Hiking Symbols","http://osm.lonvia.de/hiking/",{type: 'png', getURL: osm_getTileURL, displayOutsideMaxExtent: true, isBaseLayer: false,transparent: true, "visibility": false});
		
		 hill = new OpenLayers.Layer.TMS("Hillshading (NASA SRTM3)","http://toolserver.org/~cmarqu/hill/",{type: 'png', getURL: osm_getTileURL,displayOutsideMaxExtent: true, isBaseLayer: false, transparent: true, "visibility": false});
 
         hill2 = new OpenLayers.Layer.TMS("Hillshading (darker)","http://toolserver.org/~cmarqu/hill/",{type: 'png', getURL: osm_getTileURL, displayOutsideMaxExtent: true, isBaseLayer: false,transparent: true, "visibility": false});
		 
		 var grid = new OpenLayers.Layer.cdauth.CoordinateGrid(null, { visibility: true, shortName: "grid" });
		 //http://wiki.openstreetmap.org/wiki/Cdauth's_map/API;
		 
		//nasa = OpenLayers.Layer.WMS("NASA Global Mosaic", "http://t1.hypercube.telascience.org/cgi-bin/landsat7", {layers: "landsat7"},{isBaseLayer: false} );
		//nasa.setVisibility(false);

		//var drg = new OpenLayers.Layer.WMS("Topo Maps","http://terraservice.net/ogcmap.ashx",{layers: "DRG"},{isBaseLayer: true},{SRS:"EPSG:4326"},{numZoomLevels: 20});
        
		//shade = new OpenLayers.Layer.WMS("Shaded Relief","http://gisdata.usgs.gov/wmsconnector/com.esri.wms.Esrimap?ServiceName=USGS_EDC_Elev_NED_3",{'sphericalMercator': true,SRS:"EPSG:4326",layers: "HR-NED.IMAGE", reaspect: "false", transparent: 'true'},{isBaseLayer: false, opacity: 0.3});
			
		//var usgs_topo = new OpenLayers.Layer.WMS( "USGS Topos","http://terraservice.net/ogcmap.ashx?",{'sphericalMercator': true,SRS:"EPSG:4326",layers: 'DRG',numZoomLevels: 20},{isBaseLayer: true} );	
		
		 //var gm_layer = new OpenLayers.Layer.WMS("Blue Marble","http://maps.opengeo.org/geowebcache/service/wms?TILED=true&",{SRS:"EPSG:26986",layers : "bluemarble",maxResolution : 1.40625, minZoomLevel: 2, maxZoomLevel: 16 ,numZoomLevels: 16,isBaseLayer: true});
		 
		// var landuse = new OpenLayers.Layer.WMS("Land Use","http://gisdata.usgs.net/servlet/com.esri.wms.Esrimap?ServiceName=USGS_WMS_NLCD",{layers: 'US_NLCD',"sphericalMercator": true,});
	
		//var npe = new OpenLayers.Layer.WMS( "OS Popular Edition (1940s)","http://www.getmapping.com/iedirectimage/getmappingwms.aspx", {'format':'jpeg', 'layers':'npeoocmap'},{projection: new OpenLayers.Projection("EPSG:27700"),maxExtent: new OpenLayers.Bounds(0, 0, 800000, 1300000),maxResolution: 2500,minResolution: 1});
		
		//Seamark
		//projection: new OpenLayers.Projection("EPSG:4326"),
		layer_seamark = new OpenLayers.Layer.TMS("Sea Marks", "http://tiles.openseamap.org/seamark/",{ type: 'png', getURL:osm_getTileURL, isBaseLayer:false, displayOutsideMaxExtent:true,"visibility": false});
		
		 //create a vector layer for drawing
	    var  vector = new OpenLayers.Layer.Vector("Lines_&_Polygons");
		  
		  this.map.addLayer(layerCycleMap);
		  this.map.addLayer(layerMapnik);
		  this.map.addLayer(layerTilesAtHome);
		  
		  this.map.addLayer(openpiste);
	      //this.map.addLayer(opm);
		  this.map.addLayer(osmb);
		  this.map.addLayer(hikebike);
		  
		  this.map.addLayers([gmap, gphy, ghyb, gsat]);
		  
		  this.map.addLayer(bing);
		  this.map.addLayers([shaded, hybrid, aerial]);
		  //this.map.addLayer(birdseye);
		  this.map.addLayers([bingroad, binghybrid, bingaerial]);
		
		  //this.map.addLayer(oslayer);
		  
		  this.map.addLayer(mm_map);
		   //this.map.addLayer(layer1);
		  
           try{
		       this.map.addLayer(yahoo);
		    	}
		      catch(err)
              {
              }
		  //this.map.addLayers([yahoosat, yahoohyb]);
		  
		  //this.map.addLayers([mapsurferroad, mapsurfertopo]);
		 
		  this.map.addLayer(relief);		  
		  
		  this.map.addLayer(pubtrans);
		  this.map.addLayer(usrelief);
		  		  
		  this.map.addLayer(npe);  //Historic OS layer
	      this.map.addLayer(os7);
	      this.map.addLayer(os1);
		  
		  this.map.addLayer(nlslayer);  //NLS historic layer
		  this.map.addLayer(streetview);
		  
		 //Layers
		  this.map.addLayer(osmMapnik);
		   
		  this.map.addLayer(hill);
          this.map.addLayer(hill2);
		  this.map.addLayer(hills);
		  this.map.addLayer(grid);
		  
		  //this.map.addLayers([ch, pt, car, food, culture, services, shop, agri_ind ]);
		  
		  this.map.addLayer(trails);
		  this.map.addLayer(base2);
		  this.map.addLayer(pt2);
		  
		  //this.map.addLayer(nasa);
		  //this.map.addLayer(npe);
		  
		  ///this.map.addLayer(oalayer);
		  this.map.addLayer(lonvia);
		  
		  try{
		    this.map.addLayer(osblayer);
		     	}
		      catch(err){
		   	  }	
		  
		  this.map.addLayer(nexrad_wms);
		  this.map.addLayer(vector);
		  
		  //this.map.addLayer(gm_layer);
		  //this.map.addLayers([drg, shade]);
		  this.map.addLayer(layer_seamark);		  
		  //this.map.addLayer(earthNC);
		  
		  //this.map.addLayer(usgs_topo);
		  //this.map.addLayer(landuse);
		 
		  initialloadtopo=2;
		  }
}

		  	//alert("Base Layer Load: Base Layer: " + this.map.displayProjection + " :  Display: " + this.map.displayProjection + " : Projection: " + this.map.projection + " : Lon: " + long1 + " : Lat: " + lat1 + " : MapSelection: " + mapselection + " : MapDisplay: " + mapdisplay + " : InitialLoadBKG: " + initialloadbkg+ " : InitialLoadTopo: " + initialloadtopo);
		  
	this.defaultLonglat = new OpenLayers.LonLat(long1, lat1); 
    this.defaultLonglat.transform(this.map.displayProjection, this.map.baseLayer.projection);
   
	this.map.addControl(new OpenLayers.Control.ScaleLine());
    this.map.addControl(new OpenLayers.Control.MousePosition( {id: "gr_mouse", prefix: "TM ", displayProjection: this.map.baseLayer.projection, numDigits: 0} ));
    this.zoomChangeNeeded = true;
	
	<!--Add zoom and pan controls to map-->
	var nav=new OpenLayers.Control.NavToolbar();
	nav.position=new OpenLayers.Pixel(80,30);
	nav.title = "Select and Drag Map or Draw Rectangle for Zooming";
	this.map.addControl(nav);
	
	 // add the LayerSwitcher (a.k.a. Map Legend)
	 layerSwitcher = new OpenLayers.Control.cdauth.LayerSwitcher();
     //layerSwitcher = new OpenLayers.Control.LayerSwitcher();
     layerSwitcher.ascending = true;
     this.map.addControl(layerSwitcher);
	
	//var panel2 = new OpenLayers.Control.NavToolbar();
	//this.map.addControl(panel2);
	
	//Removed 12-Nov-2011 since icons not showing correctly
	//try{
		    //var veb=new OpenLayers.Control.EditingToolbar(vector);
	        //veb.position=new OpenLayers.Pixel(25, 30);
			//veb.title = "Draw Polygons, Lines, Circles or Cancel.  Double click to finish drawing";
	        //this.map.addControl(veb);
		    // 	}
		    //  catch(err){
		   	//  }	
	
	if (OpenLayers.Control.MultitouchNavigation) {
		var touchControl = new OpenLayers.Control.MultitouchNavigation();
		this.map.addControl(touchControl);
	}
	
	//this.map.addControl(new OpenLayers.Control.MousePosition());
	
	//if (mapdisplay==2)
	//{
	//var osmar = new OpenLayers.Layer.OSM.Osmarender("Osmarender");
   // var options = {layers: [osmar]};
   // this.map.addControl(new OpenLayers.Control.OverviewMap(options));
	//}
	
//Add initial and centre marker===============================================================

//marqueurs - projection de la carte:
		mapproj= this.map.projection;
		
		//couche des marqueurs
		coucheMarqueurs=new OpenLayers.Layer.Markers("Markers");
		this.map.addLayer(coucheMarqueurs);
		
		var taille;
		var decalage;
		var icone;
		var position;
		
		if (this.map.getZoom() == 0)
		{
		   zoomlevel = 14;
		}
		else
		{
		  zoomlevel = this.map.getZoom();	
		}
		
		//Initial position with red marker
		taille=new OpenLayers.Size(35,45);
		//decalage=new OpenLayers.Pixel(-(taille.w/2), -45);
		decalage=new OpenLayers.Pixel(-17.5, -42);
		//decalage=new OpenLayers.Pixel(-20, -37);
		icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_red.png', taille, decalage);
		position=new OpenLayers.LonLat(long, lat);
		
		position.transform(this.map.displayProjection, this.map.baseLayer.projection);
		
		baselayerProj = this.map.baseLayer.projection;
		
		cmarqueur=new OpenLayers.Marker(position, icone);
		coucheMarqueurs.addMarker(cmarqueur);

      //Form text string
		            EW = "E"; 
					 if (long < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (lat < 0)
					{
					 NS = "S";
					}
					
					ptlat = Math.abs(lat);
					ptlon = Math.abs(long);
					
					//Save positions for Geocoder
				 clicklat = lat;
				 clicklon = long;
				 
				 p=new OpenLayers.LonLat(long,lat)
					ukgrid = LatLongToOSGrid(p);
					//alert(p + " : " + ukgrid);
					
					if(ukgrid.length==0) {
						ukgrid="n/a";
					}
					
				//alerttext =  "Vous avez cliqué près de " +  "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS;
				//alert(alerttext);
				document.getElementById('message1').innerHTML = "Initial Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " +  ukgrid + " : Elevation: " +  alt + "m"; 
				
				LatDegrees = Math.floor(ptlat);
				LatMinutes = Math.floor((ptlat - Math.floor(ptlat)) * 60);
				LatDecMinutes = Math.round((((ptlat - Math.floor(ptlat)) * 60) - LatMinutes) * 60 * 100)/100;
				
				LonDegrees = Math.floor(ptlon);
				LonMinutes = Math.floor((ptlon- Math.floor(ptlon))*60);
				LonDecMinutes = Math.round((((ptlon - Math.floor(ptlon)) * 60) - LonMinutes) * 60 * 100)/100;
				
				Geohack = "http://toolserver.org/~geohack/geohack.php?params=" + LatDegrees + "_" + LatMinutes + "_" + LatDecMinutes + "_" + NS + "_" + LonDegrees + "_" + LonMinutes + "_" + LonDecMinutes + "_" + EW;
				
				//http://toolserver.org/~geohack/geohack.php?params=55_23_59_N_1_30_0_E
				
				clickposition = "Map Clicked at: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100+ " : UK Grid: " +  ukgrid + " : Elevation: " +  alt + "m" + " : " + "<a href = " + Geohack + "> Geohack Link</a>"; 

	   //Centre map on position
	   this.map.setCenter(this.defaultLonglat, zoomlevel);
	
		//Centre position
		 centrepos = this.map.getCenter();
		
		centrepos.transform(this.map.displayProjection, this.map.baseLayer.projection);
		
		//alert("Lon: " + centrepos.lon + "Lat: " + centrepos.lat);
		taille=new OpenLayers.Size(15,15);
		//decalage=new OpenLayers.Pixel(-(taille.w/2), -taille.h/2);
		decalage=new OpenLayers.Pixel(-7.5, -7.5);
		icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_cross.png', taille, decalage);
		position=new OpenLayers.LonLat(long, lat);
		
		position.transform(this.map.displayProjection, this.map.baseLayer.projection);
		
		marqueur=new OpenLayers.Marker(position, icone);
		coucheMarqueurs.addMarker(marqueur);

    //Form text string
		            EW = "E"; 
					 if (long < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (lat < 0)
					{
					 NS = "S";
					}
					
					ptlat = Math.abs(lat);
					ptlon = Math.abs(long);
					//alert("Centre1: " + centrepos + " : Lat: " + centrepos.lat + " : Long: " + centrepos.lon);
					
					p=new OpenLayers.LonLat(centrepos.lon,centrepos.lat)
					ukgrid = LatLongToOSGrid(p);
					//alert(p + " : " + ukgrid);
					
					if(ukgrid.length==0) {
						ukgrid="n/a";
					}
					
				document.getElementById('message2').innerHTML = "Centre Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " + ukgrid;
				centreposition = "Centre Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " + ukgrid;
						  
			//Write data for bottom of page
			document.getElementById('lat').innerHTML 		= "n/a";
			document.getElementById('lng').innerHTML 	    = "n/a";
			document.getElementById('grd').innerHTML 		= "n/a";
			document.getElementById('alt').innerHTML 		= "n/a";
			document.getElementById('speed').innerHTML 		= "n/a";
			document.getElementById('head').innerHTML 		= "n/a";
			document.getElementById('ts').innerHTML 		= "n/a";
			document.getElementById('satCount').innerHTML 	= "n/a"; 

		this.map.events.register("moveend", this.map, function() {
		if(trackingon == 0)
		{
	     updatecentre();
		// updatetimezone();
		 updateWikipedia();
		// updateWeather();
	     }
       });
	  
		//Get nearest weather and Wikipedia
		updatetimezone();
		updateWikipedia();
		updateWeather();
		
		// Update centre position
		updatecentre();
		
		var pointLayer = new OpenLayers.Layer.Vector("Point Layer");
                var lineLayer = new OpenLayers.Layer.Vector("Line Layer");
                var polygonLayer = new OpenLayers.Layer.Vector("Polygon Layer");

                this.map.addLayers([pointLayer, lineLayer, polygonLayer]);

                drawControls = {
                    point: new OpenLayers.Control.DrawFeature(pointLayer,
                                OpenLayers.Handler.Point),
                    line: new OpenLayers.Control.DrawFeature(lineLayer,
                                OpenLayers.Handler.Path),
                    polygon: new OpenLayers.Control.DrawFeature(polygonLayer,
                                OpenLayers.Handler.Polygon)
                };

                for(var key in drawControls) {
                    map.addControl(drawControls[key]);
                }

                document.getElementById('noneToggle').checked = true;
            }

            function toggleControl(element) {
                for(key in drawControls) {
                    var control = drawControls[key];
                    if(element.value == key && element.checked) {
                        control.activate();
                    } else {
                        control.deactivate();
                    }
                }
            }

            function allowPan(element) {
                var stop = !element.checked;
                for(var key in drawControls) {
                    drawControls[key].handler.stopDown = stop;
                    drawControls[key].handler.stopUp = stop;
                }
	   
   Position.clone($("map"), $("DrawingToolbar"), {offsetLeft:100, offsetTop:62.5, setWidth:false, setHeight:false});
   window.onresize = function()
   {
	resize_id('map');
   }
   resize_id('map');
		
}

//==============================================================

function changeOpacity(byOpacity) {
            
		try{
		   	 osmMapnik.setVisibility(true);
			 hill.setVisibility(true);
			 var maxOpacity = 1.0;
             var minOpacity = 0.0;
			var newOpacity = (parseFloat(OpenLayers.Util.getElement('opacity').value) + byOpacity).toFixed(1);
            newOpacity = Math.min(maxOpacity,
                                  Math.max(minOpacity, newOpacity));
            OpenLayers.Util.getElement('opacity').value = newOpacity;
            osmMapnik.setOpacity(newOpacity);
	   	}
	     catch(err){
	    }	
        }

// Custom tile URL
        getTileURL=function(p,z){
            return "tiles/"+img_base+"/"+z+"/"+p.x+"-"+p.y+".png";
        }

function updatemap(){
	
	    centrepos = this.map.getCenter();
		centrepos.transform(this.map.baseLayer.projection, this.map.displayProjection);
		
		this.map=Map.map;
	
	    mapselection = document.getElementById('mapselection').value;
        mapname = mapselection;
	
	    lonlat = this.map.getCenter();
		lonlat.transform(this.map.baseLayer.projection, this.map.displayProjection);
		lat = lonlat.lat;
		long = lonlat.lon;
		  
		lat1 = lat;
		long1 = long;
		  
		  defaultLonglat =  new OpenLayers.LonLat(long, lat);
		
		//alert("Update Map: Base Layer: " + this.map.displayProjection + " :  Display: " + this.map.displayProjection + " : Projection: " + this.map.projection + " : lonlat: " + lonlat +  " : Lon: " + long + " : Lat: " + lat + " : MapSelection: " + mapselection + " : MapDisplay: " + mapdisplay + " : InitialLoadBKG: " + initialloadbkg+ " : InitialLoadTopo: " + initialloadtopo);
	
	if (mapselection == "TGF")
	{
		//Clear current map
	    document.getElementById('map').innerHTML = "";
		initialloadtopo=1;
		mapdisplay=2;
		//reloadPage();
		Map.create();
		Map.addBaseLayers();
	}
	else
	{
		if (mapdisplay==1)
		{
		//Map.zoomChanged();
		//alert("UpdateMap: " + mapname + " : Selection: " + mapselection + "Map display: " + mapdisplay);
		Map.addBaseLayers();
		this.map.zoomOut(zoomlevel - 1);
		this.map.zoomIn(zoomlevel + 1);
		}
		else
		{
        //Clear current map
    	document.getElementById('map').innerHTML = "";
		initialloadbkg=1;
		mapdisplay=1;
		//reloadPage();
		Map.create();
		Map.addBaseLayers();
		}
	}
		return;
		}

Map.zoomChanged = function () {
    
	this.map=Map.map;
	mapname=mapselection;
	
	try{
	this.mapTypes = ['DTK1000','DTK1000','DTK1000','DTK500-V','DTK500-V','DTK200-V','DTK200-V',mapname,mapname,mapname];
	
	//if (this.map.getZoom()>7)
	//{	
	//mapType = mapname;
    //}
	//else
	//{
	mapType = Map.mapTypes[this.map.getZoom()];
	//alert("ZoomChange: " + mapname + " : Selection: " + mapselection + "Map display: " + mapdisplay + " : MapType: " + mapType);
	// }
		      var bl = this.baseLayer;
	          bl.setUrl(mapType == mapname ? Map.server.dlm : Map.server.bkg);
              bl.attribution = mapType == mapname ? Map.attribution.dlm : Map.attribution.bkg;
			  var attr = bl.map.getControlsByClass('OpenLayers.Control.Attribution');
              attr[0].updateAttribution();
              bl.mergeNewParams( { layers: mapType } );
		     	}
		      catch(err){
		   	  }	
}
//==========================================================================================================
 
 //Start of Geoposition
function clearWLAN() {

 try
      {
         navigator.geolocation.clearWatch(geoid);
      }
      catch(err)
      {
      }
try{
	 g = coucheMarqueurs.removeMarker(lokimarqueur);
	 //h = map.removeLayer(lokimarkers);
	}
	catch(err){
}
try{
	 i = coucheMarqueurs.removeMarker(cmarqueur);
	 //h = map.removeLayer(lokimarkers);
	}
	catch(err){
}

try{
	  q = this.map.removePopup(popup);
	   	}
	    catch(err){
	 	  }		

//Initial position with red marker
		taille=new OpenLayers.Size(35,45);
		decalage=new OpenLayers.Pixel(-17.5, -42);
		icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_red.png', taille, decalage);
		position=new OpenLayers.LonLat(plon5, plat5);
		position.transform(this.map.displayProjection, this.map.baseLayer.projection);
		baselayerProj = this.map.baseLayer.projection;
		cmarqueur=new OpenLayers.Marker(position, icone);
		coucheMarqueurs.addMarker(cmarqueur);
}

function geo_position()
{
 mapzoom = this.map.getZoom();
var browser=navigator.appName;

try{
	 i = coucheMarqueurs.removeMarker(cmarqueur);
	 //h = map.removeLayer(lokimarkers);
	}
	catch(err){
}

try{
	  q = this.map.removePopup(popup);
	   	}
	    catch(err){
	 	  }	
		  	
 //================
nVer = navigator.appVersion;
nAgt = navigator.userAgent;
browserName  = navigator.appName;
fullVersion  = ''+parseFloat(navigator.appVersion); 
majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;

// In MSIE, the true version is after "MSIE" in userAgent
if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
 browserName = "Microsoft Internet Explorer";
 fullVersion = nAgt.substring(verOffset+5);
}
// In Opera, the true version is after "Opera" 
else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+6);
}
// In Chrome, the true version is after "Chrome" 
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" 
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
 browserName = "Safari";
 fullVersion = nAgt.substring(verOffset+7);
}
// In Firefox, the true version is after "Firefox" 
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
 browserName = "Firefox";
 fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent 
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) 
{
 browserName = nAgt.substring(nameOffset,verOffset);
 fullVersion = nAgt.substring(verOffset+1);
 if (browserName.toLowerCase()==browserName.toUpperCase()) {
  browserName = navigator.appName;
 }
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1) fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1) fullVersion=fullVersion.substring(0,ix);

majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
 fullVersion  = ''+parseFloat(navigator.appVersion); 
 majorVersion = parseInt(navigator.appVersion,10);
}

//alert("Browser name " + browserName + " : Full version " + fullVersion + " : Major version " + majorVersion + " : navigator.appName " + navigator.appName +  " : navigator.userAgent " + navigator.userAgent);
//alert("Browser name " + browserName +  " : " + majorVersion);

//==================================  

if(browserName == "Microsoft Internet Explorer"){
      loki_position();
      return;
   }
 
 if (navigator.geolocation) {
 window.status = "Looking for browser position....";
navigator.geolocation.getCurrentPosition(foundLocation, noLocation, {enableHighAccuracy:true, maximumAge:40000, timeout:5000});
geoid=navigator.geolocation.watchPosition(foundLocation, noLocation, {enableHighAccuracy:true, maximumAge:100000, timeout:40000});

} else {
  alert("HTML5 Error");
  loki_position(); 
}

function foundLocation(position) {

  window.status = "";
  plat = position.coords.latitude;
  plon = position.coords.longitude;
  plat5=plat;
  plon5=plon;
  palt =  position.coords.altitude;
  paccuracy = position.coords.accuracy;
  paltaccuracy = position.coords.altitudeAccuracy;
  pheading = position.coords.heading;
  pspeed = position.coords.speed;
  
  this.map=Map.map;
	 position1 = new OpenLayers.LonLat(position.coords.longitude, position.coords.latitude);
    position1.transform(this.map.displayProjection, this.map.baseLayer.projection);
	
	//this.map.setCenter(position1, mapzoom);
	this.map.setCenter(position1);
	p=new OpenLayers.LonLat(position.coords.longitude, position.coords.latitude)
	lokiosgridRef = LatLongToOSGrid(p);
	
	if(lokiosgridRef.length==0) {
		lokiosgridRef="n/a";
	}
  
  now = new Date();
  hours = now.getHours();
  minutes = now.getMinutes();
  seconds = now.getSeconds();
  timeValue = "" + ((hours >12) ? hours -12 :hours)
  if (timeValue == "0") timeValue = 12;
  timeValue += ((minutes < 10) ? ":0" : ":") + minutes
  timeValue += ((seconds < 10) ? ":0" : ":") + seconds
  timeValue += (hours >= 12) ? " PM" : " AM"
  
  //alert("Geo-Position: " + position + " : " + mapPoint + " : " + plat + " : " + plon + " : Alt " + palt + " m : Accuracy " + paccuracy + " : Altitude Accuracy " + paltaccuracy + " : Heading " + pheading + " : Speed " + pspeed + " : Time " + timeValue);
  
  //Add marker==========================

   clicklat = position.coords.latitude;
   clicklon = position.coords.longitude;
	
	if (alt==0)
	{
	 alt = "n/a "
	}
     
	 EW = "E";
         if (position.coords.longitude < 0)
         {
            EW = "W";
         }

         NS = "N";
         if (position.coords.latitude < 0)
         {
            NS = "S";
         }

         ptlat = Math.abs(position.coords.latitude);
         ptlon = Math.abs(position.coords.longitude); 
	 
	clickposition = "Click Marker Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS +   " : UK Grid: " + lokiosgridRef + " : Elevation: " +  alt + "m" ;
	
		 updateWeather();
         updatetimezone();
		 updateWikipedia();
			
	        EW = "E"; 
					 if (position.coords.longitude < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (position.coords.latitude < 0)
					{
					 NS = "S";
					}
					
					ptlat = Math.abs(position.coords.latitude);
					ptlon = Math.abs(position.coords.longitude);
					
			lokiposition = "Browser Name " + browserName +  " : " + majorVersion + '<br/>' + "Long: " + Math.round(ptlon *10000)/10000 + EW + '<br/>' + "Lat: " + Math.round(ptlat * 10000)/10000 + NS + '<br/>' + "UK Grid: " + lokiosgridRef + '<br/>' + "Accuracy: " + paccuracy + "m" + '<br/>' + "Time: " + timeValue;
			lokiposition1 = "Browser WLAN Position: " + browserName + " " + majorVersion + " : Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + ' : ' + "UK Grid: " + lokiosgridRef  + " : Accuracy: " + paccuracy + "m : Time: " + timeValue;
			
			document.getElementById('message1').innerHTML = clickposition + '<br/>' + lokiposition1;	
	
	 try{
		  g = coucheMarqueurs.removeMarker(lokimarqueur);
		  //h = map.removeLayer(lokimarkers);
			}
		  catch(err){
			}
			
		try{
	  q = this.map.removePopup(popup);
	   	}
	    catch(err){
	 	  }		
			
    	//infocontent = "Loki Skyhook Wireless Marker: " + '<br/>' + lokiposition +'<br/>'+ geooutput ;
		infocontent = "Browser WLAN Marker: " + '<br/>' + lokiposition ;
		  
		//couche des marqueurs
		var taille;
		var decalage;
		var icone;
		var position;
		
		//Loki position with red marker
		taille=new OpenLayers.Size(35,45);
		decalage=new OpenLayers.Pixel(-17.5, -42);
		icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_blue.png', taille, decalage);
		lokimarqueur=new OpenLayers.Marker(position1, icone);
		coucheMarqueurs.addMarker(lokimarqueur);
		
			popup = new OpenLayers.Popup("BlackMarker",
                position1,
                new OpenLayers.Size(210,120),
                   infocontent,
				   true);
				popup.maxSize = (210,120);  
				popup.autoSize = true;  
                this.map.addPopup(popup);
    }  
}

function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function noLocation(error) {
 
//PERMISSION_DENIED (1) if the user clicks that “Don’t Share” button or otherwise denies you access to their location.
//POSITION_UNAVAILABLE (2) if the network is down or the positioning satellites can’t be contacted.
//TIMEOUT (3) if the network is up but it takes too long to calculate the user’s position.
//UNKNOWN_ERROR (0) if anything else goes wrong.
 window.status = "";
 switch(error.code)  
            {  
               
				case error.code == 1: alert("User did not agree to share geolocation data: Error " + error.code);  
                break;  
  
                case error.code == 2: alert("Could not detect current position: Error " + error.code);
				navigator.geolocation.clearWatch(geoid);
				gearslocation();  
                 break;   
  
                case error.code == 3: alert("Retrieving position timed out - will now try Loki Skyhook: Error " + error.code);
				navigator.geolocation.clearWatch(geoid);
				loki_position();
                break;   
  
                default: //alert("Unknown error - browser may not be compatible and will now try Loki Skyhook: Error " + error.code);
				navigator.geolocation.clearWatch(geoid);
				loki_position(); 
                 break;  
            }  
}
 
 
 
 function loki_position()
   {
	mapzoom = this.map.getZoom();
	var browser=navigator.appName;
 
	if (browser != "Microsoft Internet ExplorerAAA") {
	var loki = LokiAPI();
 
	loki.onSuccess = function(location) {
	
	this.map=Map.map;
	position=new OpenLayers.LonLat(location.longitude, location.latitude);
	position.transform(this.map.displayProjection, this.map.baseLayer.projection);
	
	this.map.setCenter(position, mapzoom);
	p=new OpenLayers.LonLat(location.longitude, location.latitude)
	lokiosgridRef = LatLongToOSGrid(p);
	
	if(lokiosgridRef.length==0) {
		lokiosgridRef="n/a";
	}
	
	clicklat = location.latitude;
	clicklon = location.longitude;
	
	if (alt==0)
	{
	 alt = "n/a "
	}
	
	 EW = "E";
         if (location.longitude < 0)
         {
            EW = "W";
         }

         NS = "N";
         if (location.latitude < 0)
         {
            NS = "S";
         }

         ptlat = Math.abs(location.latitude);
         ptlon = Math.abs(location.longitude);
     
	clickposition = "Click Marker Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS +   " : UK Grid: " + lokiosgridRef + " : Elevation: " +  alt + "m" ;
	
	//Add in geocoding 
					//geocoder = new GClientGeocoder();	
		           //getAddress2(clicklat, clicklon);
					
					//clickmarker(p);
					
					updateWeather();	
  					updatetimezone();
	
	        EW = "E"; 
					 if (location.longitude < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (location.latitude < 0)
					{
					 NS = "S";
					}
					
					ptlat = Math.abs(location.latitude);
					ptlon = Math.abs(location.longitude);
					
			lokiposition = "Long: " + Math.round(ptlon *10000)/10000 + EW + '<br/>' + "Lat: " + Math.round(ptlat * 10000)/10000 + NS + '<br/>' + "UK Grid: " + lokiosgridRef ;
			
			lokiposition1 = "Loki Skyhook Wireless WLAN Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + ' : ' + "UK Grid: " + lokiosgridRef ;
			
			document.getElementById('message1').innerHTML = clickposition + '<br/>' + lokiposition1;	
	
	 try{
		  g = coucheMarqueurs.removeMarker(lokimarqueur);
		  //h = map.removeLayer(lokimarkers);
			}
		  catch(err){
			}
	
	       //alert(location.street + " : " + location.street.length)
	     if(location.street.length !=0)
	     {	
	     infocontent = "Loki Skyhook Wireless Marker: " + location.house_number+' '+location.street+'\n'+location.city+', '+location.region_code+' ' + location.postal_code+'\n'+lokiposition;
	     }
	     else
     	{
    	//infocontent = "Loki Skyhook Wireless Marker: " + '<br/>' + lokiposition +'<br/>'+ geooutput ;
		infocontent = "Loki Skyhook Wireless Marker: " + '<br/>' + lokiposition ;
    	}
		  
		//couche des marqueurs
		var taille;
		var decalage;
		var icone;
		var position;
		
		//Loki position with red marker
		taille=new OpenLayers.Size(35,45);
		decalage=new OpenLayers.Pixel(-17.5, -42);
		icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_blue.png', taille, decalage);
		lokimarqueur=new OpenLayers.Marker(position, icone);
		coucheMarqueurs.addMarker(lokimarqueur);
		
			popup = new OpenLayers.Popup("BlackMarker",
                position,
                new OpenLayers.Size(210,120),
                   infocontent,
				   true);
				popup.maxSize = (210,120);  
				popup.autoSize = true;  
                this.map.addPopup(popup);
	}
 
	loki.onFailure = function(error) {
	  alert("No location data available! Error: " + error);
	  }
 
		//1 - Scanner not found
		//2 - Wi-Fi not available
		//3 - No Wi-Fi in range
		//4 - Invalid Application Key
		//5 - Location server unavailable
		//6 - Location cannot be determined
		//7 - Proxy unauthorized
		//8 - File I/O Error
		//9 - Invalid File format
		//1000 - Plugin could not be installed
		//1001 - User denied location request
			
	loki.setKey('[sysmaps.co.uk]');
	loki.requestLocation(true,loki.FULL_STREET_ADDRESS_LOOKUP);
 
	}else{
		alert("This Loki location function is not available in " + browser );
	}
 
    } 
 
 //Google Geocoder==========================================================================================
 
 function getAddress2(clicklat, clicklon) {
  if (clicklat != null) {
    //alert("Start of Geocoder: " + clicklat + " : " + clicklon);
	address = new GLatLng(clicklat,clicklon)
    geocoder.getLocations(address, showAddress2);
  }
}

function showAddress2(response) {
 
  	try{
	  r = coucheMarqueurs.removeMarker(gmarqueur);
		}
	   catch(err){
			  	  }	
				  
	try{
	  q = this.map.removePopup(popup);
	   	}
	    catch(err){
	 	  }		
  		  
  if (!response || response.Status.code != 200) {
    alert("Geocoder Address Status Code: " + response.Status.code);
  } else {
    place = response.Placemark[0];
						   
		glat = place.Point.coordinates[1];
		glon = place.Point.coordinates[0];
						
						EW = "E"; 
								 if (place.Point.coordinates[0] < 0)
								{
								 EW = "W";
								 } 
								 
								 NS = "N";
								 if (place.Point.coordinates[1] < 0)
								{
								 NS = "S";
								}
								
								ptlat2 = Math.abs(place.Point.coordinates[1]);
								ptlon2 = Math.abs(place.Point.coordinates[0]);
								
								geoDistance = calcDistance(place.Point.coordinates[1], place.Point.coordinates[0], clicklat, clicklon);
								
	//Start of bearing formulas===================================================			

	//Code from http://www.movable-type.co.uk/scripts/latlong.html
	//More information from scripts-geo@movable-type.co.uk under GNU licence
	var dLong = place.Point.coordinates[0].toRad() - clicklon.toRad(); 
	var yy = Math.sin(dLong) * Math.cos(place.Point.coordinates[1].toRad());
    var xx = Math.cos(clicklat.toRad())*Math.sin(place.Point.coordinates[1].toRad()) -  Math.sin(clicklat.toRad())*Math.cos(place.Point.coordinates[1].toRad())*Math.cos(dLong);
	
	var brng = Math.atan2(yy, xx);
	//alert("dLon: " + dLong + " : X: " + xx + " : Y: " + yy + " : Bearing: " + brng);
	var brng = (brng * 180 / Math.PI);
	
	//Answer is in range -180 to + 180, therefore add 360 if <0
	if(brng<0) {
	 brng=brng+360;
	 }
	//alert(brng);
	
//End of bearing formulas===================================================			
							
					p=new OpenLayers.LonLat(place.Point.coordinates[0],place.Point.coordinates[1])
					ukgrid = LatLongToOSGrid(p);
					//alert(p + " : " + ukgrid);
					
					if(ukgrid.length==0) {
						ukgrid="n/a";
					}
					
					if ( place.AddressDetails.Accuracy == "n/a")
	 {
	 accuracytext = "n/a"
	 }
	 else
	 {
	 
	  if (place.AddressDetails.Accuracy == 0)
      {
         accuracytext = "Unknown location";
      }
      if (place.AddressDetails.Accuracy == 1)
      {
         accuracytext = "Country level";
      }
      if (place.AddressDetails.Accuracy == 2)
      {
         accuracytext = "Region (state, province, prefecture, etc.) level";
      }
      if (place.AddressDetails.Accuracy == 3)
      {
         accuracytext = "Sub-region (county, municipality, etc.) level";
      }
      if (place.AddressDetails.Accuracy == 4)
      {
         accuracytext = "Town (city, village) level";
      }
      if (place.AddressDetails.Accuracy == 5)
      {
         accuracytext = "Post code (zip code) level";
      }
      if (place.AddressDetails.Accuracy == 6)
      {
         accuracytext = "Street level accuracy";
      }
      if (place.AddressDetails.Accuracy == 7)
      {
         accuracytext = "Intersection level";
      }
      if (place.AddressDetails.Accuracy == 8)
      {
         accuracytext = "Address level";
      }
      if (place.AddressDetails.Accuracy == 9)
      {
         accuracytext = "Premise (building name, property name, shopping center, etc.)";
      }
	  
	  }
					
					geomarkerpos =  "Black GeoMarker Position: " + " Long: " + Math.round(ptlon2 *10000)/10000 + EW + " : Lat: " + Math.round(ptlat2 * 10000)/10000 + NS + " : UK Grid: " + ukgrid ;		
									  
		geooutput = geomarkerpos +  " : " + 'Address: ' + place.address + ' : ' +'Country Code: ' + place.AddressDetails.Country.CountryNameCode +  " : Distance: " + Math.round(geoDistance *100) / 100 + " km (" + Math.round(geoDistance /1.609344 * 100) / 100 + " miles) : Bearing: " + brng.toFixed(2) + 'deg : ' + 'Accuracy: ' + place.AddressDetails.Accuracy + " : Level: " + accuracytext;
		
		// + ' : ' + 'Request: ' + response.Status.request +' : Code: ' + response.Status.code; 
		
	document.getElementById('message1').innerHTML = clickposition  + '<br />' + geooutput;
	clickposition1 = clickposition;
	clickposition = clickposition + " : " + geooutput;		
		
		 //Redo Wikipedia markers
		 updateWikipedia();
		 updateWeather();	
		 updatetimezone();
	         
		// geooutput = 'Original Position: ' + response.name + " : " + 'Marker Position: Lat: ' + place.Point.coordinates[1].toFixed(4) + ' : Long: ' + place.Point.coordinates[0].toFixed(4) + " : " + 'Address: ' + place.address + ' : ' +'Country Code: ' + place.AddressDetails.Country.CountryNameCode + ' : ' + 'Accuracy: ' + place.AddressDetails.Accuracy + ' : ' + 'Status Request: ' + response.Status.request +' : Status Code: ' + response.Status.code; 
			 
				var taille;
				var decalage;
				var icone;
				var position;
				
				taille=new OpenLayers.Size(35,45);
				decalage=new OpenLayers.Pixel(-17.5, -42);
				icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_black.png', taille, decalage);
				
				gposition=new OpenLayers.LonLat(glon, glat);
	        	gposition.transform(this.map.displayProjection,this.map.baseLayer.projection); 
				gmarqueur=new OpenLayers.Marker(gposition, icone);
				coucheMarqueurs.addMarker(gmarqueur);
				
				popup = new OpenLayers.Popup("BlackMarker",
                gposition,
                new OpenLayers.Size(220,220),
                   clickposition,
				   true);
				popup.maxSize = (220,220);  
				popup.autoSize = true;  
                this.map.addPopup(popup);
	}
  }
 
 //End of Google Geocoder==================================================================================

//Uses CloudMade Reverse Geocoding========================================================================
  function updateGeocode()
  {
			request = "http://geocoding.cloudmade.com/3296cfdead6d51d783df1e8e4a85f892/geocoding/v2/find.js?&callback=getGeo&around="+clicklat.toFixed(4)+","+clicklon.toFixed(4)+"&distance=closest&object_type=address&results=1&return_location=true";
			//alert(clicklat + " : " + clicklon + " : " + request);
			
		aObj = new JSONscriptRequest(request);
		aObj.buildScriptTag();
		aObj.addScriptTag();
 }
 
   // Define the callback function
  function getGeo(response) {
  
	   if (response == null) {
     // There was a problem parsing search results
	 alert('CloudMade Reverse Geocoding: There was a problem parsing search results');
	 geooutput = "CloudMade Reverse Geocoding: No data available";
     return;
	}
	  
	  glat = response.features[0].centroid.coordinates[0];
	  glon = response.features[0].centroid.coordinates[1];

		geoDistance = calcDistance(glat, glon, clicklat, clicklon);
					
						var EW = "E"; 
							 if (glon < 0)
							{
							 EW = "W";
							 } 
							 
							 var NS = "N";
							 if (glat < 0)
							{
							 NS = "S";
							}
		
							aglat = Math.abs(glat);
							aglon = Math.abs(glon);
                      //alert(glat +" : " + glon);
					  
					  p=new OpenLayers.LonLat(glon,glat)
					ukgrid = LatLongToOSGrid(p);
					//alert(p + " : " + ukgrid);
					
					if(ukgrid.length==0) {
						ukgrid="n/a";
					}
	
	//Put together the text string
	geooutput = "Nearest Geocoding Location: Long: " + Math.round(aglon *10000)/10000 + EW + " : Lat: " + Math.round(aglat * 10000)/10000 + NS + " : UK Grid: " + ukgrid;
	
	geooutput = geooutput + " : Address: ";
	if(response.features[0].properties.synthesized_name != undefined)
	{
		geooutput = geooutput  + response.features[0].properties.synthesized_name +  ", ";
	}
	
	if(response.features[0].location.road != undefined)
	{
		geooutput = geooutput  + response.features[0].location.road +  ", ";
	}
	
	if(response.features[0].location.city != undefined)
	{
		geooutput = geooutput  + response.features[0].location.city +  ", ";
	}
	
	if(response.features[0].location.postcode != undefined)
	{
		geooutput = geooutput  + response.features[0].location.postcode +  ", ";
	}
	
	if(response.features[0].location.country != undefined)
	{
		geooutput = geooutput  + response.features[0].location.country;
	}

	geooutput = geooutput +  " : ID: " + response.features[0].id;
	geooutput = geooutput + " : Distance: " + Math.round(geoDistance *100) / 100 + " km (" + Math.round(geoDistance /1.609344 * 100) / 100 + " miles)";
	 
	 //Example CloudMade Output
	 //{"features": [{"centroid": {"type": "POINT", "coordinates": [52.48441, 13.42342]}, "bounds": [[52.48441,13.42342], [52.48441, 13.42342]], "id": 7520127, "type": "Feature", "properties": {"addr:housenumber": "10","addr:city": "Berlin", "addr:postcode": "12049", "addr:country": "DE", "synthesized_name": "10", "addr:street": "Wissmannstraße"}, "location": {"county": "Berlin", "country": "Germany", "postcode": "B249", "road": "Wissmannstraße", "city": "Berlin"}}], "found": 1, "type": "FeatureCollection", "bounds": [[52.48441, 13.42342], [52.48441, 13.42342]], "crs": {"type": "EPSG", "properties": {"code": 4326, "coordinate_order": [0, 1]}}}
	 
	   //Remove current marker if possible				
				try{
		       r = coucheMarqueurs.removeMarker(gmarqueur);
		     	}
		     catch(err){
			  	  }	
				  
				try{
			   q = this.map.removePopup(popup);
		     	}
		      catch(err){
			  	  }	
				
				var taille;
				var decalage;
				var icone;
				var position;
				
				taille=new OpenLayers.Size(35,45);
				decalage=new OpenLayers.Pixel(-17.5, -42);
				icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_black.png', taille, decalage);
				
				gposition=new OpenLayers.LonLat(glon, glat);
	        	gposition.transform(this.map.displayProjection,this.map.baseLayer.projection); 
				
				gmarqueur=new OpenLayers.Marker(gposition, icone);
				coucheMarqueurs.addMarker(gmarqueur);
				
				popup = new OpenLayers.Popup("BlackMarker",
                gposition,
                new OpenLayers.Size(220,220),
                   clickposition,
				   true);
				popup.maxSize = (220,220);  
				popup.autoSize = true;  
                this.map.addPopup(popup);
	   
	  //alert(geooutput);
	  aObj.removeScriptTag();
   }
   
   /*
	 * Use Haversine formula to calculate distance (in km) between two points specified by 
	 * latitude/longitude (in numeric degrees)
	 *
	 * from: Haversine formula - R. W. Sinnott, "Virtues of the Haversine",
	 *       Sky and Telescope, vol 68, no 2, 1984
	 *       http://www.census.gov/cgi-bin/geo/gisfaq?Q5.1
	 *
	 * example usage from form:
	 *   result.value = LatLon.distHaversine(lat1.value.parseDeg(), long1.value.parseDeg(), 
	 *                                       lat2.value.parseDeg(), long2.value.parseDeg());
	 * where lat1, long1, lat2, long2, and result are form fields
	 */
	function calcDistance(lat1, lon1, lat2, lon2) {
	  var R = 6371; // earth's mean radius in km
	  var dLat = (lat2-lat1).toRad();
	  var dLon = (lon2-lon1).toRad();
	  lat1 = lat1.toRad(), lat2 = lat2.toRad();
	
	  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
			  Math.cos(lat1) * Math.cos(lat2) * 
			  Math.sin(dLon/2) * Math.sin(dLon/2);
	  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	  var d = R * c;
	  return d;
	}
	
Number.prototype.toRad = function() {  // convert degrees to radians
  return this * Math.PI / 180;
}

//Runs from second button to reload and cancel entries
  function reloadPage()
  {
  zoomlevel = 6;
  window.location.reload();
  }		
  
   //Update map centre on click with red cross marker
function centremap()
  {
	         //Remove marker if possible
			 try{
		       r = coucheMarqueurs.removeMarker(marqueur);
		     	}
		      catch(err){
		   	  }	
			    r = coucheMarqueurs.removeMarker(marqueur);
				// projection de la carte:
				
			try{
			   q = this.map.removePopup(popup);
		     	}
		      catch(err){
			  	  }	
			
			//Exit if GPS tracking is ON
			if(trackingon == 1)
		     {
				document.getElementById('message2').innerHTML = "Centre Position: n/a";
				centreposition = "Centre Position: n/a";				
				return;
			 }
			
			this.map=Map.map;
				var mapproj= this.map.projection;
				
				var taille;
				var decalage;
				var icone;
				var position;
				centrepos=null;
				
				taille=new OpenLayers.Size(15,15);
				//decalage=new OpenLayers.Pixel(-(taille.w/2), -taille.h/2);
				decalage=new OpenLayers.Pixel(-7.5, -7.5);
				icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_cross.png', taille, decalage);
				position=new OpenLayers.LonLat(clicklon, clicklat);
				
				
				position.transform(this.map.displayProjection,this.map.baseLayer.projection);  
				zoomlevel = this.map.getZoom();
				this.map.setCenter(position, zoomlevel);
				
				marqueur=new OpenLayers.Marker(position, icone);
				coucheMarqueurs.addMarker(marqueur);	
				
				  //Form text string
		            EW = "E"; 
					 if (clicklon < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (clicklat < 0)
					{
					 NS = "S";
					}
					
					ptlat = Math.abs(clicklat);
					ptlon = Math.abs(clicklon);
					//alert("Centre2: " + centrepos + " : Lat: " + centrepos.lat + " : Long: " + centrepos.lon);
					
					p=new OpenLayers.LonLat(clicklon,clicklat)
					ukgrid = LatLongToOSGrid(p);
					//alert(p + " : " + ukgrid);
					
					if(ukgrid.length==0) {
						ukgrid="n/a";
					}
					
					document.getElementById('message2').innerHTML = "Centre Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " + ukgrid;
					centreposition = "Centre Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " + ukgrid;

updateWikipedia();
}
  
 //Update map centre on click with red cross marker
function updatecentre()
  {
	         //Remove marker if possible
			 try{
		       r = coucheMarqueurs.removeMarker(marqueur);
		     	}
		      catch(err){
		   	  }	
			    r = coucheMarqueurs.removeMarker(marqueur);
				// projection de la carte:
				
			try{
			   q = this.map.removePopup(popup);
		     	}
		      catch(err){
			  	  }	
			
			//Exit if GPS tracking is ON
			if(trackingon == 1)
		     {
				document.getElementById('message2').innerHTML = "Centre Position: n/a";
				centreposition = "Centre Position: n/a";				
				return;
			 }
			
			this.map=Map.map;
				var mapproj= this.map.projection;
				
				var taille;
				var decalage;
				var icone;
				var position;
				centrepos=null;
				
				//Initial position
				centrepos = this.map.getCenter();
				
				centrepos.transform(this.map.baseLayer.projection,this.map.displayProjection);
				
				taille=new OpenLayers.Size(15,15);
				//decalage=new OpenLayers.Pixel(-(taille.w/2), -taille.h/2);
				decalage=new OpenLayers.Pixel(-7.5, -7.5);
				icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_cross.png', taille, decalage);
				position=new OpenLayers.LonLat(centrepos.lon, centrepos.lat);
				
				position = this.map.getCenter();
				
				marqueur=new OpenLayers.Marker(position, icone);
				coucheMarqueurs.addMarker(marqueur);	
				
				  //Form text string
		            EW = "E"; 
					 if (centrepos.lon < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (centrepos.lat < 0)
					{
					 NS = "S";
					}
					
					ptlat = Math.abs(centrepos.lat);
					ptlon = Math.abs(centrepos.lon);
					//alert("Centre2: " + centrepos + " : Lat: " + centrepos.lat + " : Long: " + centrepos.lon);
					
					p=new OpenLayers.LonLat(centrepos.lon,centrepos.lat)
					ukgrid = LatLongToOSGrid(p);
					//alert(p + " : " + ukgrid);
					
					if(ukgrid.length==0) {
						ukgrid="n/a";
					}
					
					document.getElementById('message2').innerHTML = "Centre Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " + ukgrid;
					centreposition = "Centre Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " + ukgrid;
updateWikipedia();		
}

	 function updateWeather()
  {
			//Update time
             updatetimezone();
			
			this.map=Map.map;
			
			//Centre position
			weatherpos = this.map.getCenter();
			weatherpos.transform(this.map.baseLayer.projection,this.map.displayProjection);
			
	       //alert("Weather: " + weatherpos + " : Lat: " + weatherpos.lat + " : Lon: " + weatherpos.lon);
			request = 'http://api.geonames.org/findNearByWeatherJSON?callback=getWeather&lat='+weatherpos.lat+'&lng='+weatherpos.lon + "&username=SysMaps";
			aObj = new JSONscriptRequest(request);
			aObj.buildScriptTag();
			aObj.addScriptTag();
 }
 
 function updatetimezone()
 {
   		this.map=Map.map;
		timepos = this.map.getCenter();
		timepos.transform(this.map.baseLayer.projection,this.map.displayProjection);
		request2 = 'http://api.geonames.org/timezoneJSON?callback=gettime&lat='+timepos.lat+'&lng='+timepos.lon + "&username=SysMaps";
			aObj = new JSONscriptRequest(request2);
			aObj.buildScriptTag();
			aObj.addScriptTag();
 }
 
  // Define the callback function
  function gettime(jData) {
   
   if (jData == null) {
     // There was a problem parsing search results
	 alert('There was a problem parsing search results');
	 timeoutput = "Time Zone: No time data available";
     return;
	}
	
	try{
			timeoutput = "Country Code: " + jData.countryCode + " : Country: " + jData.countryName + " : Time Zone: " + jData.timezoneId + " : Local Time: " + jData.time + " : Offset to UTC: " + jData.rawOffset.toFixed(1) + " hrs (Summer: " + jData.dstOffset.toFixed(1) + " hrs , Winter " + jData.gmtOffset.toFixed(1) + " hrs)";
	 // alert(timeoutput);
				}
			catch(err){
				timeoutput = "Data not available";
			  	}
	  
	   aObj.removeScriptTag();
   }
 
 // Define the callback function
  function getWeather(jData) {
   
   if (jData == null) {
     // There was a problem parsing search results
	 alert('There was a problem parsing search results');
	 html="No METAR weather data available";
	 document.getElementById('message4').innerHTML = html;
     return;
	}
	
	  weather = jData.weatherObservation;
	  
	 if (weather != undefined)
	 {
	  
	  //Form text string
		    EW = "E"; 
					 if (weather.lng < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (weather.lat < 0)
					{
					 NS = "S";
					}
					
					ptlat = Math.abs(weatherpos.lat);
					ptlon = Math.abs(weatherpos.lon);
					
					if (weather.weatherCondition == 'undefined')
					{
					weather.weatherCondition = "Unknown"
					}
					
					if (weather.clouds == 'undefined')
					{
					weather.weatherCondition = "Unknown"
					}
	  
	  var html = '<b>' + "Weather Report: "+weather.stationName+'</b> ('+weather.ICAO+')';
	   html += '<br />'+ timeoutput;
	  html += '<br />'+"Position: "+(Math.round(ptlon * 10000) / 10000) + EW +', '+(Math.round(ptlat * 10000) / 10000) + NS +': Elevation: '+weather.elevation+'m: Date/time: '+weather.datetime;
	
	  html += '<br />'+"Conditions: "+weather.weatherCondition+', '+weather.clouds+' : Temperature: '+weather.temperature+'&deg;C : Pressure: '+weather.hectoPascAltimeter+' hPa : Humidity: '+weather.humidity+'% : Wind: '+weather.windDirection+'&deg; @ '+weather.windSpeed+' knots';
		
	 }
	 else
	 {
	html = "No Weather data available";	 
	 }
	 
	 //alert(html);
	 document.getElementById('message4').innerHTML = html;
	 aObj.removeScriptTag();
 }
 
//Wikipedia entries
  function updateWikipedia()
  {
			this.map=Map.map;
			
			//Centre position
		    wikipos = this.map.getCenter();;
			wikipos.transform(this.map.baseLayer.projection,this.map.displayProjection);
			
			//alert("Wiki: " + wikipos + " : " + wikipos.lat + " : " + wikipos.lon);
			request = 'http://api.geonames.org/findNearbyWikipediaJSON?callback=getWikipediaEntries&username=SysMaps&password=SysMaps&radius=20&maxRows=20&lat='+wikipos.lat+'&lng='+wikipos.lon;
			aObj = new JSONscriptRequest(request);
			aObj.buildScriptTag();
			aObj.addScriptTag();
 } 
 // Define the callback function
  function getWikipediaEntries(jData) {
  
   //Get rid of current icons
    clearWikipedia();
	wikiMarker = [];
	
    if (typeof jData.geonames == 'undefined')
            var html = '<b>' +'No nearby Wikipedia entries or service unavailable'+'<b>';
        else {
			
			var geonames = jData.geonames;
			//alert(geonames.length);
			
            if (geonames.length == 0) {
                alert('No Wikipedia entries');
                return;
            }
			var html = '<b>' + "Wikipedia Entries: " +'</b>' + geonames.length;
		   
			for (i=0;i< geonames.length;i++) {
                
			 var geoname = geonames[i];
			 
			//Setup wiki icon 
		    var taille;
		    var decalage;
		    var icone;
		    var position;
			
			// taille=new OpenLayers.Size(25,25);
		    // decalage=new OpenLayers.Pixel(-12, -12);
		    // icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/wiktionary.png', taille, decalage);
			 
			//Added 29-Nov-2009 to provide numbered markers
			var taille = new OpenLayers.Size(17, 19);
			var decalage = new OpenLayers.Pixel(-1, -19);
			iconno = i+1;
			iconhttp = "http://www.sysmaps.co.uk/images/darkblue" + iconno +".png"
			//alert(iconhttp);
			icone=new OpenLayers.Icon(iconhttp, taille, decalage);
			 
			 position=new OpenLayers.LonLat(geoname.lng, geoname.lat);
			 position.transform(this.map.displayProjection,this.map.baseLayer.projection);
		     wikiMarker[i]=new OpenLayers.Marker(position, icone);
		     coucheMarqueurs.addMarker(wikiMarker[i]);
			 
			 //alert(i + " : " + geonames.length + " : " + geoname.summary+ " : " + position);
			  
			   EW1 = "E"; 
					 if (geoname.lng < 0)
					{
					 EW1 = "W";
					 } 
					 
					 NS1 = "N";
					 if (geoname.lat < 0)
					{
					 NS1 = "S";
					}
					
					ptlat1 = Math.abs(geoname.lat);
					ptlon1 = Math.abs(geoname.lng);
	  
	  //Form text string
	  var item =i +1; 
	  html += '<br />'+'<b>'+ item +": " +geoname.title +'</b>'+ " : " + geoname.summary;
	  html += '<br />'+"Position: "+(Math.round(ptlon1 * 10000) / 10000) + EW1 +', '+(Math.round(ptlat1 * 10000) / 10000) + NS1 +' : Distance: '+Math.round(geoname.distance  * 100) / 100 + " km (" + Math.round(geoname.distance / 1.609344 * 100) / 100 + " miles) :  URL:"+' <a href="http://'+geoname.wikipediaUrl+'" target="_blank">View Wikipedia</a>';
	  
            }
        }
        document.getElementById('message5').innerHTML = html;
		aObj.removeScriptTag();
      }
	  
	function clearWikipedia()
	{
	html = '';
	document.getElementById('message5').innerHTML = '<b>'+"Wikipedia entries:"+'<b>'+' n/a';
	
	 for (i=0;i< 20;i++) {
				try{
				 r = coucheMarqueurs.removeMarker(wikiMarker[i]);
				 r = coucheMarqueurs.removeMarker(wikiMarker);
				//alert(i);
				}
				catch(err){
				}	
				//r = coucheMarqueurs.removeMarker(wikiMarker);
			}		
	}  

 //load sysmaps home as popup
	function sysmapshome() {
    var load = window.open('http://www.sysmaps.co.uk','','scrollbars=yes,menubar=yes,height=700,width=800,resizable=no,toolbar=yes,location=yes,status=yes');
   }
   
   function loadhelp() {
var load = window.open('http://www.sysmaps.co.uk/sysmaps_bkg_help.html','','scrollbars=yes,menubar=no,height=700,width=800,resizable=yes,toolbar=no,location=no,status=no');
}

function loadinfo() {
var load = window.open('http://www.sysmaps.co.uk/sysmaps_info.html','','scrollbars=yes,menubar=no,height=700,width=800,resizable=yes,toolbar=no,location=no,status=no');
}

function loadgeohack() {
var load = window.open("http://toolserver.org/~geohack/geohack.php?params=" + LatDegrees + "_" + LatMinutes + "_" + LatDecMinutes + "_" + NS + "_" + LonDegrees + "_" + LonMinutes + "_" + LonDecMinutes + "_" + EW,'','scrollbars=yes,menubar=yes,height=700,width=1000,resizable=yes,toolbar=yes,location=yes,status=yes');
}

function loadosmkey() {
var load = window.open('http://www.sysmaps.co.uk/osmkey.html','','scrollbars=yes,menubar=no,height=600,width=500,resizable=yes,toolbar=no,location=no,status=no');
}

 //Utility to send note of positions to email address
  function sendposition()
    {
	
	// centrepos = this.map.getCenter();
   // centrepos.transform(this.map.baseLayer.projection,this.map.displayProjection);
	
	  emailalert = "on";
	  
	  //Get up to date permalink positions
	  openpermalink();
	 
	 currdate = Date();
	 
	 cmclickpermalink = "http://www.sysmaps.co.uk/sysmaps_bkg.html?!" + ptlat + "~" + ptlon;
	 cmcentrepermalink = "http://www.sysmaps.co.uk/sysmaps_bkg.html?!" + centrepos.lat.toFixed(4) + "~" + centrepos.lon.toFixed(4);
	 
	 permalink = "Current Positions from Systematic Maps at www.sysmaps.com on " + currdate + ": " + "^" + "^" + "(1) Click Marker Permalink: " + cmclickpermalink + "^" + "Centre Permalink: " + cmcentrepermalink;
	 
	  emailalert = "off";
		
		 transmessage1 = permalink;

       //alert("Msg1: " + transmessage1);
	    transmessage1 = transmessage1 + "^" + "^" + "(2) White " + clickposition1;
		transmessage1 = transmessage1 + "^" + "^" + "(3) " + geooutput;  	  
	    transmessage1 = transmessage1 + "^" + "^" + "(4) Red Cross " + centreposition;
	    transmessage1 = transmessage1 + "^" + "^" + "(5) " + "Blue " + gpsposition + "^" + "^" + "Systematic Maps : www.sysmaps.com";
		//alert("Msg2: " + transmessage1);
		transmessage = "http://www.sysmaps.co.uk/email.html? +" + transmessage1;
		//alert("Msg1: " + transmessage);
		//alert(transmessage);
		var load = window.open(transmessage,'', 'scrollbars=yes,menubar=no,height=730,width=1000,resizable=yes,toolbar=no,location=no,status=no');
		
  }
  
    //Option (1) - Geocoding---------------------------------------------------------
   function findplace()
   {
	//zoomlevel = this.map.getZoom();
	zoomlevel = 11;
    var taille;
    var decalage;
    var icone;
    var position=new OpenLayers.LonLat(clicklon, clicklat);
   
    var geocoder = new CM.Geocoder('e856ccfb0d5155d1b33b72a6835ae579');
		
			try{
			myMap.removeOverlay(gpsmarqueur);
				}
			catch(err){
			  	}
		
			try{
			r = coucheMarqueurs.removeMarker(gazmarqueur);
				}
			catch(err){
			  	}
				
				try{
			r = coucheMarqueurs.removeMarker(cmarqueur);
				}
			catch(err){
			  	}	
				
			try{
	      r = coucheMarqueurs.removeMarker(gmarqueur);
	    	}
	      catch(err){
	  	  }		
				
	//Input variable on form is read into a variable
    query = document.getElementById("lookup");
	placelookup = query.value;
	
	window.status = "Looking for: " + placelookup;
	
	//Looking for lat/lon===================================
	
	mid=0;
	
	 function delineatelat(str)
	{
	mid = str.lastIndexOf(":");
	return(str.substring(0, mid));
	}
	
	function delineatelong(str)
	{
	mid = str.lastIndexOf(":");
		if(mid>0)
		{
		return(str.substring(mid+1,str.length));
		}
	}
    
	    try{
		clicklat = delineatelat(placelookup);
		clicklon = delineatelong(placelookup);
		}
		  catch(err){
			}	
	
	//alert("Position1: " + placelookup + " : Mid: " + mid + " : " + clicklat + " : " + clicklon);
		if(mid != -1)
	{
			centrepos=null;
			ptlat = Math.abs(clicklat);
			ptlon = Math.abs(clicklon);
				
				position=new OpenLayers.LonLat(clicklon, clicklat);
				//alert("PositionA: " +  position);
				
				position.transform(this.map.displayProjection,this.map.baseLayer.projection);  
				
				//Centre map on position
	            this.map.setCenter(position, zoomlevel);
				 
				//Gaz position
				taille=new OpenLayers.Size(35,45);
				decalage=new OpenLayers.Pixel(-17.5, -45);
				icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_green.png', taille, decalage);
				
				gazmarqueur=new OpenLayers.Marker(position, icone);
				coucheMarqueurs.addMarker(gazmarqueur);	
   }
   else
   //Alternatively try to find address using Coludmade geocoder=========
   {
	
    //get response
	geocoder.getLocations(query.value, function(response) {

     this.map=Map.map;
	
	 if(response.bounds == null || response.bounds == undefined)
	{
	alert(placelookup + ": position or place not found!. Please enter a more exact address such as 'Stuttgart, Germany' or a latitude/longitude position in the form '48.8069:10.1227' with as colon in the middle (south or west are entered as negative e.g. -10.543).");
	
	}
	else{	
	
	// ... process the response and get the map boundaries
        sw = new CM.LatLng(response.bounds[0][0], response.bounds[0][1]),
        ne = new CM.LatLng(response.bounds[1][0], response.bounds[1][1]);
		
	//Update window status
	window.status = "Looking for: " + placelookup + " found at " + sw;	
   
   //Get array of responses
    for (var i = 0; i < response.features.length; i++) {
        var coords = response.features[i].centroid.coordinates;
		centrepos=null;
				
				position=new OpenLayers.LonLat(coords[1], coords[0]);
				//alert("Position1: " +  position);
				ptlat = Math.abs(coords[0]);
				ptlon = Math.abs(coords[1]);
				clicklat = Math.abs(coords[0]);
				clicklon = Math.abs(coords[1]);
			  
				position.transform(this.map.displayProjection,this.map.baseLayer.projection);  
				//alert("Position2: " +  position + " : " + zoomlevel);
				
				//Centre map on position
	            this.map.setCenter(position, zoomlevel);
				
				//Gaz position
				taille=new OpenLayers.Size(35,45);
				decalage=new OpenLayers.Pixel(-17.5, -42);
				icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_green.png', taille, decalage);
				
				gazmarqueur=new OpenLayers.Marker(position, icone);
				coucheMarqueurs.addMarker(gazmarqueur);	
				
				}
		}
		});
		}
		//End of geocoder====================================
				
				//Form text string
		            EW = "E"; 
					 if (clicklon < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (clicklat < 0)
					{
					 NS = "S";
					}
					
					properplace = toTitleCase(placelookup);
					
					p=new OpenLayers.LonLat(clicklon,clicklat)
					ukgrid = LatLongToOSGrid(p);
					//alert(p + " : " + ukgrid + " : " + ukgrid.length);
					
					if(ukgrid.length==0) {
						ukgrid="n/a";
					}
					
					if(String(ukgrid).substring(0,1)=="0")
					{
						ukgrid="n/a";
					}
					
					function isText( text ) { var regex = /^[a-zA-Z][a-zA-Z-.]*$/; return regex.test( text ); }
					if(isText(String(ukgrid).substring(0,1)) !=true)
					{
						ukgrid="n/a";
					}
					
					document.getElementById('message1').innerHTML = properplace+ " : Place found at: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " + ukgrid;
					clickposition = properplace + " : Place found at: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " + ukgrid;
	
		//Write data for bottom of page
		try{
		document.getElementById('lat').innerHTML 		= "n/a";
		document.getElementById('lng').innerHTML 	    = "n/a";
		document.getElementById('grd').innerHTML 		= "n/a";
		document.getElementById('alt').innerHTML 		= "n/a";
		document.getElementById('speed').innerHTML 		= "n/a";
		document.getElementById('head').innerHTML 		= "n/a";
		document.getElementById('ts').innerHTML 		= "n/a";
		document.getElementById('satCount').innerHTML 	= "n/a";
		}
		  catch(err){
			}	
		 
		//Update Wikipedia
		updateWikipedia();
		
		//Update centre marker
		updatecentre()
		
		//Update weather 
		updateWeather();
		
		//Reacting to different events - display the location on click
		   	function displayMessage(msg) {
			document.getElementById('message').innerHTML = msg;
			}
}

 function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
  
  //=======================================================================================================
  
  //Click Control--------------------------------------------------------------------
		
			try{
	
	//Control for click - inserts white marker
	 ClickControl= OpenLayers.Class( OpenLayers.Control, {
            /**
             * Constructor ClickControl
             */
            initialize: function(options) {
                OpenLayers.Control.prototype.initialize.apply(this,arguments);
                this.handlerOptions= {
                    'single': true,
                    'double': true,
                    'pixelTolerance': 0,
                    'stopSingle': false,
                    'stopDouble': false
                };
                this.handler= new OpenLayers.Handler.Click(
                    this, {'click': this.trigger}, this.handlerOptions);
            },

            /**
             * APIMethod: trigger
             */
            trigger: function(e) {
				var lonlat= this.map.getLonLatFromViewPortPx(e.xy).transform(this.map.displayProjection, this.map.baseLayer.projection);
				
				//Remove current marker if possible				
				try{
		       r = coucheMarqueurs.removeMarker(cmarqueur);
			   q = this.map.removePopup(popup);
		     	}
		      catch(err){
			  	  }	
				
				// projection de la carte:
				var mapproj= this.map.projection;
				
				//couche des marqueurs
				//coucheMarqueurs=new OpenLayers.Layer.Markers("Markers");
				var taille;
				var decalage;
				var icone;
				var position;
				
				//Initial position
				taille=new OpenLayers.Size(35,45);
				decalage=new OpenLayers.Pixel(-17.5, -42);
				icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_white.png', taille, decalage);
				position=new OpenLayers.LonLat(lonlat.lon, lonlat.lat);
				position.transform(this.map.displayProjection, this.map.baseLayer.projection);
				cmarqueur=new OpenLayers.Marker(position, icone);
				coucheMarqueurs.addMarker(cmarqueur);
				
				// The web service call-----------------------------------------
					//alert(lonlat.lat + " : " + lonlat.lon);
					 request = "http://api.geonames.org/astergdemJSON?lat="+lonlat.lat+"&lng="+lonlat.lon+"&callback=getLocation" + "&username=SysMaps";
					 aObj = new JSONscriptRequest(request);
					 aObj.buildScriptTag();
					 aObj.addScriptTag(); 
				    //End of web service call-------------------------------------
					
					clicklat = lonlat.lat;
				    clicklon = lonlat.lon;	
				
				  //Form text string
		            EW = "E"; 
					 if (lonlat.lon < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (lonlat.lat < 0)
					{
					 NS = "S";
					}
					
					//Find closest address
					updateGeocode;
					
					ptlat = Math.abs(lonlat.lat);
					ptlon = Math.abs(lonlat.lon);
					
					p=new OpenLayers.LonLat(lonlat.lon,lonlat.lat)
					ukgrid = LatLongToOSGrid(p);
					//alert(p + " : " + ukgrid);
					
					if(ukgrid.length==0) {
						ukgrid="n/a";
					}
					
					document.getElementById('message1').innerHTML = "Click Marker Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " + ukgrid + " : Elevation: " +  alt + "m" ; 
					
				LatDegrees = Math.floor(ptlat);
				LatMinutes = Math.floor((ptlat - Math.floor(ptlat)) * 60);
				LatDecMinutes = Math.round((((ptlat - Math.floor(ptlat)) * 60) - LatMinutes) * 60 * 100)/100;
				
				LonDegrees = Math.floor(ptlon);
				LonMinutes = Math.floor((ptlon- Math.floor(ptlon))*60);
				LonDecMinutes = Math.round((((ptlon - Math.floor(ptlon)) * 60) - LonMinutes) * 60 * 100)/100;
				
				Geohack = "http://toolserver.org/~geohack/geohack.php?params=" + LatDegrees + "_" + LatMinutes + "_" + LatDecMinutes + "_" + NS + "_" + LonDegrees + "_" + LonMinutes + "_" + LonDecMinutes + "_" + EW;
				
				//http://toolserver.org/~geohack/geohack.php?params=55_23_59_N_1_30_0_E
					
					clickposition = "Map Clicked at: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " + ukgrid + " : Elevation: " +  alt + "m" + " : " + "<a href = " + Geohack + "> Geohack Link</a>"; 
					
				//alert("Vous avez cliqué près de " + lonlat.lon + "N, " + lonlat.lat + " E");
				alerttext = "Map Clicked at: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + geooutput;
				//alert(alerttext);
				
				//Update centre marker
				updatecentre();	    

				popup = new OpenLayers.Popup("WhiteMarker",
                   position,
                   new OpenLayers.Size(220,150),
                   clickposition,
				   true);
				popup.maxSize = (220,150);  
				popup.autoSize = true;  
               // this.map.addPopup(popup);
            }
        });
		
}
 catch(err){
	  }		
	  
 // Define the callback function
  function getLocation(jData) {
   if (jData == null) {
     // There was a problem parsing search results
	 alert('There was a problem parsing search results');
     return;
   }
  
   lastalt = alt;
   alt = jData.astergdem;
  //alert(alt + " : " + lastalt);
   aObj.removeScriptTag();
 }
 
//function zoommap(long,lat,zoomlevel) {myMap.getMap().setCenterAtLonLat(long,lat,zoomlevel);}
function zoommap(long,lat,zoomlevel) {myMap.setCenterAtLonLat(long,lat,zoomlevel);}
		
		//End of Click Control--------------------------------------------------------------------
		
	//=====================================================================================  
		
         function triggermarker(lonlat) {
				
				//Remove current marker if possible				
				try{
		       r = coucheMarqueurs.removeMarker(cmarqueur);
			   q = this.map.removePopup(popup);
		     	}
		      catch(err){
			  	  }	
				
				// projection de la carte:
				var mapproj= this.map.projection;
				
				//couche des marqueurs
				var taille;
				var decalage;
				var icone;
				var position;
				
				//Initial position
				taille=new OpenLayers.Size(35,45);
				decalage=new OpenLayers.Pixel(-17.5, -42);
				icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_white.png', taille, decalage);
				position=new OpenLayers.LonLat(lonlat.lon, lonlat.lat);
				position.transform(this.map.displayProjection, this.map.baseLayer.projection);
				cmarqueur=new OpenLayers.Marker(position, icone);
				coucheMarqueurs.addMarker(cmarqueur);
				
				clicklat = lonlat.lat;
				clicklon = lonlat.lon;	
				
				// The web service call-----------------------------------------
					//alert(lonlat.lat + " : " + lonlat.lon);
					 request = "http://api.geonames.org/astergdemJSON?lat="+lonlat.lat+"&lng="+lonlat.lon+"&callback=getLocation" + "&username=SysMaps";
					 aObj = new JSONscriptRequest(request);
					 aObj.buildScriptTag();
					 aObj.addScriptTag(); 
				    //End of web service call-------------------------------------
				
				  //Form text string
		            EW = "E"; 
					 if (lonlat.lon < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (lonlat.lat < 0)
					{
					 NS = "S";
					}
					
					//Save positions for Geocoder
				   clicklat = lonlat.lat;
				   clicklon = lonlat.lon;	
				  //alert(clicklat + " : " + clicklon);
					
					//Find closest address
					//updateGeocode();
					
					//Add in Google geocoding 
			        geocoder = new GClientGeocoder();	
		            getAddress2(clicklat, clicklon);		
				    // alert(geooutput);
					
					ptlat = Math.abs(lonlat.lat);
					ptlon = Math.abs(lonlat.lon);
					
					p=new OpenLayers.LonLat(lonlat.lon,lonlat.lat)
					ukgrid = LatLongToOSGrid(p);
					//alert(p + " : " + ukgrid);
					
					if(ukgrid.length==0) {
						ukgrid="n/a";
					}
					
					document.getElementById('message1').innerHTML = "Map Clicked at: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " +  ukgrid + " : Elevation: " +  alt + "m"; 
					
				LatDegrees = Math.floor(ptlat);
				LatMinutes = Math.floor((ptlat - Math.floor(ptlat)) * 60);
				LatDecMinutes = Math.round((((ptlat - Math.floor(ptlat)) * 60) - LatMinutes) * 60 * 100)/100;
				
				LonDegrees = Math.floor(ptlon);
				LonMinutes = Math.floor((ptlon- Math.floor(ptlon))*60);
				LonDecMinutes = Math.round((((ptlon - Math.floor(ptlon)) * 60) - LonMinutes) * 60 * 100)/100;
				
				Geohack = "http://toolserver.org/~geohack/geohack.php?params=" + LatDegrees + "_" + LatMinutes + "_" + LatDecMinutes + "_" + NS + "_" + LonDegrees + "_" + LonMinutes + "_" + LonDecMinutes + "_" + EW;
				
				//http://toolserver.org/~geohack/geohack.php?params=55_23_59_N_1_30_0_E
					
					clickposition = "Map Clicked at: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : UK Grid: " +  ukgrid + " : Elevation: " +  alt + "m" + " : " + "<a href = " + Geohack + "> Geohack Link</a>"; 
					
				//alert("Vous avez cliqué près de " + lonlat.lon + "N, " + lonlat.lat + " E");
				alerttext = "Map Clicked at: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS;
				//alert(alerttext);
				
				//Update centre marker
				updatecentre();	 
				
				popup = new OpenLayers.Popup("WhiteMarker",
                   position,
                   new OpenLayers.Size(220,150),
                   clickposition,
				   true);
				popup.maxSize = (220,150);  
				popup.autoSize = true;  
               // this.map.addPopup(popup);   
            }
		
	  
   //=====================================================================================

	 //GPS Button - Live Franson GPSGate feed-----------------------------------------------------------------------------
	function init()
    {
	  if (document.getElementById('gpsbutton').value == "Stop GPS") {
		  clearTimeout(t);
		  stopTimer()
		  return
		  }
	 document.getElementById('gpsbutton').value = "Stop GPS";
	  
	   //Set default values for the position 
		gpsLat = lat1; 
		gpsLng = long1;
			
		galt = 0;
		gspeed = 0;
		ghead= 0;
		gtime = 0;
		gsat = 0;
		
		trackingon = 1;
		var trackinginterval = 2000;
		
		//window.alert = window.org_alert;  //Turn on alerts temporarily
				
	    // Check for GpsGate
        if (typeof(GpsGate) == 'undefined' || typeof(GpsGate.Client) == 'undefined' )
        {
		
		alert('Franson GpsGate is not installed or not started - the map will load at a default position.  See www.franson.com or www.gpsgate.com for more details of how to download and install the application.');
		
		//window.alert = function(){return null;}; // disable alerts since Chrome and Firefox do not support SVG and SML	
            //return;
		
		//NO GPS FOUND
		//----------------------------------------------------------------------------------------------------------------	
		
		//Default zoom level
		//var zoomlevel = 13;
		zoomlevel = this.map.getZoom;
		
		zoommap(gpsLng,gpsLat,zoomlevel);
		
		//Update centre position
	     updatecentre();
		 
		 //Get nearest weather and Wikipedia
		 clearWikipedia();
		 updateWeather();
		 
		 	try{
	  r = coucheMarqueurs.removeMarker(gmarqueur);
		}
	   catch(err){
			   }
			   
		try{
			myMap.removeOverlay(gpsmarqueur);
				}
			catch(err){
			  	}	   
		
			//Write data for bottom of page
			document.getElementById('lat').innerHTML 		= "n/a";
			document.getElementById('lng').innerHTML 	    = "n/a";
			document.getElementById('grd').innerHTML 		= "n/a";
			document.getElementById('alt').innerHTML 		= "n/a";
			document.getElementById('speed').innerHTML 		= "n/a";
			document.getElementById('head').innerHTML 		= "n/a";
			document.getElementById('ts').innerHTML 		= "n/a";
			document.getElementById('satCount').innerHTML 	= "n/a"; 
          
		//Exit function since GPS not running
		return
			
		//----------------------------------------------------------------------------------------------------------------
		//VALID GPS FOUND - BUT NOT NECESSARILY A POSITION
			
        }
		else
	  		
	    window.alert = function(){return null;}; // disable alerts since Chrome and firefox do not support SVG and SML
		
		 //Get nearest weather and Wikipedia
		 clearWikipedia();
		 updateWeather();
		
        // Franson GPSGate data polling function to get current location
        function getGpsData()
        {
			zoomlevel = this.map.getZoom;
			
			GpsGate.Client.getGpsInfo(function(gps)
            {
                if (gps.status.valid)
                {
					printGpsInfo(gps);
				
					//Current values from valid gps unit
					gpsLat = gps.trackPoint.position.latitude;
                    gpsLng = gps.trackPoint.position.longitude;
					
					position = new OpenLayers.LonLat(gpsLng, gpsLat);
					pos = position;
					
					//alert("pos: " + pos);
					position.transform(displayProj, baselayerProj);
					//alert("position: " + pos);
                    
					galt = gps.trackPoint.position.altitude;
					gspeed = roundToNDec((gps.trackPoint.velocity.groundSpeed*3.6), 2);
			        ghead= gps.trackPoint.velocity.heading;
			        gtime = gps.trackPoint.utc.toLocaleString();
			        gsat = getFixedSatellites(gps.satellites.items);
					getSpeedKmH = roundToNDec((gps.trackPoint.velocity.groundSpeed*3.6), 2);
					
					//Save data for the block of answers at the bottom of the map
					document.getElementById('lat').innerHTML 		= Math.round(gps.trackPoint.position.latitude *10000)/10000;
					document.getElementById('lng').innerHTML 		= Math.round(gps.trackPoint.position.longitude *10000)/10000;
					document.getElementById('grd').innerHTML 		= pos;
					document.getElementById('alt').innerHTML 		= gps.trackPoint.position.altitude;
					document.getElementById('speed').innerHTML 		= getSpeedKmH;
					document.getElementById('head').innerHTML 		= gps.trackPoint.velocity.heading;
					document.getElementById('ts').innerHTML 		= gps.trackPoint.utc.toLocaleString();
					document.getElementById('satCount').innerHTML 	= getFixedSatellites(gps.satellites.items);		

		         //Remove marker if possible
			 try{
		       r = coucheMarqueurs.removeMarker(gpsmarqueur);
		     	}
		      catch(err){
		   	  }	
			  
		var taille;
		var decalage;
		var icone;
		var position;
		
		//Initial position
		taille=new OpenLayers.Size(35,45);
		decalage=new OpenLayers.Pixel(-17.5, -42);
		icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_blue.png', taille, decalage);
		position=new OpenLayers.LonLat(gpsLng, gpsLat);
		position.transform(displayProj, baselayerProj);
		//alert("Position2: " + position);
		gpsmarqueur=new OpenLayers.Marker(position, icone);
		coucheMarqueurs.addMarker(gpsmarqueur);
	
       //Form text string
		            EW = "E"; 
					 if (gpsLng < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (gpsLat < 0)
					{
					 NS = "S";
					}
					

					ptlat = Math.abs(gpsLat);
					ptlon = Math.abs(gpsLng);
					
				gpsposition = "Current GPS Position: " + "Latitude: " + gpsLat + " Longitude: " + gpsLng + " : Position: " + pos + " : Elevation: " + galt + " m : Speed: " + gspeed + " km/h : Heading: " + ghead + " degrees : UTC: " + gtime + " : Satellites: " + gsat;

	//Centre on GPS position
	this.map=Map.map;
	c = this.map.setCenter(position, zoomlevel);
	
	  //Start of label=====================================
	  //Form text string
		            EW = "E"; 
					 if (gpsLng < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (gpsLat < 0)
					{
					 NS = "S";
					}
					
					ptlat = Math.abs(gpsLat);
					ptlon = Math.abs(gpsLng);
					
				document.getElementById('message1').innerHTML = "Current GPS Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : Elevation: " + galt + " m : Speed: " + gspeed + " km/h : Heading: " + ghead + " degrees : UTC: " + gtime + " : Satellites: " + gsat;
				clickposition = "Current GPS Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100 + " : Elevation: " + galt + " m : Speed: " + gspeed + " km/h : Heading: " + ghead + " degrees : UTC: " + gtime + " : Satellites: " + gsat;
				
				//End of label=====================================
	
	//Update centre position
	//updatecentre();
					
				//Set GPS time
				t = setTimeout(getGpsData, trackinginterval); // call again in 2s
				}
            });
        }

        // start polling (2s interval)
        getGpsData();
    }

      //Function to print current data at the bottom
	  function printGpsInfo(gps)
		{
			var getSpeedKmH = roundToNDec((gps.trackPoint.velocity.groundSpeed*3.6), 2);
			
			document.getElementById('lat').innerHTML 		= Math.round(gps.trackPoint.position.latitude *10000)/10000;
			document.getElementById('lng').innerHTML 		= Math.round(gps.trackPoint.position.longitude *10000)/10000;
			document.getElementById('grd').innerHTML 		= pos;
			document.getElementById('alt').innerHTML 		= gps.trackPoint.position.altitude;
			document.getElementById('speed').innerHTML 		= getSpeedKmH;
			document.getElementById('head').innerHTML 		= gps.trackPoint.velocity.heading;
			document.getElementById('ts').innerHTML 		= gps.trackPoint.utc.toLocaleString();
			document.getElementById('satCount').innerHTML 	= getFixedSatellites(gps.satellites.items);
		}
		
		function roundToNDec(value, numDecimals)
		{		
			var scale = Math.pow(10, numDecimals);
			return Math.round(value * scale) / scale;
		}
		
		function getFixedSatellites(satellites)
		{
			var fixedSat = 0;
			
			for(var i = 0; i < satellites.length; i++)
			{	
				if(satellites[i].usedForFix)
					fixedSat++;
			}
			
			return fixedSat;
		}	

  //Stop GPS Buttom
  function stopTimer() {
		clearTimeout(t);
		trackingon = 0;
		document.getElementById('gpsbutton').value = "Start GPS";
		
		
		   //Remove marker if possible
			 try{
		       r = coucheMarqueurs.removeMarker(gpsmarqueur);
			   c = coucheMarqueurs.removeMarker(cmarqueur);
		     	}
		      catch(err){
		   	  }	
			  
			//Get nearest weather and Wikipedia
		   updateWikipedia();
		   updateWeather();
			
			gpsposition = "Current GPS Position: n/a";
			  
			  	//Write data for bottom of page
			document.getElementById('lat').innerHTML 		= "n/a";
			document.getElementById('lng').innerHTML 	    = "n/a";
			document.getElementById('grd').innerHTML 		= "n/a";
			document.getElementById('alt').innerHTML 		= "n/a";
			document.getElementById('speed').innerHTML 		= "n/a";
			document.getElementById('head').innerHTML 		= "n/a";
			document.getElementById('ts').innerHTML 		= "n/a";
			document.getElementById('satCount').innerHTML 	= "n/a"; 
			
		//marqueurs - projection de la carte:
		var mapproj= this.map.projection;
		
		updatecentre();
		
		//couche des marqueurs
		var taille;
		var decalage;
		var icone;
		var position;
		
		//Set map at centre position
			centrepos = this.map.getCenter();
			centrepos.transform(this.map.displayProjection, this.map.baseLayer.projection);
		
		//Initial position with red marker
		taille=new OpenLayers.Size(35,45);
		decalage=new OpenLayers.Pixel(-17.5, -42);
		icone=new OpenLayers.Icon('http://www.sysmaps.co.uk/images/marker_red.png', taille, decalage);
		position=new OpenLayers.LonLat(centrepos.lon, centrepos.lat);
		position = this.map.getCenter();
		//centrepos.transform(this.map.displayProjection, this.map.baseLayer.projection);
		cmarqueur=new OpenLayers.Marker(position, icone);
		coucheMarqueurs.addMarker(cmarqueur);
		
		centrepos = this.map.getCenter();
		centrepos.transform(this.map.baseLayer.projection,this.map.displayProjection);
		
		//Form text string
		            EW = "E"; 
					 if (gpsLng < 0)
					{
					 EW = "W";
					 } 
					 
					 NS = "N";
					 if (gpsLat < 0)
					{
					 NS = "S";
					}
					
					ptlat = Math.abs(centrepos.lat);
					ptlon = Math.abs(centrepos.lon);
		
				document.getElementById('message1').innerHTML = "Stopped GPS Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100;
				clickposition = "Stopped GPS Position: " + "Long: " + Math.round(ptlon *10000)/10000 + EW + " : Lat: " + Math.round(ptlat * 10000)/10000 + NS + " : Grid Position: East " + Math.round(position.lon *100)/100 + " : North " + Math.round(position.lat *100)/100;
	}
	
 function openpermalink()
    {
	
		 //Set up the centre position text string
    // centrepos = myMap.getMap().getCenter();
	// centrepos.transform(mapproj, OpenLayers.Projection.CRS84); 
	centreptlat = Math.round(centrepos.lat * 10000) / 10000;
 	centreptlon = Math.round(centrepos.lon * 10000) / 10000;
	centreptlat = centreptlat.toFixed(4);
	centreptlon = centreptlon.toFixed(4);
					
	centrepermalinkstr = "http://www.sysmaps.co.uk/sysmaps_os.html?!" + centreptlat + "~" + centreptlon;			
					
					ptlat = Math.round(clicklat * 10000) / 10000;
					ptlon = Math.round(clicklon * 10000) / 10000;
		
	permalinkstr = "http://www.sysmaps.co.uk/sysmaps_os.html?!" + ptlat + "~" + ptlon;
	
		 //permalinktext = "The link is based on the central cross marker - move the map to the required position. \n \nThe permalink should be copied to Windows in Internet Explorer.  If you need to copy the link manually, select the link text and copy it using Control + C.  The link will also appear in the data log below";
		 
	if (emailalert=="off")
	{
		 permalinktext = "The permalink is based on the white click marker - move the mouse to the required position and click to create a new point. The centre link is based on the red cross centre marker. \n \nThe click marker permalink should be copied to Windows in Internet Explorer.  In other browsers, you will need to copy the click or centre link manually.  Select the link text and copy it using Control + C.";
		 permalinktext2 ="The link will also appear in the data log below and you can email the links to this map and also Cloudmade and OpenstreetMap pages from the next screen.";
		
	 //transmessage1 =  "Current Positions from Systematic Maps at www.sysmaps.com are: " + "Click Marker Permalink: " + permalinkstr + " :  Centre Permalink: " + centrepermalinkstr;
	 
	  cmclickpermalink = "http://www.sysmaps.co.uk/sysmaps_cm.html?!" + ptlat + "~" + ptlon;
	  cmcentrepermalink = "http://www.sysmaps.co.uk/sysmaps_cm.html?!" + centreptlat + "~" + centreptlon;
	  
	  smclickpermalink= "http://www.sysmaps.co.uk/sysmaps_bkg.html?!" + ptlat + "~" + ptlon
	  smcentrepermalink= "http://www.sysmaps.co.uk/sysmaps_bkg.html?!" + centreptlat + "~" + centreptlon;
	  
	  ggclickpermalink= "http://www.sysmaps.co.uk/sysmaps_google.html?!" + ptlat + "~" + ptlon
	  ggcentrepermalink= "http://www.sysmaps.co.uk/sysmaps_google.html?!" + centreptlat + "~" + centreptlon;
	  
	  mmclickpermalink= "http://www.sysmaps.co.uk/sysmaps_bing.html?!" + ptlat + "~" + ptlon
	  mmcentrepermalink= "http://www.sysmaps.co.uk/sysmaps_bing.html?!" + centreptlat + "~" + centreptlon;
	  
	  alert(permalinktext + "\n" + "\n" + permalinktext2 + "\n" + "\n" + " Click Marker Permalink: " + smclickpermalink + "\n" + "\n" + " Centre Permalink: " + smcentrepermalink);
	  
	  currdate = Date();
	  
	  transmessage1 =  "Current Positions from Systematic Maps at www.sysmaps.com on " + currdate + ".  Click on the links to load individual maps: " + "^" + "^" + "(1) UK Ordnance Survey" + "^" +"Click Marker Permalink: " + permalinkstr + "^" + "Centre Permalink: " + centrepermalinkstr  + "^" + "^" + "(2) Cloudmade" + "^" +"Click Marker Permalink: " + cmclickpermalink + "^" + "Centre Permalink: " + cmcentrepermalink + "^" + "^" + "(3) OpenStreetMap" + "^" +"Click Marker Permalink: " + smclickpermalink + "^" + "Centre Permalink: " + smcentrepermalink  + "^" + "^" + "(4) Google / Streetview" + "^" + "Click Marker Permalink: " + ggclickpermalink + "^" + "Centre Permalink: " + ggcentrepermalink +  "^" + "^"+ "(5) Bing" + "^" + "Click Marker Permalink: " + mmclickpermalink + "^" + "Centre Permalink: " + mmcentrepermalink + "^" + "^" + "Systematic Maps : www.sysmaps.com";
		transmessage = "http://www.sysmaps.co.uk/email2.html? +" + transmessage1;
		//alert("Msg1: " + transmessage);
		//alert(transmessage);
		var load = window.open(transmessage,'', 'scrollbars=yes,menubar=no,height=710,width=1000,resizable=yes,toolbar=no,location=no,status=no');
	
	}	
		
	//	if (window.clipboardData) {
     //    window.clipboardData.setData("Text",permalinkstr);
	 // }
		//copytowindows(permalinkstr);
		
		copy(permalinkstr);
  }  

function copy(text)  
{  
	//Clear existing data
	try{
		  window.clipboardData.clearData();
			}
		  catch(err){
			}	
	
	if(window.clipboardData)  
    {  
    window.clipboardData.setData('text',text);  
    }  
    else  
    {  
        var clipboarddiv=document.getElementById('divclipboardswf');  
    if(clipboarddiv==null)  
    {  
       clipboarddiv=document.createElement('div');  
       clipboarddiv.setAttribute("name", "divclipboardswf");  
       clipboarddiv.setAttribute("id", "divclipboardswf");  
       document.body.appendChild(clipboarddiv);  
    }  
        clipboarddiv.innerHTML='<embed src="clipboard.swf" FlashVars="clipboard='+  
encodeURIComponent(text)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';  
    }  
    //alert('The text is copied to your clipboard...');  
    return false;  
}  

function opengoogle()
    {
		
		//alert(clicklat + " : " + clicklon);
	      try{
		     ptlat = Math.round(clicklat * 10000) / 10000;
			 ptlon = Math.round(clicklon * 10000) / 10000;
			}
		  catch(err){
		    //Initial position
		     centrepos = this.map.getCenter();
		     centrepos.transform(this.map.baseLayer.projection,this.map.displayProjection);
	   
		    ptlat = Math.round(centrepos.lat * 10000) / 10000;
	        ptlon = Math.round(centrepos.lon * 10000) / 10000;
			}	 
	 
		transmessage = "http://www.sysmaps.co.uk/sysmaps_google.html?+!" + ptlat + "~" + ptlon;
		//alert(transmessage);
		var load = window.open(transmessage,'','scrollbars=no,menubar=no,height=600,width=1200,resizable=yes,toolbar=no,location=no,status=no');
  }  
  
  function openbing()
    {
		
		//alert(clicklat + " : " + clicklon);
	      try{
		     ptlat = Math.round(clicklat * 10000) / 10000;
			 ptlon = Math.round(clicklon * 10000) / 10000;
			}
		  catch(err){
		    //Initial position
		     centrepos = this.map.getCenter();
		     centrepos.transform(this.map.baseLayer.projection,this.map.displayProjection);
	   
		    ptlat = Math.round(centrepos.lat * 10000) / 10000;
	        ptlon = Math.round(centrepos.lon * 10000) / 10000;
			}	 
	 
		transmessage = "http://www.sysmaps.co.uk/sysmaps_bing.html?+!" + ptlat + "~" + ptlon;
		//alert(transmessage);
		var load = window.open(transmessage,'','scrollbars=no,menubar=no,height=600,width=1200,resizable=yes,toolbar=no,location=no,status=no');
  }  
  
  
   function openbing2()
    {
		
		//alert(clicklat + " : " + clicklon);
	      try{
		     ptlat = Math.round(clicklat * 10000) / 10000;
			 ptlon = Math.round(clicklon * 10000) / 10000;
			}
		  catch(err){
		    //Initial position
		     centrepos = this.map.getCenter();
		     centrepos.transform(this.map.baseLayer.projection,this.map.displayProjection);
	   
		    ptlat = Math.round(centrepos.lat * 10000) / 10000;
	        ptlon = Math.round(centrepos.lon * 10000) / 10000;
			}	 
		
		transmessage = "http://www.bing.com/maps/?v=2&where1=" + ptlat + "%2C" + ptlon + "&encType=1";
		//alert(transmessage);
		var load = window.open(transmessage,'','scrollbars=yes,menubar=yes,height=600,width=1200,resizable=yes,toolbar=yes,location=yes,status=yes');
  } 
  
  function loadearthnc() {
var load = window.open("http://earthnc.com/online-nautical-charts" ,'','scrollbars=no,menubar=no,height=700,width=1000,resizable=yes,toolbar=no,location=no,status=no');
}
  
  /*
 * convert numeric grid reference (in metres) to standard-form grid ref
 * Grid conversion function from code at http://www.movable-type.co.uk/scripts/latlong-gridref.html
 */
 
function gridrefNumToLet(e, n, digits) {
  // get the 100km-grid indices
  var e100k = Math.floor(e/100000), n100k = Math.floor(n/100000);
  
  if (e100k<0 || e100k>6 || n100k<0 || n100k>12) return '';

  // translate those into numeric equivalents of the grid letters
  var l1 = (19-n100k) - (19-n100k)%5 + Math.floor((e100k+10)/5);
  var l2 = (19-n100k)*5%25 + e100k%5;

  // compensate for skipped 'I' and build grid letter-pairs
  if (l1 > 7) l1++;
  if (l2 > 7) l2++;
  var letPair = String.fromCharCode(l1+'A'.charCodeAt(0), l2+'A'.charCodeAt(0));

  // strip 100km-grid indices from easting & northing, and reduce precision
  e = Math.floor((e%100000)/Math.pow(10,5-digits/2));
  n = Math.floor((n%100000)/Math.pow(10,5-digits/2));

  var gridRef = letPair + e.padLZ(digits/2) + n.padLZ(digits/2);
  //var gridRef = letPair + e + n;

  return gridRef;
}

//Conversion Code------------------------------------------------------------------------------------
//Grid conversion functions from code at http://www.movable-type.co.uk/scripts/latlong-gridref.html

/*
 * convert geodesic co-ordinates to OS grid reference
 * Grid conversion function from code at http://www.movable-type.co.uk/scripts/latlong-gridref.html (c) Chris Veness 2002-2009)
 */
function LatLongToOSGrid(p) {
  
  //lat = p.lat.toRad()
  //lon = p.lon.toRad();
  
  var lat = p.lat * Math.PI / 180;
  var lon = p.lon * Math.PI / 180;
  
  var a = 6377563.396, b = 6356256.910;          // Airy 1830 major & minor semi-axes
  var F0 = 0.9996012717;                         // NatGrid scale factor on central meridian
  
  //var lat0 = (49).toRad()
  //var lon0 = (-2).toRad();  // NatGrid true origin
  
  var lat0 = 49 * Math.PI / 180;
  var lon0 = -2 * Math.PI / 180;
  
  
  var N0 = -100000, E0 = 400000;                 // northing & easting of true origin, metres
  var e2 = 1 - (b*b)/(a*a);                      // eccentricity squared
  var n = (a-b)/(a+b), n2 = n*n, n3 = n*n*n;

  var cosLat = Math.cos(lat), sinLat = Math.sin(lat);
  var nu = a*F0/Math.sqrt(1-e2*sinLat*sinLat);              // transverse radius of curvature
  var rho = a*F0*(1-e2)/Math.pow(1-e2*sinLat*sinLat, 1.5);  // meridional radius of curvature
  var eta2 = nu/rho-1;

  var Ma = (1 + n + (5/4)*n2 + (5/4)*n3) * (lat-lat0);
  var Mb = (3*n + 3*n*n + (21/8)*n3) * Math.sin(lat-lat0) * Math.cos(lat+lat0);
  var Mc = ((15/8)*n2 + (15/8)*n3) * Math.sin(2*(lat-lat0)) * Math.cos(2*(lat+lat0));
  var Md = (35/24)*n3 * Math.sin(3*(lat-lat0)) * Math.cos(3*(lat+lat0));
  var M = b * F0 * (Ma - Mb + Mc - Md);              // meridional arc

  var cos3lat = cosLat*cosLat*cosLat;
  var cos5lat = cos3lat*cosLat*cosLat;
  var tan2lat = Math.tan(lat)*Math.tan(lat);
  var tan4lat = tan2lat*tan2lat;

  var I = M + N0;
  var II = (nu/2)*sinLat*cosLat;
  var III = (nu/24)*sinLat*cos3lat*(5-tan2lat+9*eta2);
  var IIIA = (nu/720)*sinLat*cos5lat*(61-58*tan2lat+tan4lat);
  var IV = nu*cosLat;
  var V = (nu/6)*cos3lat*(nu/rho-tan2lat);
  var VI = (nu/120) * cos5lat * (5 - 18*tan2lat + tan4lat + 14*eta2 - 58*tan2lat*eta2);

  var dLon = lon-lon0;
  var dLon2 = dLon*dLon, dLon3 = dLon2*dLon, dLon4 = dLon3*dLon, dLon5 = dLon4*dLon, dLon6 = dLon5*dLon;

  var N = I + II*dLon2 + III*dLon4 + IIIA*dLon6;
  var E = E0 + IV*dLon + V*dLon3 + VI*dLon5;

  return gridrefNumToLet(E, N, 8);
}

// extend Number object with methods for converting degrees/radians

Number.prototype.toRad = function() {  // convert degrees to radians
  return this * Math.PI / 180;
}

/*
 * pad a number with sufficient leading zeros to make it w chars wide
 */
Number.prototype.padLZ = function(w) {
  var n = this.toString();
  for (var i=0; i<w-n.length; i++) n = '0' + n;
  return n;
}
  
 //Resize ID=====================================================
function getObj(name)
{
   if (document.getElementById)
   {
      this.obj = document.getElementById(name);
      this.style = document.getElementById(name).style;
   }
   else if (document.all)
   {
      this.obj = document.all[name];
      this.style = document.all[name].style;
   }
}

function getWinSize(){
   var iWidth = 0, iHeight = 0;
 
   if (document.documentElement && document.documentElement.clientHeight){
       iWidth = parseInt(window.innerWidth,10);
       iHeight = parseInt(window.innerHeight,10);
   }
   else if (document.body){
       iWidth = parseInt(document.body.offsetWidth,10);
       iHeight = parseInt(document.body.offsetHeight,10);
   }
 
   return {width:iWidth, height:iHeight};
}

function resize_id(obj)
{
  
  isiPad = "N/A";
  isiPad = navigator.userAgent.match(/iPad/i)!=null;
  
//if (isiPad == true) {return};
  
   var oContent = new getObj(obj);
   var oWinSize = getWinSize();
   if ((oWinSize.height - parseInt(oContent.obj.offsetTop, 10)) > 0)
   oContent.style.height = (oWinSize.height - parseInt(oContent.obj.offsetTop, 10));

   winW = 1100, winH = 600;

   if (parseInt(navigator.appVersion) > 3)
   {
      if (navigator.appName == "Netscape")
      {
         winW = window.innerWidth;
         winH = window.innerHeight;
      }
      if (navigator.appName.indexOf("Microsoft") != - 1)
      {
         winW = document.body.offsetWidth;
         winH = document.body.offsetHeight;
      }
   }
    
	//if (winH < 600 && isiPad == false ) { winH = 600};
    newH = winH * 0.82 + 'px';
	newW = winW * 0.98 + 'px';

 if (isiPad == false) {
 
   document.getElementById('map').style.width = newW;
   document.getElementById('map').style.height = newH;
   this.map.updateSize();
	
  // alert("Not iPad: Width: " + winW + " : " + newW + " : " + document.getElementById("map").style.width + " : Height: " + winH + " : " + newH+ " : " + document.getElementById("map").style.height);
   }

if (isiPad == true) {
	
	if ( Math.abs(window.orientation) == 90 ) {  
				 document.getElementById('map').style.width = winW * 0.98 + 'px';
                 document.getElementById('map').style.height = winH * 0.82 + 'px';
				 this.map.updateSize();
				//alert("iPad Landscape: Width: " + winW + " : " + newW + " : " + document.getElementById("map").style.width + " : Height: " + winH + " : " + newH + " : " + document.getElementById("map").style.height);
    }
	else
	{
	             document.getElementById('map').style.width = winW * 0.98 + 'px';
                 document.getElementById('map').style.height = winH * 0.82 + 'px';
				  this.map.updateSize();
				 //alert("iPad Portrait: Width: " + winW + " : " + newW + " : " + document.getElementById("map").style.width + " : Height: " + winH + " : " + newH + " : " + document.getElementById("map").style.height);
	}
}
}
	
	
	//========================================================================================	
		
/**
 * Openlayer layer handler for OpenSpace layer
 */
Proj4js.defs["EPSG:27700"]	= "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs ";
EPSG27700	= new OpenLayers.Projection( "EPSG:27700" );

OpenLayers.Layer.UKOrdnanceSurvey = OpenLayers.Class(OpenLayers.Layer.WMS, {
			initialize:		function(name, options )
								{

								OpenLayers.Layer.WMS.prototype.initialize.apply
									(
										this,
										new Array
											(
												"UK Ordnance Survey",
												options.base_url + options.tile_server,
												{ format:'image/png', key:options.key, url:document.URL },
												OpenLayers.Util.extend
													(
														options,
														{
														//	UK Ordnance Survey require the 'attribution', or
														//	copyright message, in their T&C for using the service.

														attribution:	"&copy; Crown Copyright &amp; Database Right 2011.&nbsp; All rights reserved.<br />" +
																		"<a href=\"http://openspace.ordnancesurvey.co.uk/openspace/developeragreement.html#enduserlicense\" target=\"_blank\">End User License Agreement</a>",
														projection:		EPSG27700,
														maxExtent:		new OpenLayers.Bounds( 0, 0, 800000, 1300000 ),
														resolutions:	new Array( 2500, 1000, 500, 200, 100, 50, 25, 10, 5, 2, 1 ),
														tile200:		new OpenLayers.Size( 200, 200 ),
														tile250:		new OpenLayers.Size( 250, 250 )
														}
													)
											)
									);
								},

			moveTo:			function( bounds, zoomChanged, dragging )
								{
								if( zoomChanged )
									{
									var	resolution = this.getResolution();
									var	oTileSize = this.tileSize;
									this.setTileSize( resolution < 5 ? this.tile250 : this.tile200 );
									if( this.tileSize != oTileSize )
										this.clearGrid();
									this.params = OpenLayers.Util.extend( this.params, OpenLayers.Util.upperCaseObject({"layers":resolution}) );
									}
								OpenLayers.Layer.WMS.prototype.moveTo.apply(this, new Array(bounds, zoomChanged, dragging) );
								},

			CLASS_NAME:		"OpenLayers.Layer.WMS.UKOrdnanceSurvey"
		}
		);
		
	//===================================================================================			
		
		
  
  
	

