Geocaching.com + Project-GC

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

2017-11-20 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

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