Geocaching.com + Project-GC

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

As of 2017-09-18. See the latest version.

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