var data;
var osMap;
var errmsg = '';

var showtoggle = true;
var toggleLink = "gmapframe.html";
var linkParms;
var cookiemapid;
var googlemapstyle;

//Essex
//minlatitude = 51.445;
//minlongitude = -0.01;
//maxlatitude = 52.07;
//maxlongitude = 1.33;
minlatitude = 51.445;
minlongitude = -0.01;
maxlatitude = 52.05;
maxlongitude = 1.33;
var isIE = navigator.appName.indexOf("Microsoft") != -1;


// Gets filename from the parameter string (?f=filename)
// and passes it to the parser to extract the data.
//
function init() 
{  	
	var queryString = window.location.search.substring(1);

	var fileName;
	
	if  (queryString.length > 0)
	{
		if (queryString.indexOf("f=") > -1)
		{
			fileName = queryString.substring(queryString.indexOf("f=") + 2);
		}
	}
	
	if	(fileName && fileName.length > 4)
	{ 	
		var xotree = new XML.ObjTree();
		data = xotree.parseHTTP("data/" + fileName, {});
	}
	else
	{
		error('No map data file name supplied.');	
		return;	
	}

	// Set page title to the filename (minus .gpx extension) ...
	document.title = fileName.substring(0, fileName.length - 4); 
	

	// Workaround so that script works with Firefox 3.0 
	//  and Safari 3.1. Can be removed once OpenSpace
	//  is based on v2.6 (or later) of OpenLayers.
	 
	//OpenLayers.Renderer.SVG.prototype.supported = function() {
        //var svgFeature = "http://www.w3.org/TR/SVG11/feature#";
        //return (document.implementation &&
        //   (document.implementation.hasFeature("org.w3c.svg", "1.0") ||
         //   document.implementation.hasFeature(svgFeature + "SVG", "1.1") ||
          //  document.implementation.hasFeature(svgFeature + "BasicStructure", "1.1") ));
	//};

	if	(showtoggle)
	{
		linkParms = '?f=' + fileName;
		cookiemapid = fileName;
	}	 
		
	if  (data)
	{
		doGPXOverlay(data);
		
		if	(tracks.length == 0 && waypoints.length == 0)
		{
			error('No data found - may not be a valid GPX file');
			return;
		}
		
		displayMap();
		displayData();	
	}
	else
	{
		error('Data parse problem. Cannot load map data file.')
	}
	
}  


function resizemap()
{
	if	(osMap == null)
	{
		return;
	}
	
	var sizes = getAvailableArea();

	var mapDiv = document.getElementById("map"); 
	
	// Put the loading message underneath the tiles
	document.getElementById("map").style.backgroundImage = "url(images/loading.jpg)";

	//mapDiv.style.height = "100%";
	//mapDiv.style.width  = "100%";
	//mapDiv.style.margin = "0px";
	
	mapDiv.style.height = (sizes[1] - 10) + "px";
	mapDiv.style.width  = (sizes[0] - 10) + "px";
	mapDiv.style.margin = "0px 0px 10px 0px";


	if	(showtoggle)
	{
		var toggleDiv = document.getElementById("togglepanel"); 
		toggleDiv.style.left = (sizes[0] - 10) - 174 - 15 + "px";
		toggleDiv.style.top =  (sizes[1] - 60) + "px";
	
		toggleDiv.innerHTML = '<img src="http://www.essexwalks.com/images/gmaps24.gif" style="vertical-align: middle; margin-right: 2px;"/>Google Map View';
		toggleDiv.onclick = toggleGoogleMap;
		toggleDiv.title = "Click to switch to Google Maps";
		toggleDiv.style.display = "block";
		toggleDiv.style.fontFamily='Arial';
	    toggleDiv.style.fontSize='10px';
		toggleDiv.style.background='#E9E9E9';
	}
}


