//
//  Adds link to generate LOC file from geocache page.
//  (C) Copyright 2007-2010 James Inge.  Licensed under the MIT License
//
//  v1.02	Fixed for changes to geocaching.com
//  v1.01 	Made separate functions for getting the cache details, and adapted to changes in the geocaching.com page layout.
//
//  
//

// ==UserScript==
// @name	Geocaching.com LOC Link
// @namespace	http://inge.org.uk/userscripts
// @description	Adds a link to generate a LOC file from a geocache page.
// @include	http://www.geocaching.com/seek/cache_details.aspx*
// @license	MIT License; http://www.opensource.org/licenses/mit-license.php
// ==/UserScript==

(function() {
	function addGeoLink() {
		var srcTarget = document.getElementById('ctl00_ContentBody_lnkConversions');
		var destTarget = document.getElementById('ctl00_ContentBody_LatLon');
		var cacheName = getGCname();
		var cacheNum = getGCnum();

		if (srcTarget && destTarget && cacheNum && cacheName) {
			var loc = srcTarget.href;
			lat = loc.slice(loc.search('lat=')+4);
			lat2 = lat.slice(0,lat.search('&'));
			lon = loc.slice(loc.search('&lon=')+5);
			lon2 = lon.slice(0,lon.search('&'));

			locfmt = escape("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<loc version=\"1.0\" src=\"Groundspeak\">\n<waypoint>\n\t<name id=\"" + cacheNum + "\"><![CDATA[" + cacheName + "]]></name>\n\t<coord lat=\"" +
			lat2 + "\" lon=\"" + lon2 + "\"/>\n\t<type>Geocache</type>\n\t<link text=\"Cache Details\">http://www.geocaching.com/seek/cache_details.aspx?wp=" + cacheNum + "</link>\n</waypoint></loc>");

			destTarget.innerHTML += " <a type=\"application/xml-loc\" title=\"Click to generate a LOC file from the coordinates.\" href=\"data:application/xml-loc," + locfmt +"\">LOC</a>";
		}
	}

	function getGCname() {
		var name = document.getElementById('ctl00_ContentBody_CacheName');
		return name?name.innerHTML:null;
	}

	function getGCnum() {
		var tit = document.evaluate("//div[@id='ctl00_cacheCodeWidget']/p", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
		if( tit.snapshotLength > 0 ) {
			// Assume reference number is in first match.
			titl = tit.snapshotItem(0).innerHTML;
			// Strip off whitespace and any other cruft.
			return /GC[0-9A-Z]*/.exec(titl);
		} else {
			return null;
		}
	}

	addGeoLink();
})();

