/**
 * JavaScriot funtions/methods to display an OSGB map on a web page
 * 
 */  
// This function loads the XML document from the specified URL, and when
// it is fully loaded, passes that document and the url to the specified
// handler function.  This function works with any XML document

	// url		Path to file, on current server
	// handler	Function to call once the XML file is loaded
function loadXML(url, handler) 
	{
	if(url == null)
		{
			// TFC did not appear to be set in walks.ndrw.co.uk, has no effect.
		var dataDir = "";
		
		var args = getArgs();
		
		if(args.file)
			{
			var file = args.file;
			var array = file.split('/');
			
			dataDir		= array[1] + '/' + array[2] + '/' + dataDir;
			}
		else if(Get_Cookie("user") != null)
			dataDir		= Get_Cookie("user") + dataDir;
			// We assume file is in /map/ted/
		if(args.track)
			url = '/map/ted/data/' + args.track + '.xml';
		}
	try
	{
				// Use the standard DOM Level 2 technique, if it is supported
		if (document.implementation && document.implementation.createDocument) 
			{
				// Create a new Document object
			var xmldoc = document.implementation.createDocument("", "", null);
				// Specify what should happen when it finishes loading
			xmldoc.onload = function() 
				{ 
				handler(xmldoc, url); 
				}
			xmldoc.async = true;
				
				// And tell it what URL to load
			xmldoc.load(url);
			}
		    
			// Otherwise use Microsoft's proprietary API for Internet Explorer
	    else if (window.ActiveXObject) 
			{ 
				var xmldoc = new ActiveXObject("Microsoft.XMLDOM");   // Create doc.
				xmldoc.onreadystatechange = function() 
				{              
					// Specify onload
				if (xmldoc.readyState == 4) 
					handler(xmldoc, url);
				}
			xmldoc.load(url);                                     // Start loading!
			}
	}
  catch(e)
    {
    alert(e.message);
    return;
    }
	
	}
/**
 *
 * The handler function called via loadXML
 * 
 * xmlDoc	Open handle to the XML doc
 * url		Path to file on this server (not used)
 *    
 */   
function parseGPSXML(xmlDoc, url)
{
try
	{
	var osMap;

		// Update all text fields first
	populatePage(xmlDoc);

	osMap = new OpenSpace.Map('map');
	var gridProjection = new OpenSpace.GridProjection();

//	var pos= getOSGB(-1.891408244, 53.1939768335);
				
//	osMap.setCenter(new OpenSpace.MapPoint(Math.round(pos.getEasting()), Math.round(pos.getNorthing())), 7);

	populatePage(xmlDoc);
	
	centerMap(osMap, xmlDoc);
		// the markers
	addMarkers(osMap, xmlDoc);		
		// Add the track
	addTrack(osMap, xmlDoc);		
	}
  catch(e)
    {
    alert(e.message);
    return;
    }

}
/**
 *
 * Addmarkers
 * 
 * The pins for the photographs
 * 
 */     
function addMarkers(osMap, xmlDoc)
	{	
	
	var iconStart	= new OpenSpace.Icon('http://osgb.ndrw.co.uk/images/marker_start.png',   new OpenLayers.Size(12, 20), new OpenLayers.Pixel(-6, -20));
	
	var placeElements = xmlDoc.documentElement.getElementsByTagName("Place");
	
	if(placeElements)
		{
		var data		= "";
		var desc		= "";
		var images	= "";
		var output 	= "";
		var lng		= 0;
		var lat		= 0;
		var waypoint= "";
		var local	= "";

		var pos;

		for(var i = 0; i < placeElements.length; i++)
			{
			waypoint = placeElements[i].getAttribute("waypoint");
			lat 		= placeElements[i].getAttribute("lat");
			lng 		= placeElements[i].getAttribute("long");
			desc 		= placeElements[i].getAttribute("description");
			local		= placeElements[i].getAttribute("local");

				// Outout location lat/long or local
			if('Turned off' == local)
				desc += '<BR>Lat ' + lat + '<BR>Long ' + lng;
			else
				{
					// replace the 'non' printing chars

				if(local)
					{
					local = local.replace(/deg/g, "&deg;");
					local = local.replace(/min/g, "&acute;");
					local = local.replace(/ /g, "&nbsp;");
					}

				desc += '<BR>' + local;
				}
			
			desc.replace(/ /, "&nbsp;");
			output += lat + "  long " + lng + " " + desc + " ";

			var images = new Array();
			images.length = 0;
			
			var imageset = placeElements[i].getElementsByTagName("Pictures")[0];
			images = imageset.getElementsByTagName("Picture");
						
			var thumbArray = new Array();
			var kountThumb = 0;
				
				// Make sure thumnail is cleared
			var thumbnail;
			thumbnail = undefined;
			for(j = 0; j < images.length; j++)
				{
					// Need to change .jpg to _thumb.jpg, path is supplied
				var thumbnail = images[j].getAttribute("filename");
					// TFC Case sensitive suffix so we use the . as a 'delimeter'				
				thumbnail = thumbnail.replace(".", "_thumb.");
				thumbArray[kountThumb++] = thumbnail;

				output +=  images[j].getAttribute("filename") + "  ";
				}
			output += "\n";
				// Add HTML data, to contain link to next page, 1 picture, terse description, osgb
				// Wait till we have real data it > 1 picture choose one at random
				// file name user_name_thumb.jpg full size user_name.jpg
				
				// Use a random file
			var no = 0;
			if(kountThumb > 1)
				{
				kountThumb--;
				no = Math.round(Math.random() * 100 % kountThumb);
				thumbnail = thumbArray[no];
				}

			var sizeThumb = 'width="96" height="72"';
			
			if(images[no])
				{
				if(images[no].getAttribute("thumbWidth"))
					{
					var width = images[no].getAttribute("thumbWidth");
					var height = images[no].getAttribute("thumbHeight");
					
					sizeThumb = 'width="' + width + '" height="' + height + '"';
					}
				}	
			
			pos = getOSGB(lng, lat);
//			var content = new String('Test data <strong>HTML</strong><br />');
			
			var content = createMarkerPhotoHTML(waypoint, thumbnail, desc, sizeThumb);
			
			if(waypoint == 'startpoint')
				var marker = osMap.createMarker(pos, iconStart, content);
			else
				{
				var iconWPT	= new OpenSpace.Icon('http://osgb.ndrw.co.uk/images/marker_wpt.png', new OpenLayers.Size(12, 20), new OpenLayers.Pixel(-6, -20));
				var marker 	= osMap.createMarker(pos, iconWPT, content);
				}
			}
		}
	}