// Initialises the map at the highest zoom level that will allow  
// all of the tracks, routes and waypoints to be visible. 
//
function displayMap() 
{
    //var options = {maxExtent: new OpenSpace.MapBounds(400000, 120000, 690000, 290000) };
	//osMap = new OpenSpace.Map('map', options);  
	//shifts calculated centre do not use

// TEST at 1st August 2010
//Controls below incompatible with openspace 1.2 (openlayers 2.8) - compat with v1.0.1
var controls = [new OpenLayers.Control.Navigation({'zoomWheelEnabled': false}),
					                    new OpenLayers.Control.KeyboardDefaults(),
                       					new OpenSpace.Control.CopyrightCollection(),
                       					new OpenLayers.Control.ArgParser(),
                       				//	new OpenSpace.Control.SmallMapControl(),   //replaced by blue openlayers control PanZoomBar
									    new OpenLayers.Control.PanZoomBar(),
       					                new OpenSpace.Control.PoweredBy()
                     					];
    osMap = new OpenSpace.Map('map', {controls: controls}, {centreInfoWindow: true} );
    //For 1.2 compat replaced with-
    //osMap = new OpenSpace.Map('map'); 
// end of 1st August 2010 edit


	var googlebounds = getcookiebounds();

	if	(googlebounds)
	{
		googlemapstyle = googlebounds.mapstyle;
		
		var zoomLevel = osMap.getZoomForExtent(new OpenSpace.MapBounds(googlebounds.mineasting, googlebounds.minnorthing, googlebounds.maxeasting, googlebounds.maxnorthing));
		
		if	((zoomLevel < 10) && (zoomLevel >3))
		{
		zoomLevel++;
		}		
		
		if	(zoomLevel < 3)
		{
		zoomLevel = 3;
		}
		
		
		osMap.setCenter(googlebounds.centre, zoomLevel);
	}	
	else
	{
		var sw = makeMapPoint(minlongitude, minlatitude);
		var ne = makeMapPoint(maxlongitude, maxlatitude);
		
		var bounds = new OpenSpace.MapBounds();
		bounds.extend(sw);
		bounds.extend(ne);
	
		var zoomLevel = osMap.getZoomForExtent(bounds);
		osMap.setCenter(bounds.getCenterLonLat(), zoomLevel);
	}

	resizemap();
}


// Displays a single line for each of the included tracks and/or routes,
// plus a single marker (with default icon) for each waypoint.
//
function displayData() 
{
	if	(tracks.length > 0)
	{
 		vectorLayer = osMap.getVectorLayer();    
	}
	
	for (var i = 0; i < tracks.length; i++)
	{
		if	(tracks[i].points.length > 0)
		{
			var trackPoints = [];

			for (var j = 0; j < tracks[i].points.length; j++)
			{
				trackPoints.push(makeTrackPoint(tracks[i].points[j].longitude, tracks[i].points[j].latitude));		
			} 
			
			var lineString = new OpenLayers.Geometry.LineString(trackPoints); 
		
			var lineStyle = 
			{ 
				strokeColor: "#660099", 
				strokeOpacity: 0.6, 
				strokeWidth: 3 
			};
			 
			var lineFeature = new OpenLayers.Feature.Vector(lineString, null, lineStyle); 
			vectorLayer.addFeatures([lineFeature]); 
		}	
	}
	
	for (var i = 0; i < waypoints.length; i++) 
	{
		
		var html;
		
		if  (waypoints[i].desc && waypoints[i].desc.length > 0)
		{
			html= waypoints[i].desc;
		}
		else if (waypoints[i].cmt && waypoints[i].cmt.length > 0)
		{
			
			html = "";
			html = waypoints[i].cmt;
	
		}	
		
		
		
		var mapPoint = makeWaypoint(waypoints[i].longitude, waypoints[i].latitude);  
		
		var icondesc;
		
		if  (waypoints[i].sym && waypoints[i].sym.length > 0)
		{
			icondesc = ('icons/' + waypoints[i].sym + '.png');
		}
		else 
		{
			icondesc = 'icons/blank.png';
		}	
		
// OS Space lacks auto size so use GPX <source> to provide height
 		
 		var popupw = 372;  // needed for IE8,  368 ok for FF3
		var popuph = 400;
		
		if (waypoints[i].src && waypoints[i].src.length > 0)
		{
					
			popuph = waypoints[i].src;		
		}	
		else
		{
			popuph = 400;
		}
		
		var icon = new OpenSpace.Icon(icondesc, new OpenLayers.Size(32, 32), new OpenLayers.Pixel(-16,-32))
		
		osMap.createMarker(mapPoint, icon , html, new OpenLayers.Size(popupw, popuph)); 
	
	}

}


