Greasy Fork is available in English.

Geocaching.com + Project-GC

Adds links and data to Geocaching.com to make it collaborate with PGC

2021-06-01 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

  1. /* global $: true */
  2. /* global waitForKeyElements: true */
  3. /* global GM_xmlhttpRequest: true */
  4. /* global GM_getValue: true */
  5. /* global GM_setValue: true */
  6. /* global unsafeWindow: true */
  7. // jshint newcap:false
  8. // jshint multistr:true
  9.  
  10. // ==UserScript==
  11. // @name Geocaching.com + Project-GC
  12. // @namespace PGC
  13. // @description Adds links and data to Geocaching.com to make it collaborate with PGC
  14. // @icon https://project-gc.com/favicon-32x32.png
  15. // @include http://www.geocaching.com/*
  16. // @include https://www.geocaching.com/*
  17. // @exclude https://www.geocaching.com/profile/profilecontent.html
  18. // @version 2.3.5
  19. // @require http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js
  20. // @require https://greatest.deepsurf.us/scripts/5392-waitforkeyelements/code/WaitForKeyElements.js
  21. // @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
  22. // @grant GM_xmlhttpRequest
  23. // @grant GM_setValue
  24. // @grant GM_getValue
  25. // @grant GM_addStyle
  26. // @grant GM.xmlHttpRequest
  27. // @grant GM.setValue
  28. // @grant GM.getValue
  29. // @connect maps.googleapis.com
  30. // @connect project-gc.com
  31. // @connect img.geocaching.com
  32. // @connect s3.amazonaws.com
  33. // @connect nominatim.openstreetmap.org
  34. // @connect *
  35. // @license The MIT License (MIT)
  36. // ==/UserScript==
  37.  
  38.  
  39. (function() {
  40.  
  41. 'use strict';
  42.  
  43. var pgcUrl = 'https://project-gc.com/',
  44. cdnDomain = 'https://cdn2.project-gc.com/',
  45. pgcApiUrl = pgcUrl + 'api/gm/v1/',
  46. externalLinkIcon = 'https://cdn2.project-gc.com/images/external_small.png',
  47. galleryLinkIcon = 'https://cdn2.project-gc.com/images/pictures_16.png',
  48. challengeCheckerSuccessIcon = 'https://cdn2.project-gc.com/images/check16.png',
  49. challengeCheckerFailIcon = 'https://cdn2.project-gc.com/images/cancel16.png',
  50. mapLinkIcon = 'https://cdn2.project-gc.com/images/map_app_16.png',
  51. loggedIn = null,
  52. subscription = null,
  53. pgcUsername = null,
  54. gccomUsername = null,
  55. latestLogs = [],
  56. latestLogsAlert = false,
  57. settings = {},
  58. path = window.location.pathname,
  59. challengeCheckerResults = null;
  60.  
  61. // Don't run the script for iframes
  62. if (window.top == window.self) {
  63. Main();
  64. }
  65.  
  66. function Main() {
  67. ReadSettings();
  68. CheckPGCLogin();
  69. }
  70.  
  71. function Router() {
  72. if (path.match(/^\/geocache\/.*/) !== null) {
  73. Page_CachePage();
  74. } else if (path.match(/^\/seek\/cache_details\.aspx.*/) !== null) {
  75. Page_CachePage();
  76. } else if (path.match(/^\/seek\/cache_logbook\.aspx.*/) !== null) {
  77. Page_Logbook();
  78. } else if (path.match(/^\/bookmarks\/.*/) !== null) {
  79. Page_Bookmarks();
  80. } else if (path.match(/^\/map\/.*/) !== null) {
  81. Page_Map();
  82. } else if(path.match(/^\/seek\/gallery\.aspx.*/) !== null) {
  83. Page_Gallery();
  84. } else if(path.match(/^\/profile\/.*/) !== null) {
  85. Page_Profile();
  86. } else if (path.match(/^\/account\/drafts/) !== null) {
  87. Page_Drafts();
  88. } else if (path.match(/^\/account\/messagecenter/) !== null) {
  89. Page_Messagecenter();
  90. } else if (path.match(/^\/seek\/cdpf\.aspx/) !== null) {
  91. Page_PrintCachePage();
  92. }
  93. }
  94.  
  95. function GetSettingsItems() {
  96. var items = {
  97. showVGPS: {
  98. title: 'Show Virtual GPS',
  99. default: true
  100. },
  101. addChallengeCheckers: {
  102. title: 'Add challenge checkers',
  103. default: true
  104. },
  105. makeCopyFriendly: {
  106. title: 'Make copy friendly GC-Code and link',
  107. default: true
  108. },
  109. addPgcMapLinks: {
  110. title: 'Add PGC map links',
  111. default: true
  112. },
  113. addLatestLogs: {
  114. title: 'Add latest logs',
  115. default: true
  116. },
  117. cloneLogsPerType: {
  118. title: 'Clone number of logs per type',
  119. default: true
  120. },
  121. addPGCLocation: {
  122. title: 'Add PGC Location',
  123. default: true
  124. },
  125. addAddress: {
  126. title: 'Add OSM reverse geocoded address',
  127. default: true
  128. },
  129. removeUTM: {
  130. title: 'Remove UTM coordinates',
  131. default: true
  132. },
  133. addPgcFp: {
  134. title: 'Add FP from PGC',
  135. default: true
  136. },
  137. showWeekday: {
  138. title: 'Show weekday of the place date',
  139. default: true
  140. },
  141. profileStatsLinks: {
  142. title: 'Add links to Profile stats',
  143. default: true
  144. },
  145. tidy: {
  146. title: 'Tidy the web a bit',
  147. default: true
  148. },
  149. collapseDownloads: {
  150. title: 'Collapse download links',
  151. default: false
  152. },
  153. addPgcGalleryLinks: {
  154. title: 'Add links to PGC gallery',
  155. default: true
  156. },
  157. addMapBookmarkListLinks: {
  158. title: 'Add links for bookmark lists',
  159. default: true
  160. },
  161. decryptHints: {
  162. title: 'Automatically decrypt hints',
  163. default: true
  164. },
  165. addElevation: {
  166. title: 'Add elevation',
  167. default: true
  168. },
  169. imperial: {
  170. title: 'Use imperial units',
  171. default: false
  172. },
  173. removeDisclaimer: {
  174. title: 'Remove disclaimer',
  175. default: false
  176. },
  177. parseExifLocation: {
  178. title: 'Parse Exif location',
  179. default: true
  180. },
  181. addGeocacheLogsPerProfileCountry: {
  182. title: 'Geocachelogs per profile country',
  183. default: true
  184. },
  185. openDraftLogInSameWindow: {
  186. title: 'Open <em>Compose Log</em> entries in <em>Drafts</em> in same window',
  187. default: true
  188. },
  189. cachenoteFont: {
  190. title: 'Change personal cache note font to monospaced',
  191. default: true
  192. },
  193. logbookLinks: {
  194. title: 'Add links to logbook tabs',
  195. default: true
  196. },
  197. addMyNumberOfLogs: {
  198. title: 'Add my number of logs above log button',
  199. default: true
  200. },
  201. hideMapFromPrintCachePage: {
  202. title: 'Hide map from print cache page',
  203. default: true
  204. },
  205. addCachedChallengeCheckerResults: {
  206. title: 'Add icons for cached Challenge checker results',
  207. default: true
  208. },
  209. hideLogVoting: {
  210. title: 'Hide log upvote buttons and sorting options',
  211. default: false
  212. }
  213. };
  214. return items;
  215. }
  216.  
  217. async function ReadSettings() {
  218. settings = await GM.getValue('settings');
  219. if (typeof(settings) != 'undefined') {
  220. settings = JSON.parse(settings);
  221. if (settings === null) {
  222. settings = [];
  223. }
  224. } else {
  225. settings = [];
  226. }
  227.  
  228. var items = GetSettingsItems();
  229. for (var item in items) {
  230. if (typeof(settings[item]) == 'undefined') {
  231. settings[item] = items[item].default;
  232. }
  233. }
  234. }
  235.  
  236. function SaveSettings(e) {
  237. e.preventDefault();
  238. settings = {};
  239.  
  240. for (var item in GetSettingsItems()) {
  241. settings[item] = Boolean($('#pgcUserMenuForm input[name="' + item + '"]').is(':checked'));
  242. }
  243.  
  244. var json = JSON.stringify(settings);
  245. GM.setValue('settings', json);
  246.  
  247. $('#pgcUserMenuWarning').css('display', 'inherit');
  248. }
  249.  
  250. function IsSettingEnabled(setting) {
  251. return settings[setting];
  252. }
  253.  
  254. function MetersToFeet(meters) {
  255. return Math.round(meters * 3.28084);
  256. }
  257.  
  258. function FormatDistance(distance) {
  259. distance = parseInt(distance, 10);
  260. distance = IsSettingEnabled('imperial') ? MetersToFeet(distance) : distance;
  261. distance = distance.toLocaleString();
  262.  
  263. return distance;
  264. }
  265.  
  266. function GetCoordinatesFromExif(exif) {
  267. var GPSLatitudeRef = EXIF.getTag(exif, "GPSLatitudeRef"),
  268. GPSLatitude = EXIF.getTag(exif, "GPSLatitude"),
  269. GPSLongitudeRef = EXIF.getTag(exif, "GPSLongitudeRef"),
  270. GPSLongitude = EXIF.getTag(exif, "GPSLongitude");
  271.  
  272. if (typeof(GPSLatitude) === 'undefined' || isNaN(GPSLatitude[0]) || isNaN(GPSLatitude[1]) || isNaN(GPSLatitude[1]) ||
  273. isNaN(GPSLongitude[0]) || isNaN(GPSLongitude[1]) || isNaN(GPSLongitude[1])) {
  274. return false;
  275. }
  276.  
  277. // Create a latitude DD.DDD
  278. var tmp = Number(GPSLatitude[0]) + Number(GPSLatitude[1]) / 60 + Number(GPSLatitude[2]) / 60 / 60,
  279. coords = '';
  280.  
  281. coords += GPSLatitudeRef;
  282. var d = Math.floor(tmp);
  283. if (d < 10) {
  284. coords += '0' + d;
  285. } else {
  286. coords += d;
  287. }
  288. tmp = (tmp - d) * 60;
  289. coords += ' ' + padLeft(tmp.toFixed(3), 6);
  290.  
  291. coords += ' ';
  292.  
  293. // Create a longitude DD.DDD
  294. var tmp = Number(GPSLongitude[0]) + Number(GPSLongitude[1]) / 60 + Number(GPSLongitude[2]) / 60 / 60;
  295.  
  296. coords += GPSLongitudeRef;
  297. var d = Math.floor(tmp);
  298. if (d < 10) {
  299. coords += '00' + d;
  300. } else if (GPSLongitude[0] < 100) {
  301. coords += '0' + d;
  302. } else {
  303. coords += d;
  304. }
  305. tmp = (tmp - d) * 60;
  306. coords += ' ' + padLeft(tmp.toFixed(3), 6);
  307.  
  308. return coords;
  309. }
  310.  
  311. /**
  312. * Check that we are authenticated at Project-GC.com, and that it's with the same username
  313. */
  314. function CheckPGCLogin() {
  315. GM.xmlHttpRequest({
  316. method: "GET",
  317. url: pgcApiUrl + 'GetMyUsername',
  318. onload: function(response) {
  319. var result = JSON.parse(response.responseText);
  320.  
  321. if (result.status !== 'OK') {
  322. alert(response.responseText);
  323. return false;
  324. }
  325.  
  326. pgcUsername = result.data.username;
  327. loggedIn = Boolean(result.data.loggedIn);
  328. subscription = Boolean(result.data.subscription);
  329.  
  330. function waitForHeader(waitCount) {
  331. if ($('.user-menu')[0]) BuildPGCUserMenu();
  332. else {waitCount++; if (waitCount <= 1000) setTimeout(function(){waitForHeader(waitCount);}, 10);}
  333. }
  334. waitForHeader(0);
  335. Router();
  336. },
  337. onerror: function(response) {
  338. alert(response);
  339. return false;
  340. }
  341. });
  342. }
  343.  
  344. function BuildPGCUserMenu() {
  345. var loggedInContent, subscriptionContent = '';
  346.  
  347. gccomUsername = false;
  348. if ($('.username')[0]) {
  349. gccomUsername = $('.username').html();
  350. }
  351.  
  352. if (loggedIn === false) {
  353. loggedInContent = '<a href="' + pgcUrl + 'User/Login" target="_blank">Not logged in</a>';
  354. } else {
  355. loggedInContent = '<a href="' + pgcUrl + 'ProfileStats/' + pgcUsername + '"><strong' + (pgcUsername != gccomUsername ? ' style="color: red;"' : '') + '>' + pgcUsername + '</strong></a>';
  356. subscriptionContent = '<a href="https://project-gc.com/Home/Membership" target="_blank">' + (subscription ? 'Paid' : 'Missing') + ' membership</a>';
  357. }
  358.  
  359. GM_addStyle('\
  360. #pgc .player-profile, #pgc_gclh .li-user-info {width: auto;}\
  361. #pgc .player-profile:hover {text-decoration: none;}\
  362. #pgc .player-profile a:hover {text-decoration: underline;}\
  363. #pgc .player-profile a {text-decoration: none;color: white;}\
  364. #pgc_gclh img:hover {cursor:pointer;}\
  365. #pgc_gclh .draft-indicator {display: none;}\
  366. #pgcUserMenuForm > li:hover, #pgcUserMenuForm_gclh > li:hover { background-color: #e3dfc9; }\
  367. #pgcUserMenuForm > li, #pgcUserMenuForm_gclh > li { display: block; }\
  368. #pgcUserMenuForm input[type="checkbox"], #pgcUserMenuForm_gclh input[type="checkbox"] { opacity: inherit; width: inherit; height:inherit; overflow:inherit; position:inherit; }\
  369. #pgcUserMenuForm button, #pgcUserMenuForm_gclh button { display: inline-block !important; background: #ede5dc url(images/ui-bg_flat_100_ede5dc_40x100.png) 50% 50% repeat-x !important; border: 1px solid #cab6a3 !important; border-radius: 4px; color: #584528 !important; text-decoration: none; width: auto !important; font-size: 14px; padding: 4px 6px !important;}\
  370. #pgcUserMenuForm button:hover, #pgcUserMenuForm_gclh button:hover { background: #e4d8cb url(images/ui-bgflag_100_e4d8cb_40x100.png) 50% 50% repeat-x !important; }\
  371. #pgcUserMenu, #pgcUserMenu_gclh { right: 19rem; }\
  372. #pgcUserMenu > form, #pgcUserMenu_gclh > form { background-color: white; color: #5f452a; }\
  373. .profile-panel .li-user-info {min-width: 160px;}\
  374. ');
  375.  
  376. var settings = '<ul id="pgcUserMenu" class="dropdown-menu menu-user submenu" style="display:none; z-index: 1005;"><form id="pgcUserMenuForm" style="display: block; columns: 2; font-size: 14px; background-color: #fff !important;">';
  377.  
  378. var items = GetSettingsItems();
  379. for (var item in items) {
  380. let isChecked = IsSettingEnabled(item) ? ' checked="checked"' : '';
  381. // Explicitly set the styles as some pages (i.e. https://www.geocaching.com/account/settings/profile) are missing the required css.
  382. settings += '<li style="margin: .2em 1em; white-space: nowrap; display: flex;"><label style="font-weight: inherit; margin-bottom: 0" for="' + item + '"><input type="checkbox" id="' + item + '" name="' + item + '"' + isChecked + ' >&nbsp;' + items[item].title + '</label>&nbsp;<small>(default: ' + items[item].default + ')</small></li>';
  383. }
  384.  
  385. settings += '\
  386. <li style="margin: .2em 1em; background: 0;">\
  387. <button onclick="document.getElementById(\'pgcUserMenuForm\').reset(); document.getElementById(\'pgcUserMenu\').style.display=\"none\"; return false;">Cancel</button>\
  388. <button onclick="document.getElementById(\'pgcUserMenuForm\').reset(); return false;">Reset</button>\
  389. <button id="pgcUserMenuSave">Save</button>\
  390. </li>\
  391. <li id="pgcUserMenuWarning" style="display: none; margin: .5em 1em; color: red; background: 0;"><a href="#" onclick="location.reload();" style="color: red; padding: 0; text-decoration: underline; display: inline;">Reload</a> the page to activate the new settings.</li>\
  392. </form>\
  393. </ul>';
  394.  
  395. let pgc = '<li id="pgc"><div class="player-profile">' + $($('.user-menu li')[1]).find('a').html() + '</div></li>';
  396. $('.user-menu').prepend(pgc);
  397. // Icon
  398. $('#pgc div').prepend('<a href="' + pgcUrl + '"></a>');
  399. $('#pgc img').attr('src', 'https://cdn2.project-gc.com/favicon.ico');
  400. $('#pgc img').attr('style', 'border-radius:100%;');
  401. $('#pgc img').appendTo('#pgc a');
  402. // Username
  403. $('#pgc .username').html(loggedInContent);
  404. // Subscription
  405. $('#pgc .username + span').html(subscriptionContent);
  406.  
  407. // Menu Toggle
  408. let button = $($('.user-menu li')[3]).clone();
  409. $(button).find('button').attr('id', 'pgcUserMenuButton');
  410. $(button).append(settings);
  411. // Add Toggle Button
  412. $('#pgc').after(button);
  413.  
  414. $("#pgcUserMenuButton").click(function(e) {
  415. $('#pgcUserMenu').show();
  416. })
  417. $('body').click(function(e) {
  418. if (e.target != $("#pgcUserMenuButton")[0] && e.target != $("#pgcUserMenuButton svg")[0] && e.target != $("#pgcUserMenuButton svg use")[0]) {
  419. $("#pgcUserMenu").hide();
  420. }
  421. })
  422.  
  423. $('#pgcUserMenuSave').click(function(e) {
  424. SaveSettings(e);
  425. });
  426.  
  427. // Workaroud for users that also use the GClh
  428. function checkForGClh(waitCount) {
  429. if ($('#GClh_II_running')[0] && $('gclh_nav#ctl00_gcNavigation')[0]) {
  430. let gclh_pgc = '<li id="pgc_gclh" class="li-user"><div class="li-user-info">' + $($('.li-user')[0]).find('a').html() + '</div>'
  431. + '<button id="pgcUserMenuButton_gclh" class="li-user-toggle dropdown">' + $($('.li-user')[0]).find('button').html() + '</button>'
  432. + settings + '</li>';
  433. $('#ctl00_uxLoginStatus_divSignedIn').prepend(gclh_pgc);
  434. // Icon
  435. $('#pgc_gclh img').attr('src', 'https://cdn2.project-gc.com/favicon.ico');
  436. $('#pgc_gclh img').attr('style', 'border-radius:100%;');
  437. $('#pgc_gclh img')[0].onclick = function() {open(pgcUrl);};
  438. // User
  439. $('#pgc_gclh .user-name').html(loggedInContent);
  440. // Subscription
  441. $('#pgc_gclh .cache-count').html(subscriptionContent);
  442.  
  443.  
  444. // Rename the settings
  445. $('#pgc_gclh .dropdown-menu.menu-user').attr('id', 'pgcUserMenu_gclh');
  446. $('#pgc_gclh .dropdown-menu.menu-user form').attr('id', 'pgcUserMenuForm_gclh');
  447. $('#pgc_gclh .dropdown-menu.menu-user form li:nth-last-child(2) button:nth-last-child(1)').attr('id', 'pgcUserMenuSave_gclh');
  448. $('#pgc_gclh .dropdown-menu.menu-user form li:nth-last-child(1)').attr('id', 'pgcUserMenuWarning_gclh');
  449.  
  450. $("#pgcUserMenuButton_gclh").click(function(e) {
  451. console.log('click')
  452. $('#pgcUserMenu_gclh').toggle();
  453. })
  454.  
  455. $('#pgcUserMenuSave_gclh').click(function(e) {
  456. SaveSettings(e);
  457. });
  458.  
  459. } else {waitCount++; if (waitCount <= 1000) setTimeout(function(){checkForGClh(waitCount);}, 10);}
  460. }
  461. checkForGClh(0);
  462. }
  463.  
  464. /**
  465. * getGcCodeFromPage
  466. * @return string
  467. */
  468. function getGcCodeFromPage() {
  469. return $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoCode').html();
  470. }
  471.  
  472. /**
  473. * addToVGPS
  474. */
  475. function addToVGPS(gccode) {
  476. var listId = $('#comboVGPS').val(),
  477. url = null;
  478.  
  479. if (typeof(gccode) === 'undefined') { // The map provides the gccode itself
  480. gccode = getGcCodeFromPage();
  481. }
  482.  
  483. url = pgcApiUrl + 'AddToVGPSList?listId=' + listId + '&gccode=' + gccode + '&sectionName=GM-script';
  484.  
  485.  
  486. GM.xmlHttpRequest({
  487. method: "GET",
  488. url: url,
  489. onload: function(response) {
  490. var result = JSON.parse(response.responseText),
  491. msg = (result.status === 'OK') ? 'Geocache added to Virtual-GPS!' : 'Geocache not added to Virtual-GPS :(';
  492.  
  493. $('#btnAddToVGPS').css('display', 'none');
  494. $('#btnRemoveFromVGPS').css('display', '');
  495.  
  496. alert(msg);
  497.  
  498. return true;
  499. },
  500. onerror: function(response) {
  501. console.log(response);
  502. return false;
  503. }
  504. });
  505. return true;
  506. }
  507.  
  508. /**
  509. * removeFromVGPS
  510. */
  511. function removeFromVGPS(gccode) {
  512. var listId = $('#comboVGPS').val(),
  513. url = null;
  514.  
  515. if (typeof(gccode) === 'undefined') { // The map provides the gccode itself
  516. gccode = getGcCodeFromPage();
  517. }
  518.  
  519. url = pgcApiUrl + 'RemoveFromVGPSList?listId=' + listId + '&gccode=' + gccode;
  520.  
  521.  
  522. GM.xmlHttpRequest({
  523. method: "GET",
  524. url: url,
  525. onload: function(response) {
  526. var result = JSON.parse(response.responseText),
  527. msg = (result.status === 'OK') ? 'Geocache removed from Virtual-GPS!' : 'Geocache not removed from Virtual-GPS :(';
  528.  
  529. $('#btnAddToVGPS').css('display', '');
  530. $('#btnRemoveFromVGPS').css('display', 'none');
  531.  
  532. alert(msg);
  533.  
  534. return true;
  535. },
  536. onerror: function(response) {
  537. console.log(response);
  538. return false;
  539. }
  540. });
  541. }
  542.  
  543. function Page_Profile() {
  544. // Override gc.com function on alerting for external links to not alert for Project-GC URLs
  545. var gcAlertOverride = document.createElement('script');
  546. gcAlertOverride.type = "text/javascript";
  547. gcAlertOverride.innerHTML = `(function() {
  548. var _old_isGeocachingDomain = isGeocachingDomain;
  549. isGeocachingDomain = function(url) {
  550. return (_old_isGeocachingDomain.apply(this, arguments)
  551. || url == "project-gc.com"
  552. || url == "www.project-gc.com");
  553. };
  554. })();`;
  555. document.getElementsByTagName('head')[0].appendChild(gcAlertOverride);
  556. }
  557.  
  558. /**
  559. * Page_CachePage
  560. */
  561. function Page_CachePage() {
  562. var gccode = getGcCodeFromPage(),
  563. placedBy = $('#ctl00_ContentBody_mcd1 a').html(),
  564. lastUpdated = $('#ctl00_ContentBody_bottomSection p small time').get(1),
  565. lastFound = $('#ctl00_ContentBody_bottomSection p small time').get(2),
  566. coordinates, latitude, longitude, url;
  567.  
  568. lastUpdated = (lastUpdated) ? lastUpdated.dateTime : false;
  569. lastFound = (lastFound) ? lastFound.dateTime : false;
  570.  
  571. if (subscription) {
  572.  
  573. // Get geocache data from Project-GC
  574. url = pgcApiUrl + 'GetCacheDataFromGccode&gccode=' + gccode;
  575. if (lastUpdated)
  576. url += '&lastUpdated=' + lastUpdated;
  577. if (lastFound)
  578. url += '&lastFound=' + lastFound;
  579.  
  580. GM.xmlHttpRequest({
  581. method: "GET",
  582. url: url,
  583. onload: function(response) {
  584. var result = JSON.parse(response.responseText),
  585. cacheData = result.data.cacheData,
  586. bearing = result.data.bearing,
  587. cacheOwner = result.data.owner,
  588. challengeCheckerTagIds = result.data.challengeCheckerTagIds,
  589. geocacheLogsPerCountry = result.data.geocacheLogsPerCountry,
  590. myNumberOfLogs = result.data.myNumberOfLogs,
  591. location = [],
  592. fp = 0,
  593. fpp = 0,
  594. fpw = 0,
  595. elevation = '',
  596. html = '';
  597.  
  598.  
  599. challengeCheckerResults = result.data.challengeCheckerResults;
  600.  
  601. // Add an alert in top if there are Found it-logs which doesn't seem to fulfill the requirements
  602. if(challengeCheckerResults !== false) {
  603. var suspiciousFoundItLogs = [];
  604. for(var logId in challengeCheckerResults) {
  605. if(typeof challengeCheckerResults[logId] !== 'undefined' && challengeCheckerResults[logId]['status'] == 'fail') {
  606. suspiciousFoundItLogs.push(logId);
  607. }
  608. }
  609.  
  610. if(suspiciousFoundItLogs.length != 0) {
  611. var suspiciousFoundItLog = '<p style="color: #ff6c00;" class=" NoBottomSpacing"><strong>Cache Issues:</strong></p>\
  612. <ul style="color: #ff6c00;" class="">\
  613. <li>The following Found it logs might not fulfill the requirements:<br>';
  614.  
  615. for(var i = 0 ; i < suspiciousFoundItLogs.length ; i++) {
  616. suspiciousFoundItLog = suspiciousFoundItLog + ' <a href="https://www.geocaching.com/seek/log.aspx?LID=' + suspiciousFoundItLogs[i] + '">' + challengeCheckerResults[suspiciousFoundItLogs[i]]['profileName'] + '</a><br>';
  617. }
  618. suspiciousFoundItLog = suspiciousFoundItLog + 'Please understand that the checker result is a cached result. Also the geocacher might very well have fulfilled it in the past, external factors might have changed.</li></ul>';
  619.  
  620. $('div.span-6.right.last').last().next().after(suspiciousFoundItLog);
  621. }
  622. }
  623. //--
  624.  
  625.  
  626. if (result.status == 'OK' && typeof cacheData !== 'undefined') {
  627.  
  628. // If placed by != owner, show the real owner as well.
  629. if (placedBy !== cacheOwner) {
  630. $('#ctl00_ContentBody_mcd1 span.message__owner').before(' (' + cacheOwner + ')');
  631. }
  632.  
  633. // Append link to Profile Stats for the cache owner
  634. // Need to real cache owner name from PGC since the web only has placed by
  635. if (IsSettingEnabled('profileStatsLinks')) {
  636. $('#ctl00_ContentBody_mcd1 span.message__owner').before('<a href="' + pgcUrl + 'ProfileStats/' + encodeURIComponent(cacheOwner) + '"><img src="' + externalLinkIcon + '" title="PGC Profile Stats"></a>');
  637. }
  638.  
  639. // Add FP/FP%/FPW below the current FP
  640. if (IsSettingEnabled('addPgcFp')) {
  641. fp = parseInt(+cacheData.favorite_points, 10),
  642. fpp = parseInt(+cacheData.favorite_points_pct, 10),
  643. fpw = parseInt(+cacheData.favorite_points_wilson, 10);
  644. $('#uxFavContainerLink').append('<p style="text-align: center; background-color: #f0edeb;border-bottom-left-radius: 5px;border-bottom-right-radius:5px;">PGC: ' + fp + ' FP, ' + fpp + '%, ' + fpw + 'W</p>');
  645. $('.favorite-container').css({
  646. "border-bottom-left-radius": "0",
  647. "border-bottom-right-radius": "0"
  648. });
  649. }
  650.  
  651. // Add elevation (Metres above mean sea level = mamsl)
  652. if (IsSettingEnabled('addElevation')) {
  653. var formattedElevation = FormatDistance(cacheData.elevation),
  654. elevationUnit = IsSettingEnabled('imperial') ? 'ft' : 'm',
  655. elevationArrow = (cacheData.elevation >= 0) ? '&#x21a5;' : '&#x21a7;';
  656. elevation = formattedElevation + ' ' + elevationUnit + ' ' + elevationArrow;
  657.  
  658. if (cacheData.elevation >= 0) {
  659. html = '<span> (' + elevation + ')</span>';
  660. } else {
  661. html = '<span class="OldWarning"> (' + elevation + ')</span>';
  662. }
  663.  
  664. ($('#uxLatLonLink').length > 0 ? $('#uxLatLonLink') : $('#uxLatLon').parent()).after(html);
  665. }
  666.  
  667. // Add PGC location
  668. if (IsSettingEnabled('addPGCLocation')) {
  669. if (cacheData.country.length > 0) {
  670. location.push(cacheData.country);
  671. }
  672. if (cacheData.region !== null && cacheData.region.length > 0) {
  673. location.push(cacheData.region);
  674. }
  675. if (cacheData.county !== null && cacheData.county.length > 0) {
  676. location.push(cacheData.county);
  677. }
  678. location = location.join(' / ');
  679.  
  680. var gccomLocationData = $('#ctl00_ContentBody_Location').html();
  681. $('#ctl00_ContentBody_Location').html('<span style="text-decoration: line-through;">' + gccomLocationData + '</span><br><span>' + location + '</span>');
  682. }
  683.  
  684. // Add bearing from home
  685. $('#lblDistFromHome').append(' <span>(' + Math.round(bearing*10)/10 + '&deg;)</span>');
  686.  
  687. // Add challenge checkers
  688. if (IsSettingEnabled('addChallengeCheckers') && challengeCheckerTagIds.length > 0) {
  689. html = '<div id="checkerWidget" class="CacheDetailNavigationWidget TopSpacing BottomSpacing"><h3 class="WidgetHeader">Challenge checker(s)</h3><div class="WidgetBody" id="PGC_ChallengeCheckers">';
  690. for (var i = 0; i < challengeCheckerTagIds.length; i++) {
  691. html += '<a href="https://project-gc.com/Challenges/' + gccode + '/' + challengeCheckerTagIds[i] + '" style="display: block; width: 200px; margin: 0 auto;"><img src="https://cdn2.project-gc.com/Images/Checker/' + challengeCheckerTagIds[i] + '" title="Project-GC Challenge checker" alt="PGC Checker"></a>';
  692. }
  693. html += '</div></div>';
  694. $('#ctl00_ContentBody_detailWidget').before(html);
  695. }
  696.  
  697. // Display warning message if cache is logged and no longer be logged
  698. if (cacheData.locked) {
  699. $('ul.OldWarning').append('<li>This cache has been locked and can no longer be logged.</li>');
  700. }
  701.  
  702. // Add geocache logs per profile country table
  703. if (IsSettingEnabled('addGeocacheLogsPerProfileCountry')) {
  704. html = '<div id="geocacheLogsPerCountry" style="border: dashed; border-color: #aaa; border-width: thin;">';
  705.  
  706. if(typeof(geocacheLogsPerCountry['willAttend']) != 'undefined' && geocacheLogsPerCountry['willAttend'].length > 0) {
  707. html += '<p style="margin-left: 10px; margin-bottom: 0;"><strong>Will attend logs per country</strong> <small>according to Project-GC.com</small></p>';
  708. html += '<ul style="list-style: none; margin-left: 0; margin-bottom: 0;">';
  709. for (var i = 0; i < geocacheLogsPerCountry['willAttend'].length; i++) {
  710. html += '<li style="display: inline; padding-right: 20px;"><span style="display: inline-block;"><img src="' + cdnDomain + geocacheLogsPerCountry['willAttend'][i].flagIcon + '" alt="' + $('<div/>').text(geocacheLogsPerCountry['willAttend'][i].country).html() + '" title="' + $('<div/>').text(geocacheLogsPerCountry['willAttend'][i].country).html() + '"> ' + geocacheLogsPerCountry['willAttend'][i].cnt + '</span></li>';
  711. }
  712. html += '</ul>';
  713. html += '<span style="display: block; text-align: right; padding-right: 10px;"><small>' + geocacheLogsPerCountry['willAttend'].length + ' unique countries</small></span>';
  714. html += '<span style="display: block; text-align: right; padding-right: 10px;"><small><a href="https://project-gc.com/Tools/EventStatistics?gccode=' + encodeURIComponent(gccode) + '">Event statistics</a></small></span>';
  715. }
  716.  
  717. if(typeof(geocacheLogsPerCountry['found']) != 'undefined' && geocacheLogsPerCountry['found'].length > 0) {
  718. html += '<p style="margin-left: 10px; margin-bottom: 0;"><strong>Found logs per country</strong> <small>according to Project-GC.com</small></p>';
  719. html += '<ul style="list-style: none; margin-left: 0; margin-bottom: 0;">';
  720. for (var i = 0; i < geocacheLogsPerCountry['found'].length; i++) {
  721. html += '<li style="display: inline; padding-right: 20px;"><span style="display: inline-block;"><img src="' + cdnDomain + geocacheLogsPerCountry['found'][i].flagIcon + '" alt="' + $('<div/>').text(geocacheLogsPerCountry['found'][i].country).html() + '" title="' + $('<div/>').text(geocacheLogsPerCountry['found'][i].country).html() + '"> ' + geocacheLogsPerCountry['found'][i].cnt + '</span></li>';
  722. }
  723. html += '</ul>';
  724. html += '<span style="display: block; text-align: right; padding-right: 10px;"><small>' + geocacheLogsPerCountry['found'].length + ' unique countries</small></span>';
  725. }
  726.  
  727. html += '</div>';
  728.  
  729. $('#ctl00_ContentBody_lblFindCounts').append(html);
  730. }
  731.  
  732. // Add my number of logs above the log button
  733. if (IsSettingEnabled('addMyNumberOfLogs')) {
  734. $('<p style="margin: 0;"><small>You have ' + myNumberOfLogs + ' logs according to Project-GC</small></p>').insertBefore('#ctl00_ContentBody_GeoNav_logButton');
  735. }
  736.  
  737. // Append the same number to the added logbook link
  738. if (IsSettingEnabled('logbookLinks')) {
  739. $('#pgc-logbook-yours').html('Yours (' + myNumberOfLogs + ')')
  740.  
  741. }
  742. }
  743.  
  744.  
  745. // Since everything in the logbook is ajax, we need to wait for the elements
  746. // We also want to wait on challengeCheckerResults
  747. waitForKeyElements('#cache_logs_table tbody tr', Logbook);
  748. }
  749. });
  750. }
  751.  
  752. // Add weekday of place date
  753. if (IsSettingEnabled('showWeekday')) {
  754. var match = $('meta[name="description"]')[1].content.match(/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/);
  755. if (match) {
  756. var date = new Date(match[3], match[1]-1, match[2]);
  757. var weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  758. var text = $($('#ctl00_ContentBody_mcd2')[0].childNodes[0]).text();
  759. var pos = text.indexOf(':') + 2;
  760. var newText = text.substring(0, pos);
  761. newText += weekday[date.getDay()] + ', ';
  762. newText += text.substring(pos, text.length);
  763. var newNode = document.createTextNode(newText);
  764. $('#ctl00_ContentBody_mcd2')[0].replaceChild(newNode, $('#ctl00_ContentBody_mcd2')[0].childNodes[0]);
  765. }
  766. }
  767.  
  768. // Tidy the web
  769. if (IsSettingEnabled('tidy')) {
  770. $('#ctl00_divContentMain p.Clear').css('margin', '0');
  771. $('div.Note.PersonalCacheNote').css('margin', '0');
  772. $('h3.CacheDescriptionHeader').remove();
  773. $('#ctl00_ContentBody_EncryptionKey').remove();
  774. $('#ctl00_ContentBody_GeoNav_foundStatus').css('margin-bottom', '0');
  775. }
  776.  
  777. // Make it easier to copy the gccode
  778. if (IsSettingEnabled('makeCopyFriendly')) {
  779. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').
  780. html('<div style="margin-right: 15px; margin-bottom: 10px;"><p id="ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoCode" style="font-size: 125%; margin-bottom: 0">' + gccode + '</p>' +
  781. '<input size="25" type="text" value="https://coord.info/' + encodeURIComponent(gccode) + '" onclick="this.setSelectionRange(0, this.value.length);"></div>');
  782. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').css('font-weight', 'inherit').css('margin-right', '27px');
  783. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel div').css('margin', '0 0 5px 0');
  784. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel div p').css('font-weight', 'bold');
  785. }
  786.  
  787. // Add PGC Map links
  788. if (IsSettingEnabled('addPgcMapLinks')) {
  789. coordinates = $('#ctl00_ContentBody_MapLinks_MapLinks li a').attr('href'),
  790. latitude = coordinates.replace(/.*lat=([^&]*)&lng=.*/, "$1"),
  791. longitude = coordinates.replace(/.*&lng=(.*)$/, "$1");
  792. // var mapUrl = pgcUrl + 'Maps/mapcompare/?profile_name=' + gccomUsername +
  793. // '&nonefound=on&ownfound=on&location=' + latitude + ',' + longitude +
  794. // '&max_distance=5&submit=Filter';
  795. var mapUrl = pgcUrl + 'LiveMap/#c=' + latitude + ',' + longitude + ';z=14';
  796.  
  797. // $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').append(
  798. // '<div style="margin-bottom: 8px;"><a target="_blank" href="' + mapUrl + '">Project-GC map</a> (<a target="_blank" href="' + mapUrl + '&onefound=on">incl found</a>)</div>'
  799. // );
  800. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').append(
  801. '<div style="margin-bottom: 8px;"><a target="_blank" href="' + mapUrl + '">Project-GC Live map</a></div>'
  802. );
  803. }
  804.  
  805. // Remove the UTM coordinates
  806. // $('#ctl00_ContentBody_CacheInformationTable div.LocationData div.span-9 p.NoBottomSpacing br').remove();
  807. if (IsSettingEnabled('removeUTM')) {
  808. $('#ctl00_ContentBody_LocationSubPanel').html('');
  809.  
  810. // And move the "N 248.3 km from your home location"
  811. $('#ctl00_ContentBody_LocationSubPanel').after($('#lblDistFromHome'));
  812. }
  813.  
  814. // Remove ads
  815. // PGC can't really do this officially
  816. // $('#ctl00_ContentBody_uxBanManWidget').remove();
  817.  
  818. // Remove disclaimer
  819. if (IsSettingEnabled('removeDisclaimer')) {
  820. $('#divContentMain div.span-17 div.Note.Disclaimer').remove();
  821. }
  822.  
  823. // If the first log is a DNF, display a blue warning on top of the page
  824. if($('#cache_logs_table tr:first td div.LogDisplayRight strong img').attr('src') === '/images/logtypes/3.png') {
  825. var htmlFirstLogDnf = '<p style="color: #006cff;" class=" NoBottomSpacing"><strong>Cache Issues:</strong></p>\
  826. <ul style="color: #006cff;" class="">\
  827. <li>The latest log for this cache is a DNF, <a href="#cache_logs_table">please read the log</a> before your own search.</li>\
  828. </ul>';
  829. $('div.span-6.right.last').last().next().after(htmlFirstLogDnf);
  830.  
  831. }
  832.  
  833. // Collapse download links
  834. // http://www.w3schools.com/charsets/ref_utf_geometric.asp (x25BA, x25BC)
  835. if (IsSettingEnabled('collapseDownloads')) {
  836. $('<p style="cursor: pointer; margin: 0;" id="DownloadLinksToggle" onclick="$(\'#divContentMain div.DownloadLinks, #DownloadLinksToggle .arrow\').toggle();"><span class="arrow">&#x25BA;</span><span class="arrow open">&#x25BC;</span>Print and Downloads</p>').insertBefore('#divContentMain div.DownloadLinks');
  837. $('#divContentMain div.DownloadLinks, #DownloadLinksToggle .arrow.open').hide();
  838. }
  839.  
  840. // Resolve the coordinates into an address
  841. if (IsSettingEnabled('addAddress')) {
  842. coordinates = $('#ctl00_ContentBody_MapLinks_MapLinks li a').attr('href'),
  843. latitude = coordinates.replace(/.*lat=([^&]*)&lng=.*/, "$1"),
  844. longitude = coordinates.replace(/.*&lng=(.*)$/, "$1"),
  845. url = 'https://nominatim.openstreetmap.org/reverse?lat=' + latitude + '&lon=' + longitude + '&format=json';
  846.  
  847. GM.xmlHttpRequest({
  848. method: "GET",
  849. url: url,
  850. onload: function(response) {
  851. var result = JSON.parse(response.responseText);
  852. if (!result.display_name) {
  853. return false;
  854. }
  855. var formattedAddress = result.address.road;
  856. if (result.address.house_number) {
  857. formattedAddress = formattedAddress + ' ' + result.address.house_number;
  858. }
  859. if (result.address.city) {
  860. formattedAddress = formattedAddress + ', ' + result.address.city;
  861. }
  862. $('#ctl00_ContentBody_LocationSubPanel').append(formattedAddress + '<br />');
  863. }
  864. });
  865. }
  866.  
  867. // Add number of finds per type to the top
  868. if (IsSettingEnabled('cloneLogsPerType') && typeof $('#ctl00_ContentBody_lblFindCounts').html() !== 'undefined') {
  869. $('#ctl00_ContentBody_CacheInformationTable').before('<div>' + $('#ctl00_ContentBody_lblFindCounts').html() + '</div>');
  870. }
  871.  
  872. // Add link to PGC gallery
  873. if (subscription && IsSettingEnabled('addPgcGalleryLinks')) {
  874. var html = '<a href="' + pgcUrl + 'Tools/Gallery?gccode=' + gccode + '&submit=Filter"><img src="' + galleryLinkIcon + '" title="Project-GC Gallery"></a> ';
  875. $('.CacheDetailNavigation ul li:first').append(html);
  876. }
  877.  
  878. // Add map links for each bookmarklist
  879. if (IsSettingEnabled('addMapBookmarkListLinks')) {
  880. $('ul.BookmarkList li').each(function() {
  881. var guid = $(this).children(':nth-child(1)').attr('href').replace(/.*\?guid=(.*)/, "$1");
  882. var owner = $(this).children(':nth-child(3)').text();
  883.  
  884. // Add the map link
  885. url = 'https://project-gc.com/Tools/MapBookmarklist?owner_name=' + encodeURIComponent(owner) + '&guid=' + encodeURIComponent(guid);
  886. $(this).children(':nth-child(1)').append('&nbsp;<a href="' + url + '"><img src="' + mapLinkIcon + '" title="Map with Project-GC"></a>');
  887.  
  888. // Add gallery link for the bookmark list
  889. url = 'https://project-gc.com/Tools/Gallery?bml_owner=' + encodeURIComponent(owner) + '&bml_guid=' + encodeURIComponent(guid) + '&submit=Filter';
  890. $(this).children(':nth-child(1)').append('&nbsp;<a href="' + url + '"><img src="' + galleryLinkIcon + '" title="Project-GC Gallery"></a>');
  891.  
  892. // Add profile stats link to the owner
  893. url = 'https://project-gc.com/ProfileStats/' + encodeURIComponent(owner);
  894. $(this).children(':nth-child(3)').append('&nbsp;<a href="' + url + '"><img src="' + externalLinkIcon + '" title="Project-GC Profile stats"></a>');
  895. });
  896. }
  897.  
  898. // Decrypt the hint
  899. if (IsSettingEnabled('decryptHints') && $('#ctl00_ContentBody_lnkDH')[0].title == 'Decrypt') {
  900. $('#ctl00_ContentBody_lnkDH')[0].click();
  901. }
  902.  
  903. // VGPS form
  904. if (IsSettingEnabled('showVGPS')) {
  905. GM.xmlHttpRequest({
  906. method: "GET",
  907. url: pgcApiUrl + 'GetExistingVGPSLists?gccode=' + gccode,
  908. onload: function(response) {
  909. var result = JSON.parse(response.responseText),
  910. vgpsLists = result.data.lists,
  911. selected = result.data.selected,
  912. existsIn = result.data.existsIn,
  913. selectedContent,
  914. existsContent,
  915. html = '<li><img width="16" height="16" src="https://cdn2.project-gc.com/images/mobile_telephone_32.png"> <strong>Add to VGPS</strong><br />',
  916. listId;
  917.  
  918. html += '<select id="comboVGPS" style="width: 138px;">';
  919. for (listId in vgpsLists) {
  920. selectedContent = '';
  921. if (+selected === +listId) {
  922. selectedContent = ' selected="selected"';
  923. }
  924.  
  925. existsContent = '';
  926. if (existsIn.indexOf(listId) > -1) {
  927. existsContent = ' data-exists="true"';
  928. }
  929. html += '<option value="' + listId + '"' + selectedContent + existsContent + '>' + vgpsLists[listId].name + '</option>';
  930. }
  931. html += '</select>';
  932. if (existsIn.indexOf(String(selected)) == -1) {
  933. html += '&nbsp;<button id="btnAddToVGPS">+</button>';
  934. html += '&nbsp;<button id="btnRemoveFromVGPS" style="display: none;">-</button>';
  935. } else {
  936. html += '&nbsp;<button id="btnAddToVGPS" style="display: none;">+</button>';
  937. html += '&nbsp;<button id="btnRemoveFromVGPS">-</button>';
  938. }
  939. html += '</li>';
  940.  
  941. $('div.CacheDetailNavigation ul:first').append(html);
  942.  
  943. $('#comboVGPS').change(function() {
  944. selected = $(this).find(':selected').val();
  945. if (existsIn.indexOf(String(selected)) == -1) {
  946. $('#btnAddToVGPS').css('display', '');
  947. $('#btnRemoveFromVGPS').css('display', 'none');
  948. } else {
  949. $('#btnAddToVGPS').css('display', 'none');
  950. $('#btnRemoveFromVGPS').css('display', '');
  951. }
  952. });
  953. $('#btnAddToVGPS').click(function(event) {
  954. event.preventDefault();
  955. addToVGPS();
  956. });
  957. $('#btnRemoveFromVGPS').click(function(event) {
  958. event.preventDefault();
  959. removeFromVGPS();
  960. });
  961. }
  962. });
  963. }
  964.  
  965. // Change font in personal cache note to monospaced
  966. if (IsSettingEnabled('cachenoteFont')) {
  967. $("#viewCacheNote,#cacheNoteText").css("font-family", "monospace").css("font-size", "12px");
  968. $("#viewCacheNote").on("DOMSubtreeModified", function() {
  969. $(".inplace_field").css("font-family", "monospace").css("font-size", "12px");
  970. });
  971. }
  972.  
  973.  
  974. if (IsSettingEnabled('logbookLinks')) {
  975. $('\
  976. <span>&nbsp;|&nbsp;</span><a id="pgc-logbook-yours" href="' + $('#ctl00_ContentBody_uxLogbookLink').attr('href') + '#tabs-2">Yours</a>\
  977. <span>&nbsp;|&nbsp;</span><a href="' + $('#ctl00_ContentBody_uxLogbookLink').attr('href') + '#tabs-3">Friends\'</a>\
  978. ').insertAfter( $('#ctl00_ContentBody_uxLogbookLink') );
  979. }
  980. }
  981.  
  982. function Page_Logbook() {
  983. // Since everything in the logbook is ajax, we need to wait for the elements
  984. waitForKeyElements('#AllLogs tr', Logbook);
  985. waitForKeyElements('#PersonalLogs tr', Logbook);
  986. waitForKeyElements('#FriendLogs tr', Logbook);
  987. }
  988.  
  989. function Logbook(jNode) {
  990. // Add Profile stats and gallery links after each user
  991. if (IsSettingEnabled('profileStatsLinks')) {
  992. var profileNameElm = $(jNode).find('a.h5');
  993. var profileName = profileNameElm.html();
  994.  
  995. if (typeof profileName !== 'undefined') {
  996. profileName = profileNameElm.append('<a href="' + pgcUrl + 'ProfileStats/' + encodeURIComponent(profileName) + '"><img src="' + externalLinkIcon + '" title="PGC Profile Stats"></a>')
  997. .append('<a href="' + pgcUrl + 'Tools/Gallery?profile_name=' + encodeURIComponent(profileName) + '&submit=Filter"><img src="' + galleryLinkIcon + '" title="PGC Gallery"></a>');
  998. }
  999. }
  1000.  
  1001. if(IsSettingEnabled('parseExifLocation')) {
  1002. $(jNode).find('ul.LogImagesTable li>a').each(function() {
  1003. var url = $(this).attr('href');
  1004. var thumbnailUrl = url.replace('/img.geocaching.com/cache/log/large/', '/img.geocaching.com/cache/log/thumb/');
  1005.  
  1006. var imgElm = $(this).find('img');
  1007. $(imgElm).attr('src', thumbnailUrl);
  1008. $(imgElm).removeAttr('width');
  1009. $(imgElm).removeAttr('height');
  1010. $(imgElm).next().css('vertical-align', 'top');
  1011.  
  1012. $(imgElm).load(function() {
  1013. EXIF.getData($(imgElm)[0], function() {
  1014. // console.log(EXIF.pretty(this));
  1015. var coords = GetCoordinatesFromExif(this);
  1016. if(coords != false) {
  1017. $('<span style="color: #8c0b0b; font-weight: bold; float: right;">EXIF Location: <a href="https://maps.google.com/?q=' + coords + '" target="_blank">' + coords + '</a></span>').insertAfter($(imgElm).parent());
  1018. }
  1019. });
  1020. });
  1021.  
  1022. });
  1023. }
  1024.  
  1025. if(IsSettingEnabled('addCachedChallengeCheckerResults') && typeof(challengeCheckerResults) !== 'undefined' && challengeCheckerResults !== null) {
  1026. var classes = $(jNode).attr('class');
  1027. var logId = classes.match(/l-[0-9]+/)[0].replace('l-', '');
  1028. if(typeof(challengeCheckerResults[logId]) !== 'undefined') {
  1029. if(challengeCheckerResults[logId]['status'] == 'success') {
  1030. $(jNode).find('div.LogDisplayLeft').first().append('<hr style="margin-top: 12px; margin-bottom: 12px;"><p>Checker result<br>' + challengeCheckerResults[logId]['lastRun'] + ' UTC: <img src="' + challengeCheckerSuccessIcon + '"></p>');
  1031. }
  1032. else if(challengeCheckerResults[logId]['status'] == 'fail') {
  1033. $(jNode).find('div.LogDisplayLeft').first().append('<hr style="margin-top: 12px; margin-bottom: 12px;"><p>Checker result<br>' + challengeCheckerResults[logId]['lastRun'] + ' UTC: <img src="' + challengeCheckerFailIcon + '"></p>');
  1034. }
  1035. }
  1036. }
  1037.  
  1038. if(IsSettingEnabled('hideLogVoting')) {
  1039. $('div.upvotes').css('display','none');
  1040. $('div.sort-logs').css('display','none');
  1041. }
  1042.  
  1043.  
  1044. // Save to latest logs
  1045. if (latestLogs.length < 5) {
  1046. var node = $(jNode).find('div.HalfLeft.LogType h4 img[src]'),
  1047. logType = {};
  1048.  
  1049. if (node.length === 0)
  1050. return false;
  1051.  
  1052. logType = {
  1053. 'src': node.attr('src'),
  1054. 'alt': node.attr('alt'),
  1055. 'title': node.attr('title')
  1056. };
  1057.  
  1058. logType.id = +logType.src.replace(/.*logtypes\/(\d+)\.png/, "$1");
  1059.  
  1060. // First entry is undefined, due to ajax
  1061. if (logType.src) {
  1062. latestLogs.push('<img src="' + logType.src + '" alt="' + logType.alt + '" title="' + logType.title + '" style="margin-bottom: -4px; margin-right: 1px;">');
  1063. // 2 = found, 3 = dnf, 4 = note, 5 = archive, 22 = disable, 24 = publish, 45 = nm, 46 = owner maintenance, 68 = reviewer note
  1064. if ($.inArray(logType.id, [3, 5, 22, 45, 68]) !== -1) {
  1065. latestLogsAlert = true;
  1066. }
  1067. }
  1068.  
  1069. // Show latest logs
  1070. // Enhanced Nov 2016 to show icons for up to 5 of the latest logs
  1071. if (IsSettingEnabled('addLatestLogs') && latestLogs.length <= 5) {
  1072. var images = latestLogs.join('');
  1073.  
  1074. $('#latestLogIcons').remove();
  1075. $('#ctl00_ContentBody_size p').removeClass('AlignCenter').addClass('NoBottomSpacing');
  1076.  
  1077. if (latestLogsAlert) {
  1078. $('#ctl00_ContentBody_size').append('<p class="NoBottomSpacing OldWarning" id="latestLogIcons"><strong>Latest logs:</strong> <span>' + images + '</span></p>');
  1079. } else {
  1080. $('#ctl00_ContentBody_size').append('<p class="NoBottomSpacing" id="latestLogIcons">Latest logs: <span>' + images + '</span></p>');
  1081. }
  1082. }
  1083. }
  1084. }
  1085.  
  1086. function Page_Map() {
  1087. if (IsSettingEnabled('showVGPS')) {
  1088.  
  1089. setTimeout(function() {
  1090. $('#map_canvas div.leaflet-popup-pane').bind('DOMSubtreeModified', function() {
  1091. if ($('#pgc_vgps').length === 0) {
  1092. var gccode = $('#gmCacheInfo div.code').text();
  1093.  
  1094. $('#gmCacheInfo div.links').after('<div id="pgc_vgps"></div>');
  1095.  
  1096. GM.xmlHttpRequest({
  1097. method: "GET",
  1098. url: pgcApiUrl + 'GetExistingVGPSLists?gccode=' + gccode,
  1099. onload: function(response) {
  1100.  
  1101. var result = JSON.parse(response.responseText),
  1102. vgpsLists = result.data.lists,
  1103. selected = result.data.selected,
  1104. existsIn = result.data.existsIn,
  1105. selectedContent,
  1106. existsContent,
  1107. html,
  1108. listId;
  1109.  
  1110.  
  1111. html = '<img src="https://cdn2.project-gc.com/images/mobile_telephone_32.png" style="width: 24px; height: 24px; margin-bottom: -6px;">';
  1112.  
  1113. html += '<select id="comboVGPS" style="margin-bottom: 4px;">';
  1114. for (listId in vgpsLists) {
  1115. selectedContent = '';
  1116. if (+selected === +listId) {
  1117. selectedContent = ' selected="selected"';
  1118. }
  1119.  
  1120. html += '<option value="' + listId + '"' + selectedContent + existsContent + '>' + vgpsLists[listId].name + '</option>';
  1121. }
  1122. html += '</select>';
  1123.  
  1124. if (existsIn.indexOf(String(selected)) == -1) {
  1125. html += '&nbsp;<button id="btnAddToVGPS">+</button>';
  1126. html += '&nbsp;<button id="btnRemoveFromVGPS" style="display: none;">-</button>';
  1127. } else {
  1128. html += '&nbsp;<button id="btnAddToVGPS" style="display: none;">+</button>';
  1129. html += '&nbsp;<button id="btnRemoveFromVGPS">-</button>';
  1130. }
  1131.  
  1132. $('#pgc_vgps').html(html);
  1133.  
  1134.  
  1135. $('#btnAddToVGPS').click(function(event) {
  1136. event.preventDefault();
  1137. addToVGPS(gccode);
  1138. });
  1139. $('#btnRemoveFromVGPS').click(function(event) {
  1140. event.preventDefault();
  1141. removeFromVGPS(gccode);
  1142. });
  1143. }
  1144. });
  1145. }
  1146. });
  1147. }, 500);
  1148. }
  1149.  
  1150. }
  1151.  
  1152. function Page_Gallery() {
  1153. // Find location data in exif tags
  1154. if(IsSettingEnabled('parseExifLocation')) {
  1155. $(window).load(function() { // Wait until page is loaded. If the images aren't loaded before this starts it will fail.
  1156. $('#ctl00_ContentBody_GalleryItems_DataListGallery img').each(function() {
  1157. EXIF.getData($(this)[0], function() {
  1158. // console.log(EXIF.pretty(this));
  1159. var coords = GetCoordinatesFromExif(this);
  1160. if(coords != false) {
  1161. $('<span class="OldWarning">EXIF Location<br><a href="https://maps.google.com/?q=' + coords + '" target="_blank">' + coords + '</a></span>').insertAfter(this.parentNode);
  1162. }
  1163. });
  1164. });
  1165. });
  1166. }
  1167. }
  1168.  
  1169. function Page_Bookmarks() {
  1170. var owner_name = $("#ctl00_ContentBody_ListInfo_uxListOwner").text();
  1171.  
  1172. var search = window.location.search;
  1173. var guid_start = search.indexOf("guid=");
  1174. if (guid_start == -1) {
  1175. /* the guid= not found in URL
  1176. * something is wrong so we will not generate bad URL
  1177. */
  1178. return;
  1179. }
  1180. var guid = search.substr(guid_start + 5/*, eof */);
  1181.  
  1182. var url = "https://project-gc.com/Tools/MapBookmarklist?owner_name=" + owner_name + "&guid=" + guid;
  1183. var icon = "https://cdn2.project-gc.com/images/map_app_16.png";
  1184.  
  1185. /* Heading link */
  1186. var html = ' <a href="' + url + '" title="Map this Bookmark list using Project-GC" style="padding-left:20px;"><img src="' + icon + '" /> Map this!</a>';
  1187.  
  1188. $("#ctl00_ContentBody_lbHeading").after(html);
  1189.  
  1190. /* Footer button */
  1191. var html2 = '<p><input type="button" onclick="window.location.href= \'' + url + '\'" value="Map this Bookmark list on Project-GC" /></p>';
  1192.  
  1193. $("#ctl00_ContentBody_ListInfo_btnDownload").parent().before(html2);
  1194. }
  1195.  
  1196. function Page_Drafts() {
  1197. if (IsSettingEnabled("openDraftLogInSameWindow")) {
  1198. waitForKeyElements('#draftsHub > ul.draft-list > li.draft-item', Draft);
  1199. }
  1200. }
  1201.  
  1202. function Draft(jNode) {
  1203. $(jNode).find(".draft-content > a").removeAttr('target');
  1204. }
  1205.  
  1206. function Page_Messagecenter() {
  1207. var target = document.getElementById('currentMessage');
  1208. var observer = new MutationObserver(function(mutations) {
  1209. mutations.forEach(function(mutation) {
  1210. if(mutation.type === "childList") {
  1211. var userlink = $(".user-meta a.current-user-image").attr("href"), username = $(".user-meta span.current-user-name").html();
  1212. $(".user-meta span.current-user-name").html("<a href='"+userlink+"'>"+username+"</a>");
  1213. }
  1214. });
  1215. });
  1216.  
  1217. var config = { childList: true };
  1218. observer.observe(target, config);
  1219. }
  1220.  
  1221. function Page_PrintCachePage() {
  1222. // Remove the disclaimer
  1223. $('div.TermsWidget').css('display', 'none');
  1224.  
  1225.  
  1226. // Get rid of the Logs section if it's not asked for. But keep it if we asked for it, even though there are 0 logs.
  1227. if( getUrlParameter('lc') === false ) {
  1228. $('div.item.ui-widget > div.item-header > h2.ui-sortable-handle').each(function() {
  1229. if( $(this).html() == 'Logs' ) { // Will only work with English
  1230. $(this).parent().parent().addClass('no-print').css('display', 'none');
  1231. return false; // Break .each loop
  1232. }
  1233. });
  1234. }
  1235.  
  1236.  
  1237. if(IsSettingEnabled('hideMapFromPrintCachePage')) {
  1238. $('#map').parent().parent().addClass('no-print');
  1239. $('#map').parent().prev().children('span.ui-icon').removeClass('ui-icon-minusthick').addClass('ui-icon-plusthick');
  1240. $('#map').parent().css('display', 'none');
  1241. }
  1242. }
  1243.  
  1244.  
  1245. function padLeft(str, n, padstr){
  1246. return Array(n-String(str).length+1).join(padstr||'0')+str;
  1247. }
  1248.  
  1249. function getUrlParameter(sParam) {
  1250. var sPageURL = decodeURIComponent(window.location.search.substring(1)),
  1251. sURLVariables = sPageURL.split('&'),
  1252. sParameterName,
  1253. i;
  1254.  
  1255. for (i = 0; i < sURLVariables.length; i++) {
  1256. sParameterName = sURLVariables[i].split('=');
  1257.  
  1258. if (sParameterName[0] === sParam) {
  1259. return sParameterName[1] === undefined ? true : sParameterName[1];
  1260. }
  1261. }
  1262.  
  1263. return false;
  1264. }
  1265. }());
  1266.  
  1267.  
  1268.  
  1269. // https://github.com/exif-js/exif-js adjusted to use GM.xmlHttpRequest
  1270. (function() {
  1271. var debug = false;
  1272.  
  1273. var root = this;
  1274.  
  1275. var EXIF = function(obj) {
  1276. if (obj instanceof EXIF) return obj;
  1277. if (!(this instanceof EXIF)) return new EXIF(obj);
  1278. this.EXIFwrapped = obj;
  1279. };
  1280.  
  1281. if (typeof exports !== 'undefined') {
  1282. if (typeof module !== 'undefined' && module.exports) {
  1283. exports = module.exports = EXIF;
  1284. }
  1285. exports.EXIF = EXIF;
  1286. } else {
  1287. root.EXIF = EXIF;
  1288. }
  1289.  
  1290. var ExifTags = EXIF.Tags = {
  1291.  
  1292. // version tags
  1293. 0x9000 : "ExifVersion", // EXIF version
  1294. 0xA000 : "FlashpixVersion", // Flashpix format version
  1295.  
  1296. // colorspace tags
  1297. 0xA001 : "ColorSpace", // Color space information tag
  1298.  
  1299. // image configuration
  1300. 0xA002 : "PixelXDimension", // Valid width of meaningful image
  1301. 0xA003 : "PixelYDimension", // Valid height of meaningful image
  1302. 0x9101 : "ComponentsConfiguration", // Information about channels
  1303. 0x9102 : "CompressedBitsPerPixel", // Compressed bits per pixel
  1304.  
  1305. // user information
  1306. 0x927C : "MakerNote", // Any desired information written by the manufacturer
  1307. 0x9286 : "UserComment", // Comments by user
  1308.  
  1309. // related file
  1310. 0xA004 : "RelatedSoundFile", // Name of related sound file
  1311.  
  1312. // date and time
  1313. 0x9003 : "DateTimeOriginal", // Date and time when the original image was generated
  1314. 0x9004 : "DateTimeDigitized", // Date and time when the image was stored digitally
  1315. 0x9290 : "SubsecTime", // Fractions of seconds for DateTime
  1316. 0x9291 : "SubsecTimeOriginal", // Fractions of seconds for DateTimeOriginal
  1317. 0x9292 : "SubsecTimeDigitized", // Fractions of seconds for DateTimeDigitized
  1318.  
  1319. // picture-taking conditions
  1320. 0x829A : "ExposureTime", // Exposure time (in seconds)
  1321. 0x829D : "FNumber", // F number
  1322. 0x8822 : "ExposureProgram", // Exposure program
  1323. 0x8824 : "SpectralSensitivity", // Spectral sensitivity
  1324. 0x8827 : "ISOSpeedRatings", // ISO speed rating
  1325. 0x8828 : "OECF", // Optoelectric conversion factor
  1326. 0x9201 : "ShutterSpeedValue", // Shutter speed
  1327. 0x9202 : "ApertureValue", // Lens aperture
  1328. 0x9203 : "BrightnessValue", // Value of brightness
  1329. 0x9204 : "ExposureBias", // Exposure bias
  1330. 0x9205 : "MaxApertureValue", // Smallest F number of lens
  1331. 0x9206 : "SubjectDistance", // Distance to subject in meters
  1332. 0x9207 : "MeteringMode", // Metering mode
  1333. 0x9208 : "LightSource", // Kind of light source
  1334. 0x9209 : "Flash", // Flash status
  1335. 0x9214 : "SubjectArea", // Location and area of main subject
  1336. 0x920A : "FocalLength", // Focal length of the lens in mm
  1337. 0xA20B : "FlashEnergy", // Strobe energy in BCPS
  1338. 0xA20C : "SpatialFrequencyResponse", //
  1339. 0xA20E : "FocalPlaneXResolution", // Number of pixels in width direction per FocalPlaneResolutionUnit
  1340. 0xA20F : "FocalPlaneYResolution", // Number of pixels in height direction per FocalPlaneResolutionUnit
  1341. 0xA210 : "FocalPlaneResolutionUnit", // Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution
  1342. 0xA214 : "SubjectLocation", // Location of subject in image
  1343. 0xA215 : "ExposureIndex", // Exposure index selected on camera
  1344. 0xA217 : "SensingMethod", // Image sensor type
  1345. 0xA300 : "FileSource", // Image source (3 == DSC)
  1346. 0xA301 : "SceneType", // Scene type (1 == directly photographed)
  1347. 0xA302 : "CFAPattern", // Color filter array geometric pattern
  1348. 0xA401 : "CustomRendered", // Special processing
  1349. 0xA402 : "ExposureMode", // Exposure mode
  1350. 0xA403 : "WhiteBalance", // 1 = auto white balance, 2 = manual
  1351. 0xA404 : "DigitalZoomRation", // Digital zoom ratio
  1352. 0xA405 : "FocalLengthIn35mmFilm", // Equivalent foacl length assuming 35mm film camera (in mm)
  1353. 0xA406 : "SceneCaptureType", // Type of scene
  1354. 0xA407 : "GainControl", // Degree of overall image gain adjustment
  1355. 0xA408 : "Contrast", // Direction of contrast processing applied by camera
  1356. 0xA409 : "Saturation", // Direction of saturation processing applied by camera
  1357. 0xA40A : "Sharpness", // Direction of sharpness processing applied by camera
  1358. 0xA40B : "DeviceSettingDescription", //
  1359. 0xA40C : "SubjectDistanceRange", // Distance to subject
  1360.  
  1361. // other tags
  1362. 0xA005 : "InteroperabilityIFDPointer",
  1363. 0xA420 : "ImageUniqueID" // Identifier assigned uniquely to each image
  1364. };
  1365.  
  1366. var TiffTags = EXIF.TiffTags = {
  1367. 0x0100 : "ImageWidth",
  1368. 0x0101 : "ImageHeight",
  1369. 0x8769 : "ExifIFDPointer",
  1370. 0x8825 : "GPSInfoIFDPointer",
  1371. 0xA005 : "InteroperabilityIFDPointer",
  1372. 0x0102 : "BitsPerSample",
  1373. 0x0103 : "Compression",
  1374. 0x0106 : "PhotometricInterpretation",
  1375. 0x0112 : "Orientation",
  1376. 0x0115 : "SamplesPerPixel",
  1377. 0x011C : "PlanarConfiguration",
  1378. 0x0212 : "YCbCrSubSampling",
  1379. 0x0213 : "YCbCrPositioning",
  1380. 0x011A : "XResolution",
  1381. 0x011B : "YResolution",
  1382. 0x0128 : "ResolutionUnit",
  1383. 0x0111 : "StripOffsets",
  1384. 0x0116 : "RowsPerStrip",
  1385. 0x0117 : "StripByteCounts",
  1386. 0x0201 : "JPEGInterchangeFormat",
  1387. 0x0202 : "JPEGInterchangeFormatLength",
  1388. 0x012D : "TransferFunction",
  1389. 0x013E : "WhitePoint",
  1390. 0x013F : "PrimaryChromaticities",
  1391. 0x0211 : "YCbCrCoefficients",
  1392. 0x0214 : "ReferenceBlackWhite",
  1393. 0x0132 : "DateTime",
  1394. 0x010E : "ImageDescription",
  1395. 0x010F : "Make",
  1396. 0x0110 : "Model",
  1397. 0x0131 : "Software",
  1398. 0x013B : "Artist",
  1399. 0x8298 : "Copyright"
  1400. };
  1401.  
  1402. var GPSTags = EXIF.GPSTags = {
  1403. 0x0000 : "GPSVersionID",
  1404. 0x0001 : "GPSLatitudeRef",
  1405. 0x0002 : "GPSLatitude",
  1406. 0x0003 : "GPSLongitudeRef",
  1407. 0x0004 : "GPSLongitude",
  1408. 0x0005 : "GPSAltitudeRef",
  1409. 0x0006 : "GPSAltitude",
  1410. 0x0007 : "GPSTimeStamp",
  1411. 0x0008 : "GPSSatellites",
  1412. 0x0009 : "GPSStatus",
  1413. 0x000A : "GPSMeasureMode",
  1414. 0x000B : "GPSDOP",
  1415. 0x000C : "GPSSpeedRef",
  1416. 0x000D : "GPSSpeed",
  1417. 0x000E : "GPSTrackRef",
  1418. 0x000F : "GPSTrack",
  1419. 0x0010 : "GPSImgDirectionRef",
  1420. 0x0011 : "GPSImgDirection",
  1421. 0x0012 : "GPSMapDatum",
  1422. 0x0013 : "GPSDestLatitudeRef",
  1423. 0x0014 : "GPSDestLatitude",
  1424. 0x0015 : "GPSDestLongitudeRef",
  1425. 0x0016 : "GPSDestLongitude",
  1426. 0x0017 : "GPSDestBearingRef",
  1427. 0x0018 : "GPSDestBearing",
  1428. 0x0019 : "GPSDestDistanceRef",
  1429. 0x001A : "GPSDestDistance",
  1430. 0x001B : "GPSProcessingMethod",
  1431. 0x001C : "GPSAreaInformation",
  1432. 0x001D : "GPSDateStamp",
  1433. 0x001E : "GPSDifferential"
  1434. };
  1435.  
  1436. var StringValues = EXIF.StringValues = {
  1437. ExposureProgram : {
  1438. 0 : "Not defined",
  1439. 1 : "Manual",
  1440. 2 : "Normal program",
  1441. 3 : "Aperture priority",
  1442. 4 : "Shutter priority",
  1443. 5 : "Creative program",
  1444. 6 : "Action program",
  1445. 7 : "Portrait mode",
  1446. 8 : "Landscape mode"
  1447. },
  1448. MeteringMode : {
  1449. 0 : "Unknown",
  1450. 1 : "Average",
  1451. 2 : "CenterWeightedAverage",
  1452. 3 : "Spot",
  1453. 4 : "MultiSpot",
  1454. 5 : "Pattern",
  1455. 6 : "Partial",
  1456. 255 : "Other"
  1457. },
  1458. LightSource : {
  1459. 0 : "Unknown",
  1460. 1 : "Daylight",
  1461. 2 : "Fluorescent",
  1462. 3 : "Tungsten (incandescent light)",
  1463. 4 : "Flash",
  1464. 9 : "Fine weather",
  1465. 10 : "Cloudy weather",
  1466. 11 : "Shade",
  1467. 12 : "Daylight fluorescent (D 5700 - 7100K)",
  1468. 13 : "Day white fluorescent (N 4600 - 5400K)",
  1469. 14 : "Cool white fluorescent (W 3900 - 4500K)",
  1470. 15 : "White fluorescent (WW 3200 - 3700K)",
  1471. 17 : "Standard light A",
  1472. 18 : "Standard light B",
  1473. 19 : "Standard light C",
  1474. 20 : "D55",
  1475. 21 : "D65",
  1476. 22 : "D75",
  1477. 23 : "D50",
  1478. 24 : "ISO studio tungsten",
  1479. 255 : "Other"
  1480. },
  1481. Flash : {
  1482. 0x0000 : "Flash did not fire",
  1483. 0x0001 : "Flash fired",
  1484. 0x0005 : "Strobe return light not detected",
  1485. 0x0007 : "Strobe return light detected",
  1486. 0x0009 : "Flash fired, compulsory flash mode",
  1487. 0x000D : "Flash fired, compulsory flash mode, return light not detected",
  1488. 0x000F : "Flash fired, compulsory flash mode, return light detected",
  1489. 0x0010 : "Flash did not fire, compulsory flash mode",
  1490. 0x0018 : "Flash did not fire, auto mode",
  1491. 0x0019 : "Flash fired, auto mode",
  1492. 0x001D : "Flash fired, auto mode, return light not detected",
  1493. 0x001F : "Flash fired, auto mode, return light detected",
  1494. 0x0020 : "No flash function",
  1495. 0x0041 : "Flash fired, red-eye reduction mode",
  1496. 0x0045 : "Flash fired, red-eye reduction mode, return light not detected",
  1497. 0x0047 : "Flash fired, red-eye reduction mode, return light detected",
  1498. 0x0049 : "Flash fired, compulsory flash mode, red-eye reduction mode",
  1499. 0x004D : "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",
  1500. 0x004F : "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",
  1501. 0x0059 : "Flash fired, auto mode, red-eye reduction mode",
  1502. 0x005D : "Flash fired, auto mode, return light not detected, red-eye reduction mode",
  1503. 0x005F : "Flash fired, auto mode, return light detected, red-eye reduction mode"
  1504. },
  1505. SensingMethod : {
  1506. 1 : "Not defined",
  1507. 2 : "One-chip color area sensor",
  1508. 3 : "Two-chip color area sensor",
  1509. 4 : "Three-chip color area sensor",
  1510. 5 : "Color sequential area sensor",
  1511. 7 : "Trilinear sensor",
  1512. 8 : "Color sequential linear sensor"
  1513. },
  1514. SceneCaptureType : {
  1515. 0 : "Standard",
  1516. 1 : "Landscape",
  1517. 2 : "Portrait",
  1518. 3 : "Night scene"
  1519. },
  1520. SceneType : {
  1521. 1 : "Directly photographed"
  1522. },
  1523. CustomRendered : {
  1524. 0 : "Normal process",
  1525. 1 : "Custom process"
  1526. },
  1527. WhiteBalance : {
  1528. 0 : "Auto white balance",
  1529. 1 : "Manual white balance"
  1530. },
  1531. GainControl : {
  1532. 0 : "None",
  1533. 1 : "Low gain up",
  1534. 2 : "High gain up",
  1535. 3 : "Low gain down",
  1536. 4 : "High gain down"
  1537. },
  1538. Contrast : {
  1539. 0 : "Normal",
  1540. 1 : "Soft",
  1541. 2 : "Hard"
  1542. },
  1543. Saturation : {
  1544. 0 : "Normal",
  1545. 1 : "Low saturation",
  1546. 2 : "High saturation"
  1547. },
  1548. Sharpness : {
  1549. 0 : "Normal",
  1550. 1 : "Soft",
  1551. 2 : "Hard"
  1552. },
  1553. SubjectDistanceRange : {
  1554. 0 : "Unknown",
  1555. 1 : "Macro",
  1556. 2 : "Close view",
  1557. 3 : "Distant view"
  1558. },
  1559. FileSource : {
  1560. 3 : "DSC"
  1561. },
  1562.  
  1563. Components : {
  1564. 0 : "",
  1565. 1 : "Y",
  1566. 2 : "Cb",
  1567. 3 : "Cr",
  1568. 4 : "R",
  1569. 5 : "G",
  1570. 6 : "B"
  1571. }
  1572. };
  1573.  
  1574. function addEvent(element, event, handler) {
  1575. if (element.addEventListener) {
  1576. element.addEventListener(event, handler, false);
  1577. } else if (element.attachEvent) {
  1578. element.attachEvent("on" + event, handler);
  1579. }
  1580. }
  1581.  
  1582. function imageHasData(img) {
  1583. return !!(img.exifdata);
  1584. }
  1585.  
  1586.  
  1587. function base64ToArrayBuffer(base64, contentType) {
  1588. contentType = contentType || base64.match(/^data\:([^\;]+)\;base64,/mi)[1] || ''; // e.g. 'data:image/jpeg;base64,...' => 'image/jpeg'
  1589. base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
  1590. var binary = atob(base64);
  1591. var len = binary.length;
  1592. var buffer = new ArrayBuffer(len);
  1593. var view = new Uint8Array(buffer);
  1594. for (var i = 0; i < len; i++) {
  1595. view[i] = binary.charCodeAt(i);
  1596. }
  1597. return buffer;
  1598. }
  1599.  
  1600. function objectURLToBlob(url, callback) {
  1601. // var http = new XMLHttpRequest();
  1602. // http.open("GET", url, true);
  1603. // http.responseType = "blob";
  1604. // http.onload = function(e) {
  1605. // if (this.status == 200 || this.status === 0) {
  1606. // callback(this.response);
  1607. // }
  1608. // };
  1609. // http.send();
  1610.  
  1611. // GM.xmlHttpRequest({
  1612. // method: "GET",
  1613. // url: url,
  1614. // onload: function(e) {
  1615. // if (this.status == 200 || this.status === 0) {
  1616. // callback(this.response);
  1617. // }
  1618. // }
  1619. // });
  1620. }
  1621.  
  1622. function getImageData(img, callback) {
  1623. function handleBinaryFile(binFile) {
  1624. var data = findEXIFinJPEG(binFile);
  1625. var iptcdata = findIPTCinJPEG(binFile);
  1626. img.exifdata = data || {};
  1627. img.iptcdata = iptcdata || {};
  1628. if (callback) {
  1629. callback.call(img);
  1630. }
  1631. }
  1632.  
  1633. if (img.src) {
  1634. if (/^data\:/i.test(img.src)) { // Data URI
  1635. var arrayBuffer = base64ToArrayBuffer(img.src);
  1636. handleBinaryFile(arrayBuffer);
  1637.  
  1638. } else if (/^blob\:/i.test(img.src)) { // Object URL
  1639. var fileReader = new FileReader();
  1640. fileReader.onload = function(e) {
  1641. handleBinaryFile(e.target.result);
  1642. };
  1643. objectURLToBlob(img.src, function (blob) {
  1644. fileReader.readAsArrayBuffer(blob);
  1645. });
  1646. } else {
  1647. // var http = new XMLHttpRequest();
  1648. // http.onload = function() {
  1649. // if (this.status == 200 || this.status === 0) {
  1650. // handleBinaryFile(http.response);
  1651. // } else {
  1652. // throw "Could not load image";
  1653. // }
  1654. // http = null;
  1655. // };
  1656. // http.open("GET", img.src, true);
  1657. // http.responseType = "arraybuffer";
  1658. // http.send(null);
  1659.  
  1660. GM.xmlHttpRequest({
  1661. method: "GET",
  1662. url: img.src,
  1663. responseType: 'arraybuffer',
  1664. onload: function(response) {
  1665. if (response.status == 200 || response.status === 0) {
  1666. handleBinaryFile(response.response);
  1667. }
  1668. }
  1669. });
  1670. }
  1671. } else if (window.FileReader && (img instanceof window.Blob || img instanceof window.File)) {
  1672. var fileReader = new FileReader();
  1673. fileReader.onload = function(e) {
  1674. if (debug) console.log("Got file of length " + e.target.result.byteLength);
  1675. handleBinaryFile(e.target.result);
  1676. };
  1677.  
  1678. fileReader.readAsArrayBuffer(img);
  1679. }
  1680. }
  1681.  
  1682. function findEXIFinJPEG(file) {
  1683. var dataView = new DataView(file);
  1684.  
  1685. if (debug) console.log("Got file of length " + file.byteLength);
  1686. if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
  1687. if (debug) console.log("Not a valid JPEG");
  1688. return false; // not a valid jpeg
  1689. }
  1690.  
  1691. var offset = 2,
  1692. length = file.byteLength,
  1693. marker;
  1694.  
  1695. while (offset < length) {
  1696. if (dataView.getUint8(offset) != 0xFF) {
  1697. if (debug) console.log("Not a valid marker at offset " + offset + ", found: " + dataView.getUint8(offset));
  1698. return false; // not a valid marker, something is wrong
  1699. }
  1700.  
  1701. marker = dataView.getUint8(offset + 1);
  1702. if (debug) console.log(marker);
  1703.  
  1704. // we could implement handling for other markers here,
  1705. // but we're only looking for 0xFFE1 for EXIF data
  1706.  
  1707. if (marker == 225) {
  1708. if (debug) console.log("Found 0xFFE1 marker");
  1709.  
  1710. return readEXIFData(dataView, offset + 4, dataView.getUint16(offset + 2) - 2);
  1711.  
  1712. // offset += 2 + file.getShortAt(offset+2, true);
  1713.  
  1714. } else {
  1715. offset += 2 + dataView.getUint16(offset+2);
  1716. }
  1717.  
  1718. }
  1719.  
  1720. }
  1721.  
  1722. function findIPTCinJPEG(file) {
  1723. var dataView = new DataView(file);
  1724.  
  1725. if (debug) console.log("Got file of length " + file.byteLength);
  1726. if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
  1727. if (debug) console.log("Not a valid JPEG");
  1728. return false; // not a valid jpeg
  1729. }
  1730.  
  1731. var offset = 2,
  1732. length = file.byteLength;
  1733.  
  1734.  
  1735. var isFieldSegmentStart = function(dataView, offset){
  1736. return (
  1737. dataView.getUint8(offset) === 0x38 &&
  1738. dataView.getUint8(offset+1) === 0x42 &&
  1739. dataView.getUint8(offset+2) === 0x49 &&
  1740. dataView.getUint8(offset+3) === 0x4D &&
  1741. dataView.getUint8(offset+4) === 0x04 &&
  1742. dataView.getUint8(offset+5) === 0x04
  1743. );
  1744. };
  1745.  
  1746. while (offset < length) {
  1747.  
  1748. if ( isFieldSegmentStart(dataView, offset )){
  1749.  
  1750. // Get the length of the name header (which is padded to an even number of bytes)
  1751. var nameHeaderLength = dataView.getUint8(offset+7);
  1752. if(nameHeaderLength % 2 !== 0) nameHeaderLength += 1;
  1753. // Check for pre photoshop 6 format
  1754. if(nameHeaderLength === 0) {
  1755. // Always 4
  1756. nameHeaderLength = 4;
  1757. }
  1758.  
  1759. var startOffset = offset + 8 + nameHeaderLength;
  1760. var sectionLength = dataView.getUint16(offset + 6 + nameHeaderLength);
  1761.  
  1762. return readIPTCData(file, startOffset, sectionLength);
  1763.  
  1764. break;
  1765.  
  1766. }
  1767.  
  1768.  
  1769. // Not the marker, continue searching
  1770. offset++;
  1771.  
  1772. }
  1773.  
  1774. }
  1775. var IptcFieldMap = {
  1776. 0x78 : 'caption',
  1777. 0x6E : 'credit',
  1778. 0x19 : 'keywords',
  1779. 0x37 : 'dateCreated',
  1780. 0x50 : 'byline',
  1781. 0x55 : 'bylineTitle',
  1782. 0x7A : 'captionWriter',
  1783. 0x69 : 'headline',
  1784. 0x74 : 'copyright',
  1785. 0x0F : 'category'
  1786. };
  1787. function readIPTCData(file, startOffset, sectionLength){
  1788. var dataView = new DataView(file);
  1789. var data = {};
  1790. var fieldValue, fieldName, dataSize, segmentType, segmentSize;
  1791. var segmentStartPos = startOffset;
  1792. while(segmentStartPos < startOffset+sectionLength) {
  1793. if(dataView.getUint8(segmentStartPos) === 0x1C && dataView.getUint8(segmentStartPos+1) === 0x02){
  1794. segmentType = dataView.getUint8(segmentStartPos+2);
  1795. if(segmentType in IptcFieldMap) {
  1796. dataSize = dataView.getInt16(segmentStartPos+3);
  1797. segmentSize = dataSize + 5;
  1798. fieldName = IptcFieldMap[segmentType];
  1799. fieldValue = getStringFromDB(dataView, segmentStartPos+5, dataSize);
  1800. // Check if we already stored a value with this name
  1801. if(data.hasOwnProperty(fieldName)) {
  1802. // Value already stored with this name, create multivalue field
  1803. if(data[fieldName] instanceof Array) {
  1804. data[fieldName].push(fieldValue);
  1805. }
  1806. else {
  1807. data[fieldName] = [data[fieldName], fieldValue];
  1808. }
  1809. }
  1810. else {
  1811. data[fieldName] = fieldValue;
  1812. }
  1813. }
  1814.  
  1815. }
  1816. segmentStartPos++;
  1817. }
  1818. return data;
  1819. }
  1820.  
  1821.  
  1822.  
  1823. function readTags(file, tiffStart, dirStart, strings, bigEnd) {
  1824. var entries = file.getUint16(dirStart, !bigEnd),
  1825. tags = {},
  1826. entryOffset, tag,
  1827. i;
  1828.  
  1829. for (i=0;i<entries;i++) {
  1830. entryOffset = dirStart + i*12 + 2;
  1831. tag = strings[file.getUint16(entryOffset, !bigEnd)];
  1832. if (!tag && debug) console.log("Unknown tag: " + file.getUint16(entryOffset, !bigEnd));
  1833. tags[tag] = readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd);
  1834. }
  1835. return tags;
  1836. }
  1837.  
  1838.  
  1839. function readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd) {
  1840. var type = file.getUint16(entryOffset+2, !bigEnd),
  1841. numValues = file.getUint32(entryOffset+4, !bigEnd),
  1842. valueOffset = file.getUint32(entryOffset+8, !bigEnd) + tiffStart,
  1843. offset,
  1844. vals, val, n,
  1845. numerator, denominator;
  1846.  
  1847. switch (type) {
  1848. case 1: // byte, 8-bit unsigned int
  1849. case 7: // undefined, 8-bit byte, value depending on field
  1850. if (numValues == 1) {
  1851. return file.getUint8(entryOffset + 8, !bigEnd);
  1852. } else {
  1853. offset = numValues > 4 ? valueOffset : (entryOffset + 8);
  1854. vals = [];
  1855. for (n=0;n<numValues;n++) {
  1856. vals[n] = file.getUint8(offset + n);
  1857. }
  1858. return vals;
  1859. }
  1860.  
  1861. case 2: // ascii, 8-bit byte
  1862. offset = numValues > 4 ? valueOffset : (entryOffset + 8);
  1863. return getStringFromDB(file, offset, numValues-1);
  1864.  
  1865. case 3: // short, 16 bit int
  1866. if (numValues == 1) {
  1867. return file.getUint16(entryOffset + 8, !bigEnd);
  1868. } else {
  1869. offset = numValues > 2 ? valueOffset : (entryOffset + 8);
  1870. vals = [];
  1871. for (n=0;n<numValues;n++) {
  1872. vals[n] = file.getUint16(offset + 2*n, !bigEnd);
  1873. }
  1874. return vals;
  1875. }
  1876.  
  1877. case 4: // long, 32 bit int
  1878. if (numValues == 1) {
  1879. return file.getUint32(entryOffset + 8, !bigEnd);
  1880. } else {
  1881. vals = [];
  1882. for (n=0;n<numValues;n++) {
  1883. vals[n] = file.getUint32(valueOffset + 4*n, !bigEnd);
  1884. }
  1885. return vals;
  1886. }
  1887.  
  1888. case 5: // rational = two long values, first is numerator, second is denominator
  1889. if (numValues == 1) {
  1890. numerator = file.getUint32(valueOffset, !bigEnd);
  1891. denominator = file.getUint32(valueOffset+4, !bigEnd);
  1892. val = new Number(numerator / denominator);
  1893. val.numerator = numerator;
  1894. val.denominator = denominator;
  1895. return val;
  1896. } else {
  1897. vals = [];
  1898. for (n=0;n<numValues;n++) {
  1899. numerator = file.getUint32(valueOffset + 8*n, !bigEnd);
  1900. denominator = file.getUint32(valueOffset+4 + 8*n, !bigEnd);
  1901. vals[n] = new Number(numerator / denominator);
  1902. vals[n].numerator = numerator;
  1903. vals[n].denominator = denominator;
  1904. }
  1905. return vals;
  1906. }
  1907.  
  1908. case 9: // slong, 32 bit signed int
  1909. if (numValues == 1) {
  1910. return file.getInt32(entryOffset + 8, !bigEnd);
  1911. } else {
  1912. vals = [];
  1913. for (n=0;n<numValues;n++) {
  1914. vals[n] = file.getInt32(valueOffset + 4*n, !bigEnd);
  1915. }
  1916. return vals;
  1917. }
  1918.  
  1919. case 10: // signed rational, two slongs, first is numerator, second is denominator
  1920. if (numValues == 1) {
  1921. return file.getInt32(valueOffset, !bigEnd) / file.getInt32(valueOffset+4, !bigEnd);
  1922. } else {
  1923. vals = [];
  1924. for (n=0;n<numValues;n++) {
  1925. vals[n] = file.getInt32(valueOffset + 8*n, !bigEnd) / file.getInt32(valueOffset+4 + 8*n, !bigEnd);
  1926. }
  1927. return vals;
  1928. }
  1929. }
  1930. }
  1931.  
  1932. function getStringFromDB(buffer, start, length) {
  1933. var outstr = "";
  1934. for (n = start; n < start+length; n++) {
  1935. outstr += String.fromCharCode(buffer.getUint8(n));
  1936. }
  1937. return outstr;
  1938. }
  1939.  
  1940. function readEXIFData(file, start) {
  1941. if (getStringFromDB(file, start, 4) != "Exif") {
  1942. if (debug) console.log("Not valid EXIF data! " + getStringFromDB(file, start, 4));
  1943. return false;
  1944. }
  1945.  
  1946. var bigEnd,
  1947. tags, tag,
  1948. exifData, gpsData,
  1949. tiffOffset = start + 6;
  1950.  
  1951. // test for TIFF validity and endianness
  1952. if (file.getUint16(tiffOffset) == 0x4949) {
  1953. bigEnd = false;
  1954. } else if (file.getUint16(tiffOffset) == 0x4D4D) {
  1955. bigEnd = true;
  1956. } else {
  1957. if (debug) console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)");
  1958. return false;
  1959. }
  1960.  
  1961. if (file.getUint16(tiffOffset+2, !bigEnd) != 0x002A) {
  1962. if (debug) console.log("Not valid TIFF data! (no 0x002A)");
  1963. return false;
  1964. }
  1965.  
  1966. var firstIFDOffset = file.getUint32(tiffOffset+4, !bigEnd);
  1967.  
  1968. if (firstIFDOffset < 0x00000008) {
  1969. if (debug) console.log("Not valid TIFF data! (First offset less than 8)", file.getUint32(tiffOffset+4, !bigEnd));
  1970. return false;
  1971. }
  1972.  
  1973. tags = readTags(file, tiffOffset, tiffOffset + firstIFDOffset, TiffTags, bigEnd);
  1974.  
  1975. if (tags.ExifIFDPointer) {
  1976. exifData = readTags(file, tiffOffset, tiffOffset + tags.ExifIFDPointer, ExifTags, bigEnd);
  1977. for (tag in exifData) {
  1978. switch (tag) {
  1979. case "LightSource" :
  1980. case "Flash" :
  1981. case "MeteringMode" :
  1982. case "ExposureProgram" :
  1983. case "SensingMethod" :
  1984. case "SceneCaptureType" :
  1985. case "SceneType" :
  1986. case "CustomRendered" :
  1987. case "WhiteBalance" :
  1988. case "GainControl" :
  1989. case "Contrast" :
  1990. case "Saturation" :
  1991. case "Sharpness" :
  1992. case "SubjectDistanceRange" :
  1993. case "FileSource" :
  1994. exifData[tag] = StringValues[tag][exifData[tag]];
  1995. break;
  1996.  
  1997. case "ExifVersion" :
  1998. case "FlashpixVersion" :
  1999. exifData[tag] = String.fromCharCode(exifData[tag][0], exifData[tag][1], exifData[tag][2], exifData[tag][3]);
  2000. break;
  2001.  
  2002. case "ComponentsConfiguration" :
  2003. exifData[tag] =
  2004. StringValues.Components[exifData[tag][0]] +
  2005. StringValues.Components[exifData[tag][1]] +
  2006. StringValues.Components[exifData[tag][2]] +
  2007. StringValues.Components[exifData[tag][3]];
  2008. break;
  2009. }
  2010. tags[tag] = exifData[tag];
  2011. }
  2012. }
  2013.  
  2014. if (tags.GPSInfoIFDPointer) {
  2015. gpsData = readTags(file, tiffOffset, tiffOffset + tags.GPSInfoIFDPointer, GPSTags, bigEnd);
  2016. for (tag in gpsData) {
  2017. switch (tag) {
  2018. case "GPSVersionID" :
  2019. gpsData[tag] = gpsData[tag][0] +
  2020. "." + gpsData[tag][1] +
  2021. "." + gpsData[tag][2] +
  2022. "." + gpsData[tag][3];
  2023. break;
  2024. }
  2025. tags[tag] = gpsData[tag];
  2026. }
  2027. }
  2028.  
  2029. return tags;
  2030. }
  2031.  
  2032. EXIF.getData = function(img, callback) {
  2033. if ((img instanceof Image || img instanceof HTMLImageElement) && !img.complete) return false;
  2034.  
  2035. if (!imageHasData(img)) {
  2036. getImageData(img, callback);
  2037. } else {
  2038. if (callback) {
  2039. callback.call(img);
  2040. }
  2041. }
  2042. return true;
  2043. }
  2044.  
  2045. EXIF.getTag = function(img, tag) {
  2046. if (!imageHasData(img)) return;
  2047. return img.exifdata[tag];
  2048. }
  2049.  
  2050. EXIF.getAllTags = function(img) {
  2051. if (!imageHasData(img)) return {};
  2052. var a,
  2053. data = img.exifdata,
  2054. tags = {};
  2055. for (a in data) {
  2056. if (data.hasOwnProperty(a)) {
  2057. tags[a] = data[a];
  2058. }
  2059. }
  2060. return tags;
  2061. }
  2062.  
  2063. EXIF.pretty = function(img) {
  2064. if (!imageHasData(img)) return "";
  2065. var a,
  2066. data = img.exifdata,
  2067. strPretty = "";
  2068. for (a in data) {
  2069. if (data.hasOwnProperty(a)) {
  2070. if (typeof data[a] == "object") {
  2071. if (data[a] instanceof Number) {
  2072. strPretty += a + " : " + data[a] + " [" + data[a].numerator + "/" + data[a].denominator + "]\r\n";
  2073. } else {
  2074. strPretty += a + " : [" + data[a].length + " values]\r\n";
  2075. }
  2076. } else {
  2077. strPretty += a + " : " + data[a] + "\r\n";
  2078. }
  2079. }
  2080. }
  2081. return strPretty;
  2082. }
  2083.  
  2084. EXIF.readFromBinaryFile = function(file) {
  2085. return findEXIFinJPEG(file);
  2086. }
  2087.  
  2088. if (typeof define === 'function' && define.amd) {
  2089. define('exif-js', [], function() {
  2090. return EXIF;
  2091. });
  2092. }
  2093. }.call(this));
  2094. // -- https://github.com/exif-js/exif-js