/**
 *
 * Add a track by pasing the XML file  between <WayPoint> tags
 * 
 * osMap		Open handle to the OS Map
 * xmlDoc	Open handle to the XML file
 *    
 */  
function addTrack(osMap, xmlDoc)
	{
	var points = [];
		// TFC Caused the Z Order to be NBG ansds makers did not opo up
//	var vectorLayer = new OpenLayers.Layer.Vector("Vector Layer");
	var vectorLayer = osMap.getVectorLayer();
	
	osMap.addLayer(vectorLayer);
	/*
	* Define the line style
	*/
	var style_red =
		{
	   strokeColor: "#FF00FF",
	   strokeOpacity: 0.7,
	   strokeWidth: 4,
	   pointRadius: 6,
	   pointerEvents: "visiblePainted"
		};
			
		// Get an array of <WayPoint> tag data
	var waypoints 		= xmlDoc.documentElement.getElementsByTagName("WayPoint");
	
	for (var i = 0; i < waypoints.length; i++) 
		{
		pos = getOSGB(parseFloat(waypoints[i].getAttribute("long")), parseFloat(waypoints[i].getAttribute("lat")));
		var point = new OpenLayers.Geometry.Point(Math.round(pos.getEasting()), Math.round(pos.getNorthing()));
		points.push(point);
		}

		// create a line feature from a list of points
	var lineString 	= new OpenLayers.Geometry.LineString(points);
	var lineFeature 	= new OpenLayers.Feature.Vector(lineString, null, style_red);
	
	vectorLayer.addFeatures([lineFeature]);
	}
			
/**
 *
 * Centers the map using the <BoundingRectangle> tag
 * 
 * osMap		Open handle to the OS Map
 * xmlDoc	Open handle to the XML file
 *    
 */  
function centerMap(osMap, xmlDoc)
	{
	var BoundingRectangle = xmlDoc.documentElement.getElementsByTagName("BoundingRectangle");

	if(BoundingRectangle.length > 0)
		{
		var left 	= parseFloat(BoundingRectangle[0].getAttribute('minX'));
		var right 	= parseFloat(BoundingRectangle[0].getAttribute('maxX'));
		var bottom 	= parseFloat(BoundingRectangle[0].getAttribute('maxY'));
		var top	 	= parseFloat(BoundingRectangle[0].getAttribute('minY'));

		var llLH = getOSGB(left, top);
		var llRH = getOSGB(right, bottom);							
	
			// left, top, right, bottom				
		var bounds = new OpenLayers.Bounds(llLH.lon, llLH.lat, llRH.lon, llRH.lat);
	
		osMap.zoomToExtent(bounds); 
		}
	else
		alert("centerMap failure");
	}

/**
 *
 * Builds the HTML string to the marker pop up using the <Place> tag
 *  
 * waypoint 		Waypoint name
 * thumbnail		Name of a random thumbnail
 * data				The description fileld from the <Place> tag
 * sizeThumb		Thumbnail size HTML string 
 *    
 */  