//
// Converts a track or route point from Lon/Lat to OpenSpace format
//
function makeTrackPoint(lon, lat)
{
	var mp = makeMapPoint(lon, lat);
	return new OpenLayers.Geometry.Point(mp.getEasting(), mp.getNorthing());
}


//
// Converts a waypoint from Lon/Lat to OpenSpace format
//
function makeWaypoint(lon, lat)
{
	var mp = makeMapPoint(lon, lat);
	return new OpenSpace.MapPoint(mp.getEasting(), mp.getNorthing());
}


//
// Makes an OS MapPoint from Lon/Lat
//
function makeMapPoint(lon, lat)
{
	var pos = new OpenLayers.LonLat(lon, lat);
	var gridProjection = new OpenSpace.GridProjection();
	return gridProjection.getMapPointFromLonLat(pos);
}

function error(msg)
{
	errmsg += '<li>' + msg + '</li>\n';
	var errDiv = document.getElementById('error');
	errDiv.innerHTML = '<h4>Error!</h4><ul>' + errmsg + '</ul>' ;
	errDiv.style.display = 'block';
}


function toggleGoogleMap()
{
	var gridProjection = new OpenSpace.GridProjection();

	var bounds = osMap.getExtent();
	var lbrt = bounds.toArray();			
	
	var sw = gridProjection.getLonLatFromMapPoint(new OpenSpace.MapPoint(lbrt[0], lbrt[1])); 
	var ne = gridProjection.getLonLatFromMapPoint(new OpenSpace.MapPoint(lbrt[2], lbrt[3])); 

	if	(!googlemapstyle)
	{
		googlemapstyle = 'N';
	}

	writeCookies(cookiemapid, sw.lon, sw.lat, ne.lon, ne.lat, googlemapstyle);

	window.location.href = toggleLink + linkParms;
}


function writeCookies(mapid, minx, miny, maxx, maxy, mapstyle)
{
	setCookie("mapid", escape(mapid));
	setCookie("minx", minx);
	setCookie("miny", miny);
	setCookie("maxx", maxx);
	setCookie("maxy", maxy);
	setCookie("gmapstyle", mapstyle);
} 
 
 
function getcookiebounds()
{
	var mapid = unescape(getCookie("mapid"));
	 
	deleteCookie("mapid");

	if	(!mapid || mapid != cookiemapid)
	{
		return false;
	}
	
	var googlebounds = new Object();	
	
	var minx = parseFloat(getCookie("minx"));	
	var miny = parseFloat(getCookie("miny"));	
	var maxx = parseFloat(getCookie("maxx"));	
	var maxy = parseFloat(getCookie("maxy"));	
	
	var centrex = (maxx + minx) / 2;	
	var centrey = (maxy + miny) / 2;	

	var gridProjection = new OpenSpace.GridProjection();

	var ne = gridProjection.getMapPointFromLonLat(new OpenLayers.LonLat(maxx, maxy));
	var sw = gridProjection.getMapPointFromLonLat(new OpenLayers.LonLat(minx, miny));
	
	googlebounds.mineasting = sw.getEasting();
	googlebounds.maxeasting = ne.getEasting();
	googlebounds.minnorthing = sw.getNorthing();
	googlebounds.maxnorthing = ne.getNorthing();
		
	googlebounds.centre = gridProjection.getMapPointFromLonLat(new OpenLayers.LonLat(centrex, centrey));
	googlebounds.mapstyle = getCookie("gmapstyle"); 
	
	return googlebounds;
}	


