Geocaching.com + Project-GC

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

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

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