function createMarkerPhotoHTML(waypoint, thumbnail, data, sizeThumb) 
	{ 
	var html = "<P><font size='1' face='Helvetica, Arial,sans-serif'>";
	var wpt 	= waypoint;
	
	var waypointModified = wpt.replace(/_/g, ' ');
	
	if(thumbnail)
		{
			// Get base file name and strip the data between _ and .
		var filepath = thumbnail.replace("_thumb.", ".");
		var lastdot	 = filepath.lastIndexOf(".");
		
			// used to search for all files in the next page assume JPG
		filepath = filepath.substr(0, lastdot);
		
			// arg thumbnail is /map/ted/photos/zz_startpoint_1159350401.jpg
			// so '/' not needed in from of it
		thumbnail = location.protocol + "//" + location.hostname + thumbnail;
		}
		
	if(thumbnail)
		{
		html += '<a href="http://walks.ndrw.co.uk/display_photo.php?file=' + filepath + '&waypoint=' + waypoint +'">';
		html += '<IMG SRC = "' + thumbnail + '" border="0"' + sizeThumb + '>';
		html += '</a>';
		html += '<br>';
		}
	html += waypointModified + "<br>";
	html += data + "</P>";

	return(html); 
	} // end createMarkerPhotoHTML

/**
 *
 * return the OSGB values for the lat long
 * 
 */    
function getOSGB(lon, lat)
	{
	var gridProjection = new OpenSpace.GridProjection();

	var lonlat = new OpenLayers.LonLat(lon, lat);
	var pos = gridProjection.getMapPointFromLonLat(lonlat);
	
	return(pos);
	}

/**
 *
 * Update all the text fields on the page
 * 
 */   
function populatePage(xmlDoc)
	{
	try
		{
		var Ascent 			 = xmlDoc.documentElement.getElementsByTagName("Ascent");
		var Date 			 = xmlDoc.documentElement.getElementsByTagName("Date");
		var Distance 		 = xmlDoc.documentElement.getElementsByTagName("Distance");
		var Elevation 		 = xmlDoc.documentElement.getElementsByTagName("Elevation");
		var Units	 		 = xmlDoc.documentElement.getElementsByTagName("Units");

		var elementDate	 	= document.getElementById("Date");
		var elementDistance 	= document.getElementById("Distance");
		var elementAscent		= document.getElementById("Ascent");
		var elementMaxheight	= document.getElementById("MaxHeight");
		var elementMinheight	= document.getElementById("MinHeight");
					
		var ascent    		= Ascent[0].getAttribute('ascent');
		var Date				= Date[0].getAttribute('date');
		var dist 			= Distance[0].getAttribute('distance');
		var ElevationMin	= Elevation[0].getAttribute('MinHeight');
		var ElevationMax	= Elevation[0].getAttribute('MaxHeight');

						// The units data
		var units_ascent		= Units[0].getAttribute('Ascent');
		var units_distance	= Units[0].getAttribute('Distance');
		var units_hybrid		= Units[0].getAttribute('Hybrid');

		var distMiles	= dist / 1.6;
		
			// Distance miles & km
		distMiles		= distMiles.toFixed(2);
		elementDistance.innerHTML = dist + "&nbsp;" + units_distance + "&nbsp;";
		if(units_hybrid == 1)
			elementDistance.innerHTML += "(" + distMiles + "&nbsp;miles)";	
		
			// Date
		elementDate.innerHTML = Date;	

			// Max/Min Heights
		elementAscent.innerHTML 	= ascent + " " + units_ascent + ".";
		elementMaxheight.innerHTML = ElevationMax + " " + units_ascent + ".";
		elementMinheight.innerHTML = ElevationMin + " " + units_ascent + ".";
		}
  catch(e)
		{
		return;
		}
	}

/**
 *
 * Cut/Paste from gpssharing.walks utils.js
 * 
 */   

	// from the JavaScript definitive Guide, O'Reilly
function getArgs() 
	{
	var args 	= new Object();
	var query 	= location.search.substring(1);     // Get query string.
	var pairs 	= query.split("&");                 // Break at '&'.
	
	for(var i = 0; i < pairs.length; i++) 
		{
		var pos = pairs[i].indexOf('=');          // Look for "name=value".
		
		if (pos == -1) 									// If not found, skip.
			continue;
			
		var argname 	= pairs[i].substring(0,pos);  // Extract the name.
			
		var value 		= pairs[i].substring(pos+1);    // Extract the value.
		args[argname] 	= unescape(value);          // Store as a property.
		// In JavaScript 1.5, use decodeURIComponent() instead of escape()
   	}
	return args;                                  // Return the object.
	}

	// Get a cookie, obvious really
function Get_Cookie( name ) 
	{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&( name != document.cookie.substring( 0, name.length ) ) )
		{
		return null;
		}
	if ( start == -1 ) 
		return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) 
	
	end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
	}

