/* global $: true */
/* global waitForKeyElements: true */
/* global GM_xmlhttpRequest: true */
/* global GM_getValue: true */
// ==UserScript==
// @name Geocaching.com + Project-GC
// @namespace PGC
// @description Adds links and data to Geocaching.com to make it collaborate with PGC
// @include http://www.geocaching.com/*
// @include https://www.geocaching.com/*
// @version 1.4.2
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js
// @require https://greasyfork.org/scripts/5392-waitforkeyelements/code/WaitForKeyElements.js?version=19641
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @license The MIT License (MIT)
// @downloadURL none
// ==/UserScript==
'use strict';
(function() {
var pgcUrl = 'http://project-gc.com/',
pgcApiUrl = pgcUrl + 'api/gm/v1/',
externalLinkIcon = 'http://maxcdn.project-gc.com/images/external_small.png',
galleryLinkIcon = 'http://maxcdn.project-gc.com/images/pictures_16.png',
mapLinkIcon = 'http://maxcdn.project-gc.com/images/map_app_16.png',
loggedIn = GM_getValue('loggedIn'),
subscription = GM_getValue('subscription'),
pgcUsername = GM_getValue('pgcUsername'),
gccomUsername = GM_getValue('gccomUsername'),
latestLogs = [],
latestLogsAlert = false,
settings = {},
path = window.location.pathname;
// Don't run the script for iframes
if (window.top == window.self) {
Main();
}
/**
* Router
*/
function Main() {
ReadSettings();
CheckPGCLogin();
if (path.match(/^\/geocache\/.*/) !== null) {
Page_CachePage();
} else if (path.match(/^\/seek\/cache_logbook\.aspx.*/) !== null) {
Page_Logbook();
}
}
function GetSettingsItems() {
var items = {
showVGPS: { title: 'Show Virtual GPS', default: true },
addChallengeCheckers: { title: 'Add challenge checkers', default: true },
makeCopyFriendly: { title: 'Make copy friendly GC-Code and link', default: true },
addPgcMapLinks: { title: 'Add PGC map links', default: true },
addLatestLogs: { title: 'Add latest logs', default: true },
cloneLogsPerType: { title: 'Clone number of logs per type', default: true },
addPGCLocation: { title: 'Add PGC Location', default: true },
addAddress: { title: 'Add reverse geocoded address', default: true },
removeUTM: { title: 'Remove UTM coordinates', default: true },
addPgcFp: { title: 'Add FP from PGC', default: true },
profileStatsLinks: { title: 'Add links to Profile stats', default: true },
tidy: { title: 'Tidy the web a bit', default: true },
collapseDownloads: { title: 'Collapse download links', default: false },
addPgcGalleryLinks: { title: 'Add links to PGC gallery', default: true },
addMapBookmarkListLinks: { title: 'Add links for bookmark lists', default: true },
decryptHints: { title: 'Automatically decrypt hints', default: true },
addElevation: { title: 'Add elevation', default: true }
};
return items;
}
function ReadSettings() {
settings = GM_getValue('settings');
if(typeof(settings) != 'undefined') {
settings = JSON.parse(settings);
} else {
settings = [];
}
var items = GetSettingsItems();
for(var item in items) {
if(typeof(settings[item]) == 'undefined') {
settings[item] = items[item].default;
}
}
}
function SaveSettings() {
GM_deleteValue('disabledFunctions'); // Legacy
settings = {};
var items = GetSettingsItems();
for(var item in items) {
var checked = $('#pgcUserMenuForm input[name="' + item + '"]').is(':checked');
settings[item] = (checked) ? 1 : 0;
}
var json = JSON.stringify(settings);
GM_setValue('settings', json);
$('#pgcUserMenuWarning').css('display', 'inherit');
}
function IsSettingEnabled(setting) {
return settings[setting];
}
/**
* Check that we are logged in at PGC, and that it's with the same username
*/
function CheckPGCLogin() {
gccomUsername = false;
if( $('#ctl00_divSignedIn').length ) {
gccomUsername = $('#ctl00_divSignedIn .li-user-info span').html();
} else if( $('ul.profile-panel-menu').length ) {
gccomUsername = $('ul.profile-panel-menu .li-user-info span:nth-child(2)').text();
}
GM_setValue('gccomUsername', gccomUsername);
GM_xmlhttpRequest({
method: "GET",
url: pgcApiUrl + 'GetMyUsername',
onload: function(response) {
var result = JSON.parse(response.responseText),
html, loggedInContent, subscriptionContent = '';
if (result.status !== 'OK') {
alert(response.responseText);
return false;
}
pgcUsername = result.data.username;
loggedIn = !!result.data.loggedIn;
subscription = !!result.data.subscription;
if (loggedIn === false) {
loggedInContent = 'Not logged in';
} else {
if (pgcUsername == gccomUsername) {
loggedInContent = '' + pgcUsername + '';
} else {
loggedInContent = '' + pgcUsername + '';
}
if (subscription) {
subscriptionContent = 'Paid membership';
} else {
subscriptionContent = 'Missing membership';
}
}
var html = '\
\
\
\
\
\
' + loggedInContent + '\
' + subscriptionContent + '\
\
\
\
\
\
';
if ( $('#ctl00_divSignedIn ul.logged-in-user').length ) { // The default look of the header bar
$('#ctl00_divSignedIn ul.logged-in-user').prepend('
' + html + '
');
} else if( $('ul.profile-panel-menu').length ) { // Special case for https://www.geocaching.com/account/settings/preferences
$('ul.profile-panel-menu').prepend('
' + html + '
');
}
$('#pgcUserMenuSave').click(function() {
SaveSettings();
});
// Save the login value
GM_setValue('loggedIn', loggedIn);
GM_setValue('subscription', subscription);
GM_setValue('pgcUsername', pgcUsername);
},
onerror: function(response) {
alert(response);
return false;
}
});
}
/**
* getGcCodeFromPage
* @return string
*/
function getGcCodeFromPage() {
return $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoCode').html();
}
/**
* addToVGPS
*/
function addToVGPS() {
var gccode = GM_getValue('gccode'),
listId = $('#comboVGPS').val(),
msg,
url = pgcApiUrl + 'AddToVGPSList?listId=' + listId + '&gccode=' + gccode + '§ionName=GM-script';
GM_xmlhttpRequest({
method: "GET",
url: url,
onload: function(response) {
var result = JSON.parse(response.responseText);
var msg = (result.status === 'OK') ? 'Geocache added to Virtual-GPS!' : 'Geocache not added to Virtual-GPS :(';
$('#btnAddToVGPS').css('display', 'none');
$('#btnRemoveFromVGPS').css('display', '');
alert(msg);
return true;
},
onerror: function(response) {
console.log(response);
return false;
}
});
}
/**
* removeFromVGPS
*/
function removeFromVGPS() {
var gccode = GM_getValue('gccode'),
listId = $('#comboVGPS').val(),
msg,
url = pgcApiUrl + 'RemoveFromVGPSList?listId=' + listId + '&gccode=' + gccode;
GM_xmlhttpRequest({
method: "GET",
url: url,
onload: function(response) {
var result = JSON.parse(response.responseText);
var msg = (result.status === 'OK') ? 'Geocache removed from Virtual-GPS!' : 'Geocache not removed from Virtual-GPS :(';
$('#btnAddToVGPS').css('display', '');
$('#btnRemoveFromVGPS').css('display', 'none');
alert(msg);
return true;
},
onerror: function(response) {
console.log(response);
return false;
}
});
}
/**
* Page_CachePage
*/
function Page_CachePage() {
var gccode = getGcCodeFromPage(),
placedBy = $('#ctl00_ContentBody_mcd1 a').html(),
lastUpdated = $('#ctl00_ContentBody_bottomSection p small time').get(1),
lastFound = $('#ctl00_ContentBody_bottomSection p small time').get(2);
lastUpdated = (lastUpdated) ? lastUpdated.dateTime : false;
lastFound = (lastFound) ? lastFound.dateTime : false;
GM_setValue('gccode', gccode);
// Since everything in the logbook is ajax, we need to wait for the elements
waitForKeyElements('#cache_logs_table tr', Logbook);
// Get geocache data from Project-GC
var url = pgcApiUrl + 'GetCacheDataFromGccode&gccode=' + gccode;
if(lastUpdated)
url += '&lastUpdated=' + lastUpdated;
if(lastFound)
url += '&lastFound=' + lastFound;
if (GM_getValue('subscription')) {
GM_xmlhttpRequest({
method: "GET",
url: url,
onload: function(response) {
var result = JSON.parse(response.responseText),
cacheData = result.data.cacheData,
cacheOwner = result.data.owner,
challengeCheckerTagIds = result.data.challengeCheckerTagIds,
location = [],
fp = 0,
fpp = 0,
fpw = 0;
if(result.status == 'OK' && cacheData !== false) {
// If placed by != owner, show the real owner as well.
if(placedBy != cacheOwner) {
$('#ctl00_ContentBody_mcd1 span.message__owner').before(' (' + cacheOwner + ')');
}
// Append link to Profile Stats for the cache owner
// Need to real cache owner name from PGC since the web only has placed by
if(IsSettingEnabled('profileStatsLinks')) {
$('#ctl00_ContentBody_mcd1 span.message__owner').before('');
}
// Add FP/FP%/FPW below the current FP
if(IsSettingEnabled('addPgcFp')) {
fp = parseInt(+cacheData.favorite_points, 10),
fpp = parseInt(+cacheData.favorite_points_pct, 10),
fpw = parseInt(+cacheData.favorite_points_wilson, 10);
$('#uxFavContainerLink').append('
'
);
}
// Remove the UTM coordinates
// $('#ctl00_ContentBody_CacheInformationTable div.LocationData div.span-9 p.NoBottomSpacing br').remove();
if(IsSettingEnabled('removeUTM')) {
$('#ctl00_ContentBody_LocationSubPanel').html('');
}
// Remove ads
// PGC can't really do this officially
// $('#ctl00_ContentBody_uxBanManWidget').remove();
// Remove disclaimer
// PGC can't really do this officially
// $('#ctl00_divContentMain div.span-17 div.Note.Disclaimer').remove();
// Collapse download links
// http://www.w3schools.com/charsets/ref_utf_geometric.asp (x25BA, x25BC)
if(IsSettingEnabled('collapseDownloads')) {
$('
►▼Print and Downloads
').insertAfter('#ctl00_ContentBody_CacheInformationTable div.LocationData');
$('#ctl00_divContentMain div.DownloadLinks, #DownloadLinksToggle .arrow.open').hide();
}
// Resolve the coordinates into an address
if(IsSettingEnabled('addAddress')) {
var coordinates = $('#ctl00_ContentBody_lnkConversions').attr('href'),
latitude = coordinates.replace(/.*lat=([^&]*)&lon=.*/, "$1"),
longitude = coordinates.replace(/.*&lon=([^&]*)&.*/, "$1"),
url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=false';
GM_xmlhttpRequest({
method: "GET",
url: url,
onload: function(response) {
var result = JSON.parse(response.responseText);
if (result.status !== 'OK') {
return false;
}
var formattedAddress = result.results[0].formatted_address;
$('#ctl00_ContentBody_LocationSubPanel').append(formattedAddress + ' ');
}
});
}
// Add number of finds per type to the top
if(IsSettingEnabled('cloneLogsPerType')) {
$('#ctl00_ContentBody_CacheInformationTable').before('
');
}
// Add link to PGC gallery
if (subscription && IsSettingEnabled('addPgcGalleryLinks')) {
var html = ' ';
$('.CacheDetailNavigation ul li:first').append(html);
}
// Add map links for each bookmarklist
if(IsSettingEnabled('addMapBookmarkListLinks')) {
$('ul.BookmarkList li').each(function() {
var guid = $(this).children(':nth-child(1)').attr('href').replace(/.*\?guid=(.*)/, "$1");
var owner = $(this).children(':nth-child(3)').text();
// Add the map link
var url = 'http://project-gc.com/Tools/MapBookmarklist?owner_name=' + encodeURIComponent(owner) + '&guid=' + encodeURIComponent(guid);
$(this).children(':nth-child(1)').append( ' ' );
// Add gallery link for the bookmark list
var url = 'http://project-gc.com/Tools/Gallery?bml_owner=' + encodeURIComponent(owner) + '&bml_guid=' + encodeURIComponent(guid) +'&submit=Filter';
$(this).children(':nth-child(1)').append( ' ' );
// Add profile stats link to the owner
var url = 'http://project-gc.com/ProfileStats/' + encodeURIComponent(owner);
$(this).children(':nth-child(3)').append( ' ' );
});
}
// Decrypt the hint
unsafeWindow.dht();
// VGPS form
if(IsSettingEnabled('showVGPS')) {
GM_xmlhttpRequest({
method: "GET",
url: pgcApiUrl + 'GetExistingVGPSLists?gccode=' + gccode,
onload: function(response) {
var result = JSON.parse(response.responseText),
vgpsLists = result.data.lists,
selected = result.data.selected,
existsIn = result.data.existsIn,
selectedContent,
existsContent,
html = '
Add to VGPS ',
listId, list;
html += '';
if(existsIn.indexOf( String(selected) ) == -1) {
html += ' ';
html += ' ';
} else {
html += ' ';
html += ' ';
}
html += '
';
$('div.CacheDetailNavigation ul:first').append(html);
$('#comboVGPS').change(function(event) {
selected = $(this).find(':selected').val();
if(existsIn.indexOf( String(selected) ) == -1) {
$('#btnAddToVGPS').css('display', '');
$('#btnRemoveFromVGPS').css('display', 'none');
} else {
$('#btnAddToVGPS').css('display', 'none');
$('#btnRemoveFromVGPS').css('display', '');
}
});
$('#btnAddToVGPS').click(function(event) {
event.preventDefault();
addToVGPS();
});
$('#btnRemoveFromVGPS').click(function(event) {
event.preventDefault();
removeFromVGPS();
});
}
});
}
}
function Page_Logbook() {
// Since everything in the logbook is ajax, we need to wait for the elements
waitForKeyElements('#AllLogs tr', Logbook);
waitForKeyElements('#PersonalLogs tr', Logbook);
waitForKeyElements('#FriendLogs tr', Logbook);
}
function Logbook(jNode) {
// Add Profile stats and gallery links after each user
if(IsSettingEnabled('profileStatsLinks')) {
var profileNameElm = $(jNode).find('p.logOwnerProfileName strong a');
var profileName = profileNameElm.html();
if (typeof profileName !== 'undefined') {
profileName = profileNameElm.append('')
.append('');
}
}
// Save to latest logs
if (latestLogs.length < 5) {
var logType = $(jNode).find('div.LogType strong img').attr('src');
// First entry is undefined, due to ajax
if(logType) {
latestLogs.push('');
// 2 = found, 3 = dnf, 4 = note, 5 = archive, 22 = disable, 24 = publish, 45 = nm, 46 = owner maintenance, 68 = reviewer note
var logTypeId = logType.replace(/.*logtypes\/(.*)\.png/, "$1");
if(latestLogs.length == 1) {
if(logTypeId == 3 || logTypeId == 5 || logTypeId == 22 || logTypeId == 45 || logTypeId == 68) {
latestLogsAlert = true;
}
}
}
// Show latest logs
if(IsSettingEnabled('addLatestLogs')) {
if (latestLogs.length == 5) {
var images = latestLogs.join('');
$('#ctl00_ContentBody_size p').removeClass('AlignCenter').addClass('NoBottomSpacing');
if(latestLogsAlert) {
$('#ctl00_ContentBody_size').append('